//! 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 cursor index. pub fn apply_directive_completion( body: &mut String, at_index: usize, cursor: usize, completed: &str, ) -> usize { let replace_start = at_index + 1; let cursor = cursor.min(body.len()); let replace_start = replace_start.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 names = BTreeSet::new(); if let Ok(doc) = crate::dsl::parse(source) { for name in crate::params::collect_parameter_names(&doc) { names.insert(name); } } for preset in [ "DocumentNumber", "Data", "Name", "StoreName", "Total", "OrderId", "Date", "Time", ] { names.insert(preset.to_string()); } names .into_iter() .map(|name| InsertOption { label: format!("${{{name}}}"), snippet: format!("${{{name}}}"), }) .collect() } /// If the cursor is after `@` on the current line, return (start_index, typed_prefix). pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> { let cursor = 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; } Some((line_start + at, fragment.to_string())) } pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize) { let cursor = 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 inserts_snippet() { let (text, cur) = insert_at_cursor("ab", 1, "X"); assert_eq!(text, "aXb"); assert_eq!(cur, 2); } }