BlueGit

timfa posprint

Files

posprint / src / editor_assist.rs

editor_assist.rs

editor_assist.rs 8.1 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 cursor index.
68pub fn apply_directive_completion(
69 body: &mut String,
70 at_index: usize,
71 cursor: usize,
72 completed: &str,
73) -> usize {
74 let replace_start = at_index + 1;
75 let cursor = cursor.min(body.len());
76 let replace_start = replace_start.min(cursor);
77 body.replace_range(replace_start..cursor, completed);
78 at_index + 1 + completed.len()
79}
80
81pub struct InsertOption {
82 pub label: String,
83 pub snippet: String,
84}
85
86pub fn image_insert_options() -> Vec<InsertOption> {
87 vec![InsertOption {
88 label: "Image from file".into(),
89 snippet: "@image logo.png\n".into(),
90 }]
91}
92
93pub fn barcode_insert_options() -> Vec<InsertOption> {
94 let mut out = Vec::new();
95 for &sym in crate::dsl::BarcodeSymbology::ALL {
96 if sym.supports_native() {
97 out.push(InsertOption {
98 label: format!("Native {}", sym.as_str()),
99 snippet: format!("@barcode {} ${{Data}}\n", sym.as_str()),
100 });
101 }
102 }
103 for &sym in crate::dsl::BarcodeSymbology::ALL {
104 out.push(InsertOption {
105 label: format!("Raster {}", sym.as_str()),
106 snippet: format!("@barcode RASTER {} ${{Data}}\n", sym.as_str()),
107 });
108 }
109 out
110}
111
112pub fn qr_insert_options() -> Vec<InsertOption> {
113 vec![
114 InsertOption {
115 label: "Native QR (ESC/POS)".into(),
116 snippet: "@qr ${Data}\n".into(),
117 },
118 InsertOption {
119 label: "Raster QR (auto version)".into(),
120 snippet: "@qr RASTER ${Data} scale=4 ecc=M\n".into(),
121 },
122 InsertOption {
123 label: "Raster QR (version 5)".into(),
124 snippet: "@qr RASTER ${Data} version=5 scale=4 ecc=M\n".into(),
125 },
126 ]
127}
128
129pub fn date_time_insert_options() -> Vec<InsertOption> {
130 vec![
131 InsertOption {
132 label: "@date (regional)".into(),
133 snippet: "@date\n".into(),
134 },
135 InsertOption {
136 label: "@date DD-YYYY-MM".into(),
137 snippet: "@date DD-YYYY-MM\n".into(),
138 },
139 InsertOption {
140 label: "@date MMMM DD".into(),
141 snippet: "@date MMMM DD\n".into(),
142 },
143 InsertOption {
144 label: "@time (24h)".into(),
145 snippet: "@time\n".into(),
146 },
147 InsertOption {
148 label: "@time 12h".into(),
149 snippet: "@time 12h\n".into(),
150 },
151 InsertOption {
152 label: "@time 24h".into(),
153 snippet: "@time 24h\n".into(),
154 },
155 ]
156}
157
158pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
159 use std::collections::BTreeSet;
160
161 let mut text_names = BTreeSet::new();
162 let mut bool_names = BTreeSet::new();
163 if let Ok(doc) = crate::dsl::parse(source) {
164 for spec in crate::params::collect_parameters(&doc) {
165 match spec.kind {
166 crate::params::ParamKind::Text => {
167 text_names.insert(spec.name);
168 }
169 crate::params::ParamKind::Bool => {
170 bool_names.insert(spec.name);
171 }
172 }
173 }
174 }
175 for preset in [
176 "DocumentNumber",
177 "Data",
178 "Name",
179 "StoreName",
180 "Total",
181 "OrderId",
182 "Date",
183 "Time",
184 ] {
185 text_names.insert(preset.to_string());
186 }
187 for preset in ["Paid", "Done", "Checked"] {
188 bool_names.insert(preset.to_string());
189 }
190
191 let mut out = Vec::new();
192 for name in text_names {
193 out.push(InsertOption {
194 label: format!("${{{name}}}"),
195 snippet: format!("${{{name}}}"),
196 });
197 }
198 for name in bool_names {
199 out.push(InsertOption {
200 label: format!("$[{name}]"),
201 snippet: format!("$[{name}]"),
202 });
203 }
204 out
205}
206
207/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
208pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> {
209 let cursor = cursor.min(body.len());
210 let before = &body[..cursor];
211 let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
212 let line = &before[line_start..];
213 let at = line.find('@')?;
214 if at > 0 && !line[..at].trim().is_empty() {
215 return None;
216 }
217 let fragment = &line[at + 1..];
218 if fragment.contains(' ') {
219 return None;
220 }
221 Some((line_start + at, fragment.to_string()))
222}
223
224pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize) {
225 let cursor = cursor.min(body.len());
226 let mut out = String::with_capacity(body.len() + text.len());
227 out.push_str(&body[..cursor]);
228 out.push_str(text);
229 out.push_str(&body[cursor..]);
230 let new_cursor = cursor + text.len();
231 (out, new_cursor)
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 #[test]
239 fn ghost_suffix_for_partial_directive() {
240 assert_eq!(directive_ghost_suffix("ba"), Some("rcode".into()));
241 }
242
243 #[test]
244 fn ghost_suffix_none_when_ambiguous() {
245 assert!(directive_ghost_suffix("").is_none());
246 }
247
248 #[test]
249 fn completes_directive_on_tab() {
250 assert_eq!(complete_directive("ba"), Some("barcode"));
251 }
252
253 #[test]
254 fn applies_directive_completion() {
255 let mut body = "hello\n@ba".to_string();
256 let end = body.len();
257 let cursor = apply_directive_completion(&mut body, 6, end, "barcode");
258 assert_eq!(body, "hello\n@barcode");
259 assert_eq!(cursor, 6 + 1 + "barcode".len());
260 }
261
262 #[test]
263 fn completes_directives() {
264 let hits = directive_completions("ba");
265 assert!(hits.contains(&"barcode"));
266 }
267
268 #[test]
269 fn detects_at_prefix() {
270 let body = "hello\n@bar";
271 let (start, frag) = at_directive_prefix(body, body.len()).unwrap();
272 assert_eq!(start, 6);
273 assert_eq!(frag, "bar");
274 }
275
276 #[test]
277 fn inserts_snippet() {
278 let (text, cur) = insert_at_cursor("ab", 1, "X");
279 assert_eq!(text, "aXb");
280 assert_eq!(cur, 2);
281 }
282}