BlueGit

timfa posprint

Files

posprint / src / editor_assist.rs

editor_assist.rs

editor_assist.rs 10.8 KiB Download Raw
1//! Editor snippets, directive autocomplete, and insert helpers.
2
3pub const DIRECTIVES: &[&str] = &["feed", "cut", "image", "barcode", "qr", "date", "time"];
4
5pub fn directive_completions(prefix: &str) -> Vec<&'static str> {
6 let p = prefix.to_ascii_lowercase();
7 DIRECTIVES
8 .iter()
9 .copied()
10 .filter(|d| d.starts_with(&p))
11 .collect()
12}
13
14/// Transparent continuation shown after the typed `@` prefix (e.g. `ba` → `rcode`).
15pub fn directive_ghost_suffix(prefix: &str) -> Option<String> {
16 let matches = directive_completions(prefix);
17 let full = match matches.len() {
18 0 => return None,
19 1 => matches[0],
20 _ => longest_common_prefix(&matches)?,
21 };
22 if full.len() > prefix.len() {
23 Some(full[prefix.len()..].to_string())
24 } else {
25 None
26 }
27}
28
29/// Full directive name to insert when the user presses Tab.
30pub fn complete_directive(prefix: &str) -> Option<&'static str> {
31 let matches = directive_completions(prefix);
32 match matches.len() {
33 0 => None,
34 1 => Some(matches[0]),
35 _ => {
36 let common = longest_common_prefix(&matches)?;
37 if common.len() > prefix.len() {
38 Some(common)
39 } else {
40 Some(matches[0])
41 }
42 }
43 }
44}
45
46fn longest_common_prefix(matches: &[&'static str]) -> Option<&'static str> {
47 if matches.is_empty() {
48 return None;
49 }
50 let mut common = matches[0];
51 for candidate in &matches[1..] {
52 let mut len = 0;
53 while len < common.len()
54 && len < candidate.len()
55 && common.as_bytes()[len] == candidate.as_bytes()[len]
56 {
57 len += 1;
58 }
59 common = &common[..len];
60 if common.is_empty() {
61 return None;
62 }
63 }
64 Some(common)
65}
66
67/// Replace the partial directive after `@` with `completed`; returns new byte cursor.
68pub fn apply_directive_completion(
69 body: &mut String,
70 at_index: usize,
71 cursor: usize,
72 completed: &str,
73) -> usize {
74 let cursor = floor_char_boundary(body, cursor.min(body.len()));
75 let replace_start = floor_char_boundary(body, (at_index + 1).min(cursor));
76 body.replace_range(replace_start..cursor, completed);
77 at_index + 1 + completed.len()
78}
79
80pub struct InsertOption {
81 pub label: String,
82 pub snippet: String,
83}
84
85pub fn image_insert_options() -> Vec<InsertOption> {
86 vec![InsertOption {
87 label: "Image from file".into(),
88 snippet: "@image logo.png\n".into(),
89 }]
90}
91
92pub fn barcode_insert_options() -> Vec<InsertOption> {
93 let mut out = Vec::new();
94 for &sym in crate::dsl::BarcodeSymbology::ALL {
95 if sym.supports_native() {
96 out.push(InsertOption {
97 label: format!("Native {}", sym.as_str()),
98 snippet: format!("@barcode {} ${{Data}}\n", sym.as_str()),
99 });
100 }
101 }
102 for &sym in crate::dsl::BarcodeSymbology::ALL {
103 out.push(InsertOption {
104 label: format!("Raster {}", sym.as_str()),
105 snippet: format!("@barcode RASTER {} ${{Data}}\n", sym.as_str()),
106 });
107 }
108 out
109}
110
111pub fn qr_insert_options() -> Vec<InsertOption> {
112 vec![
113 InsertOption {
114 label: "Native QR (ESC/POS)".into(),
115 snippet: "@qr ${Data}\n".into(),
116 },
117 InsertOption {
118 label: "Raster QR (auto version)".into(),
119 snippet: "@qr RASTER ${Data} scale=4 ecc=M\n".into(),
120 },
121 InsertOption {
122 label: "Raster QR (version 5)".into(),
123 snippet: "@qr RASTER ${Data} version=5 scale=4 ecc=M\n".into(),
124 },
125 ]
126}
127
128pub fn date_time_insert_options() -> Vec<InsertOption> {
129 vec![
130 InsertOption {
131 label: "@date (regional)".into(),
132 snippet: "@date\n".into(),
133 },
134 InsertOption {
135 label: "@date DD-YYYY-MM".into(),
136 snippet: "@date DD-YYYY-MM\n".into(),
137 },
138 InsertOption {
139 label: "@date MMMM DD".into(),
140 snippet: "@date MMMM DD\n".into(),
141 },
142 InsertOption {
143 label: "@time (24h)".into(),
144 snippet: "@time\n".into(),
145 },
146 InsertOption {
147 label: "@time 12h".into(),
148 snippet: "@time 12h\n".into(),
149 },
150 InsertOption {
151 label: "@time 24h".into(),
152 snippet: "@time 24h\n".into(),
153 },
154 ]
155}
156
157pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
158 use std::collections::BTreeSet;
159
160 let mut text_names = BTreeSet::new();
161 let mut bool_names = BTreeSet::new();
162 if let Ok(doc) = crate::dsl::parse(source) {
163 for spec in crate::params::collect_parameters(&doc) {
164 match spec.kind {
165 crate::params::ParamKind::Text => {
166 text_names.insert(spec.name);
167 }
168 crate::params::ParamKind::Bool => {
169 bool_names.insert(spec.name);
170 }
171 }
172 }
173 }
174 for preset in [
175 "DocumentNumber",
176 "Data",
177 "Name",
178 "StoreName",
179 "Total",
180 "OrderId",
181 "Date",
182 "Time",
183 ] {
184 text_names.insert(preset.to_string());
185 }
186 for preset in ["Paid", "Done", "Checked"] {
187 bool_names.insert(preset.to_string());
188 }
189
190 let mut out = Vec::new();
191 for name in text_names {
192 out.push(InsertOption {
193 label: format!("${{{name}}}"),
194 snippet: format!("${{{name}}}"),
195 });
196 }
197 for name in bool_names {
198 out.push(InsertOption {
199 label: format!("$[{name}]"),
200 snippet: format!("$[{name}]"),
201 });
202 }
203 out
204}
205
206/// Convert an egui `CCursor` character index to a UTF-8 byte offset in `s`.
207pub fn char_index_to_byte(s: &str, char_index: usize) -> usize {
208 s.char_indices()
209 .nth(char_index)
210 .map(|(i, _)| i)
211 .unwrap_or(s.len())
212}
213
214/// Convert a UTF-8 byte offset to an egui `CCursor` character index.
215pub fn byte_index_to_char(s: &str, byte_index: usize) -> usize {
216 let byte_index = floor_char_boundary(s, byte_index.min(s.len()));
217 s[..byte_index].chars().count()
218}
219
220/// Clamp `index` down to the nearest char boundary (avoids UTF-8 slice panics).
221pub fn floor_char_boundary(s: &str, mut index: usize) -> usize {
222 if index >= s.len() {
223 return s.len();
224 }
225 while index > 0 && !s.is_char_boundary(index) {
226 index -= 1;
227 }
228 index
229}
230
231/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
232/// `cursor` is a UTF-8 **byte** offset.
233///
234/// Only letter prefixes are treated as directive autocomplete (so pasting a URL
235/// like `https://…` after `@`, or any non-directive junk, does not lock the editor).
236pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> {
237 let cursor = floor_char_boundary(body, cursor.min(body.len()));
238 let before = &body[..cursor];
239 let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
240 let line = &before[line_start..];
241 let at = line.find('@')?;
242 if at > 0 && !line[..at].trim().is_empty() {
243 return None;
244 }
245 let fragment = &line[at + 1..];
246 if fragment.contains(' ') {
247 return None;
248 }
249 if !fragment.chars().all(|c| c.is_ascii_alphabetic()) {
250 return None;
251 }
252 // Bound prefix length to longest directive name; longer text is not a directive.
253 if fragment.len() > DIRECTIVES.iter().map(|d| d.len()).max().unwrap_or(0) {
254 return None;
255 }
256 Some((line_start + at, fragment.to_string()))
257}
258
259/// Insert `text` at a UTF-8 **byte** cursor offset; returns new body and cursor.
260pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize) {
261 let cursor = floor_char_boundary(body, cursor.min(body.len()));
262 let mut out = String::with_capacity(body.len() + text.len());
263 out.push_str(&body[..cursor]);
264 out.push_str(text);
265 out.push_str(&body[cursor..]);
266 let new_cursor = cursor + text.len();
267 (out, new_cursor)
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 #[test]
275 fn ghost_suffix_for_partial_directive() {
276 assert_eq!(directive_ghost_suffix("ba"), Some("rcode".into()));
277 }
278
279 #[test]
280 fn ghost_suffix_none_when_ambiguous() {
281 assert!(directive_ghost_suffix("").is_none());
282 }
283
284 #[test]
285 fn completes_directive_on_tab() {
286 assert_eq!(complete_directive("ba"), Some("barcode"));
287 }
288
289 #[test]
290 fn applies_directive_completion() {
291 let mut body = "hello\n@ba".to_string();
292 let end = body.len();
293 let cursor = apply_directive_completion(&mut body, 6, end, "barcode");
294 assert_eq!(body, "hello\n@barcode");
295 assert_eq!(cursor, 6 + 1 + "barcode".len());
296 }
297
298 #[test]
299 fn completes_directives() {
300 let hits = directive_completions("ba");
301 assert!(hits.contains(&"barcode"));
302 }
303
304 #[test]
305 fn detects_at_prefix() {
306 let body = "hello\n@bar";
307 let (start, frag) = at_directive_prefix(body, body.len()).unwrap();
308 assert_eq!(start, 6);
309 assert_eq!(frag, "bar");
310 }
311
312 #[test]
313 fn url_after_at_is_not_directive_prefix() {
314 let body = "@https://www.youtube.com/watch?v=9gIMZ0WyY88";
315 assert!(at_directive_prefix(body, body.len()).is_none());
316 }
317
318 #[test]
319 fn long_letter_prefix_is_not_directive() {
320 let body = "@notadirectivename";
321 assert!(at_directive_prefix(body, body.len()).is_none());
322 }
323
324 #[test]
325 fn inserts_snippet() {
326 let (text, cur) = insert_at_cursor("ab", 1, "X");
327 assert_eq!(text, "aXb");
328 assert_eq!(cur, 2);
329 }
330
331 #[test]
332 fn char_index_to_byte_handles_multibyte() {
333 let s = format!("a{}b", '\u{221A}'); // three UTF-8 bytes
334 assert_eq!(s.len(), 5);
335 assert_eq!(char_index_to_byte(&s, 0), 0);
336 assert_eq!(char_index_to_byte(&s, 1), 1);
337 assert_eq!(char_index_to_byte(&s, 2), 4);
338 assert_eq!(char_index_to_byte(&s, 3), 5);
339 assert_eq!(char_index_to_byte(&s, 99), 5);
340 assert_eq!(byte_index_to_char(&s, 0), 0);
341 assert_eq!(byte_index_to_char(&s, 1), 1);
342 assert_eq!(byte_index_to_char(&s, 4), 2);
343 assert_eq!(byte_index_to_char(&s, 5), 3);
344 }
345
346 #[test]
347 fn floor_char_boundary_avoids_mid_glyph() {
348 let s = format!("a{}b", '\u{221A}');
349 assert_eq!(floor_char_boundary(&s, 2), 1);
350 assert_eq!(floor_char_boundary(&s, 3), 1);
351 assert_eq!(floor_char_boundary(&s, 4), 4);
352 }
353
354 #[test]
355 fn insert_and_prefix_survive_sqrt_cursor_misalign() {
356 let body = format!("[{}] done", '\u{221A}');
357 // Deliberately pass a mid-character byte index (inside sqrt glyph).
358 let (text, cur) = insert_at_cursor(&body, 2, "!");
359 assert!(text.contains('!'));
360 assert!(text.is_char_boundary(cur));
361 assert!(at_directive_prefix(&body, 2).is_none());
362 }
363}