BlueGit

timfa posprint

Files

posprint / src / editor_assist.rs

editor_assist.rs

checkboxes
timfa Tim Falken · pushed by timfa · 4 months ago
00ee9454 History
editor_assist.rs 9.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/// Clamp `index` down to the nearest char boundary (avoids UTF-8 slice panics).
215pub fn floor_char_boundary(s: &str, mut index: usize) -> usize {
216 if index >= s.len() {
217 return s.len();
218 }
219 while index > 0 && !s.is_char_boundary(index) {
220 index -= 1;
221 }
222 index
223}
224
225/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
226/// `cursor` is a UTF-8 **byte** offset.
227pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> {
228 let cursor = floor_char_boundary(body, cursor.min(body.len()));
229 let before = &body[..cursor];
230 let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
231 let line = &before[line_start..];
232 let at = line.find('@')?;
233 if at > 0 && !line[..at].trim().is_empty() {
234 return None;
235 }
236 let fragment = &line[at + 1..];
237 if fragment.contains(' ') {
238 return None;
239 }
240 Some((line_start + at, fragment.to_string()))
241}
242
243/// Insert `text` at a UTF-8 **byte** cursor offset; returns new body and cursor.
244pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize) {
245 let cursor = floor_char_boundary(body, cursor.min(body.len()));
246 let mut out = String::with_capacity(body.len() + text.len());
247 out.push_str(&body[..cursor]);
248 out.push_str(text);
249 out.push_str(&body[cursor..]);
250 let new_cursor = cursor + text.len();
251 (out, new_cursor)
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
259 fn ghost_suffix_for_partial_directive() {
260 assert_eq!(directive_ghost_suffix("ba"), Some("rcode".into()));
261 }
262
263 #[test]
264 fn ghost_suffix_none_when_ambiguous() {
265 assert!(directive_ghost_suffix("").is_none());
266 }
267
268 #[test]
269 fn completes_directive_on_tab() {
270 assert_eq!(complete_directive("ba"), Some("barcode"));
271 }
272
273 #[test]
274 fn applies_directive_completion() {
275 let mut body = "hello\n@ba".to_string();
276 let end = body.len();
277 let cursor = apply_directive_completion(&mut body, 6, end, "barcode");
278 assert_eq!(body, "hello\n@barcode");
279 assert_eq!(cursor, 6 + 1 + "barcode".len());
280 }
281
282 #[test]
283 fn completes_directives() {
284 let hits = directive_completions("ba");
285 assert!(hits.contains(&"barcode"));
286 }
287
288 #[test]
289 fn detects_at_prefix() {
290 let body = "hello\n@bar";
291 let (start, frag) = at_directive_prefix(body, body.len()).unwrap();
292 assert_eq!(start, 6);
293 assert_eq!(frag, "bar");
294 }
295
296 #[test]
297 fn inserts_snippet() {
298 let (text, cur) = insert_at_cursor("ab", 1, "X");
299 assert_eq!(text, "aXb");
300 assert_eq!(cur, 2);
301 }
302
303 #[test]
304 fn char_index_to_byte_handles_multibyte() {
305 let s = "axb"; // x is U+221A, three UTF-8 bytes
306 assert_eq!(char_index_to_byte(s, 0), 0);
307 assert_eq!(char_index_to_byte(s, 1), 1);
308 assert_eq!(char_index_to_byte(s, 2), 4);
309 assert_eq!(char_index_to_byte(s, 3), 5);
310 assert_eq!(char_index_to_byte(s, 99), 5);
311 }
312
313 #[test]
314 fn floor_char_boundary_avoids_mid_glyph() {
315 let s = "axb";
316 assert_eq!(floor_char_boundary(s, 2), 1);
317 assert_eq!(floor_char_boundary(s, 3), 1);
318 assert_eq!(floor_char_boundary(s, 4), 4);
319 }
320
321 #[test]
322 fn insert_and_prefix_survive_sqrt_cursor_misalign() {
323 let body = "[\u{221A}] done";
324 // Deliberately pass a mid-character byte index (inside x).
325 let (text, cur) = insert_at_cursor(body, 2, "!");
326 assert!(text.contains('!'));
327 assert!(text.is_char_boundary(cur));
328 assert!(at_directive_prefix(body, 2).is_none());
329 }
330}