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