//! Editor snippets, directive autocomplete, and insert helpers. pub const DIRECTIVES: &[&str] = &["feed", "cut", "image", "barcode", "qr", "date", "time"]; pub fn directive_completions(prefix: &str) -> Vec<&'static str> { let p = prefix.to_ascii_lowercase(); DIRECTIVES .iter() .copied() .filter(|d| d.starts_with(&p)) .collect() } /// Transparent continuation shown after the typed `@` prefix (e.g. `ba` → `rcode`). pub fn directive_ghost_suffix(prefix: &str) -> Option { let matches = directive_completions(prefix); let full = match matches.len() { 0 => return None, 1 => matches[0], _ => longest_common_prefix(&matches)?, }; if full.len() > prefix.len() { Some(full[prefix.len()..].to_string()) } else { None } } /// Full directive name to insert when the user presses Tab. pub fn complete_directive(prefix: &str) -> Option<&'static str> { let matches = directive_completions(prefix); match matches.len() { 0 => None, 1 => Some(matches[0]), _ => { let common = longest_common_prefix(&matches)?; if common.len() > prefix.len() { Some(common) } else { Some(matches[0]) } } } } fn longest_common_prefix(matches: &[&'static str]) -> Option<&'static str> { if matches.is_empty() { return None; } let mut common = matches[0]; for candidate in &matches[1..] { let mut len = 0; while len < common.len() && len < candidate.len() && common.as_bytes()[len] == candidate.as_bytes()[len] { len += 1; } common = &common[..len]; if common.is_empty() { return None; } } Some(common) } /// Replace the partial directive after `@` with `completed`; returns new byte cursor. pub fn apply_directive_completion( body: &mut String, at_index: usize, cursor: usize, completed: &str, ) -> usize { let cursor = floor_char_boundary(body, cursor.min(body.len())); let replace_start = floor_char_boundary(body, (at_index + 1).min(cursor)); body.replace_range(replace_start..cursor, completed); at_index + 1 + completed.len() } pub struct InsertOption { pub label: String, pub snippet: String, } pub fn image_insert_options() -> Vec { vec![InsertOption { label: "Image from file".into(), snippet: "@image logo.png\n".into(), }] } pub fn barcode_insert_options() -> Vec { let mut out = Vec::new(); for &sym in crate::dsl::BarcodeSymbology::ALL { if sym.supports_native() { out.push(InsertOption { label: format!("Native {}", sym.as_str()), snippet: format!("@barcode {} ${{Data}}\n", sym.as_str()), }); } } for &sym in crate::dsl::BarcodeSymbology::ALL { out.push(InsertOption { label: format!("Raster {}", sym.as_str()), snippet: format!("@barcode RASTER {} ${{Data}}\n", sym.as_str()), }); } out } pub fn qr_insert_options() -> Vec { vec![ InsertOption { label: "Native QR (ESC/POS)".into(), snippet: "@qr ${Data}\n".into(), }, InsertOption { label: "Raster QR (auto version)".into(), snippet: "@qr RASTER ${Data} scale=4 ecc=M\n".into(), }, InsertOption { label: "Raster QR (version 5)".into(), snippet: "@qr RASTER ${Data} version=5 scale=4 ecc=M\n".into(), }, ] } pub fn date_time_insert_options() -> Vec { vec![ InsertOption { label: "@date (regional)".into(), snippet: "@date\n".into(), }, InsertOption { label: "@date DD-YYYY-MM".into(), snippet: "@date DD-YYYY-MM\n".into(), }, InsertOption { label: "@date MMMM DD".into(), snippet: "@date MMMM DD\n".into(), }, InsertOption { label: "@time (24h)".into(), snippet: "@time\n".into(), }, InsertOption { label: "@time 12h".into(), snippet: "@time 12h\n".into(), }, InsertOption { label: "@time 24h".into(), snippet: "@time 24h\n".into(), }, ] } pub fn parameter_insert_options(source: &str) -> Vec { use std::collections::BTreeSet; let mut text_names = BTreeSet::new(); let mut bool_names = BTreeSet::new(); if let Ok(doc) = crate::dsl::parse(source) { for spec in crate::params::collect_parameters(&doc) { match spec.kind { crate::params::ParamKind::Text => { text_names.insert(spec.name); } crate::params::ParamKind::Bool => { bool_names.insert(spec.name); } } } } for preset in [ "DocumentNumber", "Data", "Name", "StoreName", "Total", "OrderId", "Date", "Time", ] { text_names.insert(preset.to_string()); } for preset in ["Paid", "Done", "Checked"] { bool_names.insert(preset.to_string()); } let mut out = Vec::new(); for name in text_names { out.push(InsertOption { label: format!("${{{name}}}"), snippet: format!("${{{name}}}"), }); } for name in bool_names { out.push(InsertOption { label: format!("$[{name}]"), snippet: format!("$[{name}]"), }); } out } /// Convert an egui `CCursor` character index to a UTF-8 byte offset in `s`. pub fn char_index_to_byte(s: &str, char_index: usize) -> usize { s.char_indices() .nth(char_index) .map(|(i, _)| i) .unwrap_or(s.len()) } /// Convert a UTF-8 byte offset to an egui `CCursor` character index. pub fn byte_index_to_char(s: &str, byte_index: usize) -> usize { let byte_index = floor_char_boundary(s, byte_index.min(s.len())); s[..byte_index].chars().count() } /// Clamp `index` down to the nearest char boundary (avoids UTF-8 slice panics). pub fn floor_char_boundary(s: &str, mut index: usize) -> usize { if index >= s.len() { return s.len(); } while index > 0 && !s.is_char_boundary(index) { index -= 1; } index } /// If the cursor is after `@` on the current line, return (start_index, typed_prefix). /// `cursor` is a UTF-8 **byte** offset. /// /// Only letter prefixes are treated as directive autocomplete (so pasting a URL /// like `https://…` after `@`, or any non-directive junk, does not lock the editor). pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> { let cursor = floor_char_boundary(body, cursor.min(body.len())); let before = &body[..cursor]; let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0); let line = &before[line_start..]; let at = line.find('@')?; if at > 0 && !line[..at].trim().is_empty() { return None; } let fragment = &line[at + 1..]; if fragment.contains(' ') { return None; } if !fragment.chars().all(|c| c.is_ascii_alphabetic()) { return None; } // Bound prefix length to longest directive name; longer text is not a directive. if fragment.len() > DIRECTIVES.iter().map(|d| d.len()).max().unwrap_or(0) { return None; } Some((line_start + at, fragment.to_string())) } /// Insert `text` at a UTF-8 **byte** cursor offset; returns new body and cursor. pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize) { let cursor = floor_char_boundary(body, cursor.min(body.len())); let mut out = String::with_capacity(body.len() + text.len()); out.push_str(&body[..cursor]); out.push_str(text); out.push_str(&body[cursor..]); let new_cursor = cursor + text.len(); (out, new_cursor) } #[cfg(test)] mod tests { use super::*; #[test] fn ghost_suffix_for_partial_directive() { assert_eq!(directive_ghost_suffix("ba"), Some("rcode".into())); } #[test] fn ghost_suffix_none_when_ambiguous() { assert!(directive_ghost_suffix("").is_none()); } #[test] fn completes_directive_on_tab() { assert_eq!(complete_directive("ba"), Some("barcode")); } #[test] fn applies_directive_completion() { let mut body = "hello\n@ba".to_string(); let end = body.len(); let cursor = apply_directive_completion(&mut body, 6, end, "barcode"); assert_eq!(body, "hello\n@barcode"); assert_eq!(cursor, 6 + 1 + "barcode".len()); } #[test] fn completes_directives() { let hits = directive_completions("ba"); assert!(hits.contains(&"barcode")); } #[test] fn detects_at_prefix() { let body = "hello\n@bar"; let (start, frag) = at_directive_prefix(body, body.len()).unwrap(); assert_eq!(start, 6); assert_eq!(frag, "bar"); } #[test] fn url_after_at_is_not_directive_prefix() { let body = "@https://www.youtube.com/watch?v=9gIMZ0WyY88"; assert!(at_directive_prefix(body, body.len()).is_none()); } #[test] fn long_letter_prefix_is_not_directive() { let body = "@notadirectivename"; assert!(at_directive_prefix(body, body.len()).is_none()); } #[test] fn inserts_snippet() { let (text, cur) = insert_at_cursor("ab", 1, "X"); assert_eq!(text, "aXb"); assert_eq!(cur, 2); } #[test] fn char_index_to_byte_handles_multibyte() { let s = format!("a{}b", '\u{221A}'); // three UTF-8 bytes assert_eq!(s.len(), 5); assert_eq!(char_index_to_byte(&s, 0), 0); assert_eq!(char_index_to_byte(&s, 1), 1); assert_eq!(char_index_to_byte(&s, 2), 4); assert_eq!(char_index_to_byte(&s, 3), 5); assert_eq!(char_index_to_byte(&s, 99), 5); assert_eq!(byte_index_to_char(&s, 0), 0); assert_eq!(byte_index_to_char(&s, 1), 1); assert_eq!(byte_index_to_char(&s, 4), 2); assert_eq!(byte_index_to_char(&s, 5), 3); } #[test] fn floor_char_boundary_avoids_mid_glyph() { let s = format!("a{}b", '\u{221A}'); assert_eq!(floor_char_boundary(&s, 2), 1); assert_eq!(floor_char_boundary(&s, 3), 1); assert_eq!(floor_char_boundary(&s, 4), 4); } #[test] fn insert_and_prefix_survive_sqrt_cursor_misalign() { let body = format!("[{}] done", '\u{221A}'); // Deliberately pass a mid-character byte index (inside sqrt glyph). let (text, cur) = insert_at_cursor(&body, 2, "!"); assert!(text.contains('!')); assert!(text.is_char_boundary(cur)); assert!(at_directive_prefix(&body, 2).is_none()); } }