use super::{ Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ListItem, ParseError, QrEcc, QrMode, }; pub fn parse(source: &str) -> Result { let source = strip_comments(source); let mut blocks = Vec::new(); let mut lines = source.lines().peekable(); let mut line_no = 0usize; let mut current_align = Align::Left; while let Some(raw_line) = lines.next() { line_no += 1; let line = raw_line.trim_end(); let (content, align_for_block) = match parse_align_line(line) { Some((align, None)) => { current_align = align; continue; } Some((align, Some(rest))) => { current_align = align; (rest, current_align) } None => (line, current_align), }; if is_blank_feed_line(content) { blocks.push(Block::Feed(1)); continue; } let segments = split_aligned_segments(content, align_for_block); if segments.is_empty() { continue; } // Same-line multi-align plain text → one AlignedRow (space-padded at print time). if segments.len() > 1 && segments .iter() .all(|(_, seg_text)| is_plain_paragraph_segment(seg_text)) { let mut parts = Vec::with_capacity(segments.len()); for (seg_align, seg_text) in &segments { current_align = *seg_align; parts.push((*seg_align, parse_inlines(seg_text, line_no, 1)?)); } blocks.push(Block::AlignedRow { parts }); continue; } for (idx, (seg_align, seg_text)) in segments.iter().enumerate() { current_align = *seg_align; let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1; if is_blank_feed_line(seg_text) { blocks.push(Block::Feed(1)); continue; } if seg_text.starts_with('#') { blocks.push(parse_heading(seg_text, line_no, *seg_align)?); continue; } if seg_text.trim() == "---" { blocks.push(Block::Rule); continue; } if seg_text.trim_start().starts_with("@") { blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?); continue; } if is_list_item_line(seg_text) { let mut items = vec![parse_list_item(seg_text, line_no)?]; while let Some(&next) = lines.peek() { if is_blank_feed_line(next) || next.starts_with('#') || next.trim() == "---" || next.trim_start().starts_with('@') || parse_align_line(next).is_some() || !is_list_item_line(next.trim_end()) { break; } line_no += 1; let next_line = lines.next().unwrap().trim_end(); items.push(parse_list_item(next_line, line_no)?); } blocks.push(Block::List { align: *seg_align, items, }); continue; } if allow_multiline_paragraph { let mut paragraph_lines = vec![seg_text.clone()]; while let Some(&next) = lines.peek() { if is_blank_feed_line(next) || next.starts_with('#') || next.trim() == "---" || next.trim_start().starts_with('@') || parse_align_line(next).is_some() || is_list_item_line(next.trim_end()) { break; } line_no += 1; lines.next(); paragraph_lines.push(next.trim_end().to_string()); } let text = paragraph_lines.join("\n"); blocks.push(Block::Paragraph { align: *seg_align, inlines: parse_inlines(&text, line_no, 1)?, }); } else { blocks.push(Block::Paragraph { align: *seg_align, inlines: parse_inlines(seg_text, line_no, 1)?, }); } } } let document = Document { blocks }; validate_param_kinds(&document)?; Ok(document) } fn validate_param_kinds(document: &Document) -> Result<(), ParseError> { use std::collections::BTreeSet; let mut text_names = BTreeSet::new(); let mut bool_names = BTreeSet::new(); for block in &document.blocks { collect_param_kinds_from_block(block, &mut text_names, &mut bool_names); } for name in text_names.intersection(&bool_names) { return Err(err( 1, 1, format!( "parameter '{name}' cannot be both ${{{name}}} (text) and $[{name}] (checkbox)" ), )); } Ok(()) } fn collect_param_kinds_from_block( block: &Block, text_names: &mut std::collections::BTreeSet, bool_names: &mut std::collections::BTreeSet, ) { match block { Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => { for inline in inlines { match inline { Inline::Param(name) => { text_names.insert(name.clone()); } Inline::CheckboxParam(name) => { bool_names.insert(name.clone()); } _ => {} } } } Block::AlignedRow { parts } => { for (_, inlines) in parts { for inline in inlines { match inline { Inline::Param(name) => { text_names.insert(name.clone()); } Inline::CheckboxParam(name) => { bool_names.insert(name.clone()); } _ => {} } } } } Block::List { items, .. } => { for item in items { for inline in &item.inlines { match inline { Inline::Param(name) => { text_names.insert(name.clone()); } Inline::CheckboxParam(name) => { bool_names.insert(name.clone()); } _ => {} } } } } Block::Image { path, .. } => collect_text_params_from_raw(path, text_names), Block::Barcode { data, .. } | Block::Qr { data, .. } => { collect_text_params_from_raw(data, text_names); } Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {} } } fn collect_text_params_from_raw(text: &str, text_names: &mut std::collections::BTreeSet) { let chars: Vec = text.chars().collect(); let mut i = 0; while i < chars.len() { if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' { let start = i + 2; let mut j = start; while j < chars.len() && chars[j] != '}' { j += 1; } if j < chars.len() { text_names.insert(chars[start..j].iter().collect()); i = j + 1; continue; } } i += 1; } } /// True when the last substantive block is `@cut` (trailing blank-line feeds are ignored). pub fn document_ends_with_cut(document: &Document) -> bool { for block in document.blocks.iter().rev() { match block { Block::Feed(_) => continue, Block::Cut => return true, _ => return false, } } false } fn strip_comments(source: &str) -> String { let mut out = String::with_capacity(source.len()); let mut chars = source.chars().peekable(); while let Some(ch) = chars.next() { if ch == '<' && chars.peek() == Some(&'!') { let mut rest: String = chars.clone().collect(); if rest.starts_with('!') { let _ = chars.next(); rest = chars.clone().collect(); if rest.starts_with("--") { for _ in 0..3 { chars.next(); } while let Some(c) = chars.next() { if c == '-' && chars.peek() == Some(&'-') { chars.next(); if chars.peek() == Some(&'>') { chars.next(); break; } } } continue; } } out.push('<'); } else { out.push(ch); } } out } /// True when a segment is ordinary paragraph text (eligible for AlignedRow). fn is_plain_paragraph_segment(seg_text: &str) -> bool { !is_blank_feed_line(seg_text) && !seg_text.starts_with('#') && seg_text.trim() != "---" && !seg_text.trim_start().starts_with('@') && !is_list_item_line(seg_text) } /// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start. /// Returns the alignment and optional remaining content on the same line. fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> { let trimmed = line.trim_start(); if let Some(rest) = trimmed.strip_prefix(":left:") { let rest = rest.trim_start(); return Some(( Align::Left, if rest.is_empty() { None } else { Some(rest) }, )); } if let Some(rest) = trimmed.strip_prefix(":center:") { let rest = rest.trim_start(); return Some(( Align::Center, if rest.is_empty() { None } else { Some(rest) }, )); } if let Some(rest) = trimmed.strip_prefix(":centre:") { let rest = rest.trim_start(); return Some(( Align::Center, if rest.is_empty() { None } else { Some(rest) }, )); } if let Some(rest) = trimmed.strip_prefix(":right:") { let rest = rest.trim_start(); return Some(( Align::Right, if rest.is_empty() { None } else { Some(rest) }, )); } None } /// Split line content on embedded `:left:`, `:center:`, `:centre:`, or `:right:` markers. /// Leading spaces in each segment are preserved (for manual indent); trailing spaces are trimmed. fn split_aligned_segments(content: &str, start_align: Align) -> Vec<(Align, String)> { let mut segments = Vec::new(); let mut align = start_align; let mut rest = content; while let Some((pos, new_align, marker_len)) = find_next_align_marker(rest) { let before = rest[..pos].trim_end(); if !before.trim().is_empty() { segments.push((align, before.to_string())); } align = new_align; rest = rest[pos + marker_len..].trim_start(); } let tail = rest.trim_end(); if !tail.trim().is_empty() { segments.push((align, tail.to_string())); } segments } fn find_next_align_marker(s: &str) -> Option<(usize, Align, usize)> { const MARKERS: &[(&str, Align)] = &[ (":left:", Align::Left), (":center:", Align::Center), (":centre:", Align::Center), (":right:", Align::Right), ]; let mut best: Option<(usize, Align, usize)> = None; for (pat, marker_align) in MARKERS { if let Some(pos) = s.find(pat) { if best.is_none() || pos < best.unwrap().0 { best = Some((pos, *marker_align, pat.len())); } } } best } /// True only when a line has no visible content (empty or whitespace-only). /// Lines with DSL markers (`:right:`, `@feed`, `#`, etc.) are never feed lines. fn is_blank_feed_line(line: &str) -> bool { line.chars().all(|c| c.is_whitespace()) } fn parse_heading(line: &str, line_no: usize, align: Align) -> Result { let mut level = 0u8; for ch in line.chars() { if ch == '#' { level += 1; } else { break; } } if level == 0 || level > 2 { return Err(err(line_no, 1, "heading must use # or ##")); } let text = line[level as usize..].trim(); if text.is_empty() { return Err(err(line_no, 1, "heading text is empty")); } Ok(Block::Heading { level, align, inlines: parse_inlines(text, line_no, level as usize + 1)?, }) } fn parse_directive(line: &str, line_no: usize, default_align: Align) -> Result { let body = line .trim_start() .strip_prefix('@') .ok_or_else(|| err(line_no, 1, "expected directive"))?; let mut parts = body.split_whitespace(); let name = parts.next().unwrap_or("").to_ascii_lowercase(); match name.as_str() { "feed" => { let n = parts .next() .ok_or_else(|| err(line_no, 1, "@feed requires line count"))?; let lines: u8 = n .parse() .map_err(|_| err(line_no, 1, "@feed count must be 0-255"))?; Ok(Block::Feed(lines)) } "cut" => Ok(Block::Cut), "image" => parse_image_directive(parts.collect(), line_no, default_align), "barcode" => parse_barcode_directive(parts.collect(), line_no, default_align), "qr" => parse_qr_directive(parts.collect(), line_no, default_align), "date" => parse_date_directive(parts.collect(), line_no, default_align), "time" => parse_time_directive(parts.collect(), line_no, default_align), _ => Err(err(line_no, 1, format!("unknown directive @{name}"))), } } fn parse_image_directive( parts: Vec<&str>, line_no: usize, default_align: Align, ) -> Result { if parts.is_empty() { return Err(err(line_no, 1, "@image requires a path")); } let path = parts[0].to_string(); let mut width = ImageWidth::Default; let mut align = default_align; for attr in &parts[1..] { if let Some((k, v)) = attr.split_once('=') { match k.to_ascii_lowercase().as_str() { "width" => { width = if let Some(p) = v.strip_suffix('%') { let pct: u8 = p .parse() .map_err(|_| err(line_no, 1, "invalid width percent"))?; ImageWidth::Percent(pct.min(100)) } else { let dots: u16 = v .parse() .map_err(|_| err(line_no, 1, "invalid width dots"))?; ImageWidth::Dots(dots) }; } "align" => align = parse_align_value(v, line_no)?, _ => return Err(err(line_no, 1, format!("unknown image attribute {k}"))), } } } Ok(Block::Image { path, width, align }) } fn parse_barcode_directive( parts: Vec<&str>, line_no: usize, default_align: Align, ) -> Result { if parts.len() < 2 { return Err(err( line_no, 1, "@barcode requires symbology and data (or RASTER symbology data)", )); } let (mode, sym_idx, data_idx) = if parts[0].eq_ignore_ascii_case("RASTER") { if parts.len() < 3 { return Err(err( line_no, 1, "@barcode RASTER requires symbology and data", )); } (BarcodeMode::Raster, 1, 2) } else { (BarcodeMode::Native, 0, 1) }; let symbology = BarcodeSymbology::from_name(parts[sym_idx]) .ok_or_else(|| err(line_no, 1, format!("unknown barcode symbology {}", parts[sym_idx])))?; if mode == BarcodeMode::Native && !symbology.supports_native() { return Err(err( line_no, 1, format!( "{} has no native ESC/POS support; use RASTER {}", symbology.as_str(), symbology.as_str() ), )); } let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@barcode")?; let mut height = 64u8; let mut align = default_align; // Default off: many printers print HRI under native barcodes otherwise. let mut show_text = false; for attr in attrs { if let Some((k, v)) = attr.split_once('=') { match k.to_ascii_lowercase().as_str() { "height" => { height = v .parse() .map_err(|_| err(line_no, 1, "invalid barcode height"))?; } "align" => align = parse_align_value(v, line_no)?, "show_text" => show_text = v == "true", _ => return Err(err(line_no, 1, format!("unknown barcode attribute {k}"))), } } else { return Err(err( line_no, 1, format!("unexpected barcode token '{attr}' (attributes use key=value)"), )); } } Ok(Block::Barcode { mode, symbology, data, height, align, show_text, }) } fn parse_date_directive( parts: Vec<&str>, _line_no: usize, default_align: Align, ) -> Result { let pattern = parts.join(" "); let format = if pattern.is_empty() { None } else { Some(pattern) }; Ok(Block::Date { format, align: default_align, }) } fn parse_time_directive( parts: Vec<&str>, line_no: usize, default_align: Align, ) -> Result { use super::TimeFormatSpec; let spec = match parts.first().map(|s| s.to_ascii_lowercase()).as_deref() { None => TimeFormatSpec::Hours24, Some("12h") => TimeFormatSpec::Hours12, Some("24h") => TimeFormatSpec::Hours24, Some(other) => { return Err(err( line_no, 1, format!("unknown @time format '{other}' (use 12h or 24h)"), )); } }; if parts.len() > 1 { return Err(err( line_no, 1, "@time accepts at most one format argument (12h or 24h)", )); } Ok(Block::Time { format: spec, align: default_align, }) } fn parse_qr_directive( parts: Vec<&str>, line_no: usize, default_align: Align, ) -> Result { if parts.is_empty() { return Err(err(line_no, 1, "@qr requires data")); } let (mode, data_idx) = if parts[0].eq_ignore_ascii_case("RASTER") { if parts.len() < 2 { return Err(err(line_no, 1, "@qr RASTER requires data")); } (QrMode::Raster, 1) } else { (QrMode::Native, 0) }; let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@qr")?; let mut size = 4u8; let mut ecc = QrEcc::M; let mut align = default_align; let mut version = None; for attr in attrs { if let Some((k, v)) = attr.split_once('=') { match k.to_ascii_lowercase().as_str() { "size" => { size = v .parse::() .map_err(|_| err(line_no, 1, "invalid qr size"))? .clamp(1, 16); } "scale" => { size = v .parse::() .map_err(|_| err(line_no, 1, "invalid qr scale"))? .clamp(1, 16); } "version" => { let ver: u8 = v .parse() .map_err(|_| err(line_no, 1, "invalid qr version"))?; if !(1..=40).contains(&ver) { return Err(err(line_no, 1, "qr version must be 1-40")); } version = Some(ver); } "ecc" => { ecc = QrEcc::from_name(v) .ok_or_else(|| err(line_no, 1, "qr ecc must be L, M, Q, or H"))?; } "align" => align = parse_align_value(v, line_no)?, _ => return Err(err(line_no, 1, format!("unknown qr attribute {k}"))), } } else { return Err(err( line_no, 1, format!("unexpected qr token '{attr}' (attributes use key=value)"), )); } } Ok(Block::Qr { mode, data, size, ecc, version, align, }) } fn parse_align_value(value: &str, line_no: usize) -> Result { match value.to_ascii_lowercase().as_str() { "left" => Ok(Align::Left), "center" | "centre" => Ok(Align::Center), "right" => Ok(Align::Right), _ => Err(err(line_no, 1, "align must be left, center, or right")), } } /// Collect data tokens from `data_idx` until the first `key=value` attribute. /// Remaining tokens are returned as attributes (must all be `key=value`). /// /// Tokens that contain `=` inside a URL/query (e.g. `https://x?a=1`) are still /// treated as data — only simple identifier keys count as attributes. fn take_data_tokens<'a>( parts: &'a [&str], data_idx: usize, line_no: usize, directive: &str, ) -> Result<(String, &'a [&'a str]), ParseError> { if data_idx >= parts.len() { return Err(err(line_no, 1, format!("{directive} requires data"))); } if looks_like_attribute_token(parts[data_idx]) { return Err(err( line_no, 1, format!("{directive} data cannot start with an attribute"), )); } let mut data_end = data_idx + 1; while data_end < parts.len() && !looks_like_attribute_token(parts[data_end]) { data_end += 1; } let data = parts[data_idx..data_end].join(" "); Ok((data, &parts[data_end..])) } /// True for tokens like `size=4` / `align=center`, false for URLs with `?a=1`. fn looks_like_attribute_token(token: &str) -> bool { let Some((key, _value)) = token.split_once('=') else { return false; }; if key.is_empty() { return false; } key.chars() .all(|c| c.is_ascii_alphanumeric() || c == '_') } fn is_list_item_line(line: &str) -> bool { line.trim_start().starts_with("- ") } /// Nesting depth from leading whitespace: two spaces (or one tab) per level. fn list_item_depth(line: &str) -> u8 { let mut spaces = 0u32; for ch in line.chars() { match ch { ' ' => spaces += 1, '\t' => spaces += 2, _ => break, } } spaces.div_euclid(2).min(u32::from(u8::MAX)) as u8 } fn list_item_text(line: &str) -> &str { line.trim_start() .strip_prefix("- ") .map(str::trim_end) .unwrap_or(line.trim_end()) } fn parse_list_item(line: &str, line_no: usize) -> Result { Ok(ListItem { depth: list_item_depth(line), inlines: parse_inlines(list_item_text(line), line_no, 1)?, }) } fn parse_inlines(input: &str, line: usize, col: usize) -> Result, ParseError> { let mut out = Vec::new(); let mut i = 0usize; let chars: Vec = input.chars().collect(); while i < chars.len() { if chars[i] == '$' && i + 1 < chars.len() { match chars[i + 1] { '{' => { let start = i + 2; let mut j = start; while j < chars.len() && chars[j] != '}' { j += 1; } if j >= chars.len() { return Err(err(line, col + i, "unclosed parameter ${...}")); } let name: String = chars[start..j].iter().collect(); if !is_valid_param_name(&name) { return Err(err( line, col + i, format!("invalid parameter name '{name}'"), )); } out.push(Inline::Param(name)); i = j + 1; continue; } '[' => { let start = i + 2; let mut j = start; while j < chars.len() && chars[j] != ']' { j += 1; } if j >= chars.len() { return Err(err(line, col + i, "unclosed parameter $[...]")); } let name: String = chars[start..j].iter().collect(); if !is_valid_param_name(&name) { return Err(err( line, col + i, format!("invalid checkbox parameter name '{name}'"), )); } out.push(Inline::CheckboxParam(name)); i = j + 1; continue; } _ => {} } } if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) { out.push(Inline::Checkbox { checked }); i += consumed; continue; } let start = i; while i < chars.len() && chars[i] != '$' { // Stop before a checkbox so it becomes its own inline. if try_parse_checkbox(&chars[i..]).is_some() { break; } i += 1; } if i == start { i += 1; continue; } out.push(Inline::Text(chars[start..i].iter().collect())); } Ok(out) } /// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`. /// Returns `(checked, chars_consumed)`. fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> { if chars.first() != Some(&'[') { return None; } match chars.get(1) { Some(']') => Some((false, 2)), Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)), Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)), _ => None, } } fn is_valid_param_name(name: &str) -> bool { let mut chars = name.chars(); match chars.next() { Some(c) if c.is_ascii_alphabetic() || c == '_' => {} _ => return false, } chars.all(|c| c.is_ascii_alphanumeric() || c == '_') } fn err(line: usize, column: usize, message: impl Into) -> ParseError { ParseError { line, column, message: message.into(), } } #[cfg(test)] mod tests { use super::*; use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline, TimeFormatSpec}; fn inlines_to_text(inlines: &[Inline]) -> String { let mut out = String::new(); for inline in inlines { match inline { Inline::Text(t) | Inline::Param(t) | Inline::CheckboxParam(t) => out.push_str(t), Inline::Checkbox { checked } => { out.push_str(crate::dsl::checkbox_glyph(*checked)); } } } out } #[test] fn parses_inline_checkboxes() { let doc = parse("[] empty\n[ ] spaced\n[x] done\n[X] also").unwrap(); assert_eq!(doc.blocks.len(), 1); let Block::Paragraph { inlines, .. } = &doc.blocks[0] else { panic!("expected paragraph"); }; let glyphs: Vec<_> = inlines .iter() .filter_map(|i| match i { Inline::Checkbox { checked } => Some(*checked), _ => None, }) .collect(); assert_eq!(glyphs, vec![false, false, true, true]); } #[test] fn parses_checkbox_param() { let doc = parse("$[Paid] ok").unwrap(); let Block::Paragraph { inlines, .. } = &doc.blocks[0] else { panic!("expected paragraph"); }; assert!(matches!( &inlines[0], Inline::CheckboxParam(name) if name == "Paid" )); } #[test] fn rejects_same_name_as_text_and_checkbox_param() { let err = parse("${Paid}\n$[Paid]").unwrap_err(); assert!( err.message.contains("cannot be both"), "unexpected error: {}", err.message ); } #[test] fn parses_heading_and_paragraph() { let doc = parse("# Store\nHello world").unwrap(); assert_eq!(doc.blocks.len(), 2); assert!(matches!(doc.blocks[0], Block::Heading { level: 1, .. })); assert!(matches!(doc.blocks[1], Block::Paragraph { .. })); } #[test] fn preserves_leading_spaces_in_paragraph() { let doc = parse(" hoi").unwrap(); let Block::Paragraph { inlines, .. } = &doc.blocks[0] else { panic!("expected paragraph"); }; assert_eq!(inlines_to_text(inlines), " hoi"); } #[test] fn trims_trailing_but_keeps_leading_spaces() { let doc = parse(" hello ").unwrap(); let Block::Paragraph { inlines, .. } = &doc.blocks[0] else { panic!("expected paragraph"); }; assert_eq!(inlines_to_text(inlines), " hello"); } #[test] fn parses_bullet_list() { let doc = parse("- this\n- is then\n- a list").unwrap(); assert_eq!(doc.blocks.len(), 1); let Block::List { items, .. } = &doc.blocks[0] else { panic!("expected list"); }; assert_eq!(items.len(), 3); assert_eq!(inlines_to_text(&items[0].inlines), "this"); assert_eq!(inlines_to_text(&items[1].inlines), "is then"); assert_eq!(inlines_to_text(&items[2].inlines), "a list"); assert_eq!(items[0].depth, 0); } #[test] fn parses_nested_bullet_list() { let doc = parse("- Groceries\n - Milk\n - Eggs\n- Wash car").unwrap(); let Block::List { items, .. } = &doc.blocks[0] else { panic!("expected list"); }; assert_eq!(items.len(), 4); assert_eq!(items[0].depth, 0); assert_eq!(inlines_to_text(&items[0].inlines), "Groceries"); assert_eq!(items[1].depth, 1); assert_eq!(inlines_to_text(&items[1].inlines), "Milk"); assert_eq!(items[2].depth, 1); assert_eq!(items[3].depth, 0); assert_eq!(inlines_to_text(&items[3].inlines), "Wash car"); } #[test] fn blank_line_breaks_bullet_list() { let doc = parse("- one\n\n- two").unwrap(); assert_eq!(doc.blocks.len(), 3); assert!(matches!(doc.blocks[0], Block::List { .. })); assert!(matches!(doc.blocks[1], Block::Feed(1))); assert!(matches!(doc.blocks[2], Block::List { .. })); } #[test] fn parses_parameters() { let doc = parse("Order ${OrderId}").unwrap(); let Block::Paragraph { inlines, .. } = &doc.blocks[0] else { panic!("expected paragraph"); }; assert!(matches!( inlines.as_slice(), [ Inline::Text(_), Inline::Param(name) ] if name == "OrderId" )); } #[test] fn dedupes_collect_is_separate_module() { let doc = parse("@barcode CODE128 ${A}\n@qr ${A}").unwrap(); assert_eq!(doc.blocks.len(), 2); } #[test] fn strips_comments() { let doc = parse("Visible").unwrap(); assert_eq!(doc.blocks.len(), 1); let doc = parse("\nVisible").unwrap(); assert!(matches!(doc.blocks[0], Block::Feed(1))); } #[test] fn rejects_unknown_directive() { assert!(parse("@unknown x").is_err()); } #[test] fn parses_alignment_prefix() { let doc = parse(":center:\nCentered").unwrap(); let Block::Paragraph { align, .. } = &doc.blocks[0] else { panic!(); }; assert_eq!(*align, Align::Center); } #[test] fn persistent_center_applies_to_heading_and_directives() { let doc = parse( ":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n:left:\nLeft\n", ) .unwrap(); assert_eq!(doc.blocks.len(), 4); assert!(matches!( doc.blocks[0], Block::Heading { align: Align::Center, .. } )); assert!(matches!( doc.blocks[1], Block::Qr { align: Align::Center, .. } )); assert!(matches!( doc.blocks[2], Block::Barcode { align: Align::Center, .. } )); assert!(matches!( doc.blocks[3], Block::Paragraph { align: Align::Left, .. } )); } #[test] fn persistent_center_groups_following_paragraph_lines() { let doc = parse(":center:\nLine one\nLine two").unwrap(); assert_eq!(doc.blocks.len(), 1); let Block::Paragraph { align, inlines } = &doc.blocks[0] else { panic!(); }; assert_eq!(*align, Align::Center); assert_eq!(inlines_to_text(inlines), "Line one\nLine two"); } #[test] fn align_prefix_on_same_line_sets_persistent_state() { let doc = parse(":center: Inline\nNext").unwrap(); assert_eq!(doc.blocks.len(), 1); let Block::Paragraph { align, inlines } = &doc.blocks[0] else { panic!(); }; assert_eq!(*align, Align::Center); assert_eq!(inlines_to_text(inlines), "Inline\nNext"); } #[test] fn multiple_align_prefixes_on_one_line() { let doc = parse(":left:left :right:right").unwrap(); assert_eq!(doc.blocks.len(), 1); let Block::AlignedRow { parts } = &doc.blocks[0] else { panic!("expected AlignedRow, got {:?}", doc.blocks[0]); }; assert_eq!(parts.len(), 2); assert_eq!(parts[0].0, Align::Left); assert_eq!(parts[1].0, Align::Right); assert_eq!(inlines_to_text(&parts[0].1), "left"); assert_eq!(inlines_to_text(&parts[1].1), "right"); } #[test] fn right_before_left_keeps_source_part_order_in_ast() { let doc = parse(":right:10:left:appel").unwrap(); let Block::AlignedRow { parts } = &doc.blocks[0] else { panic!(); }; assert_eq!(parts[0].0, Align::Right); assert_eq!(inlines_to_text(&parts[0].1), "10"); assert_eq!(parts[1].0, Align::Left); assert_eq!(inlines_to_text(&parts[1].1), "appel"); } #[test] fn align_only_line_does_not_emit_block() { let doc = parse(":center:\n:center:").unwrap(); assert!(doc.blocks.is_empty()); } #[test] fn parses_date_and_time_directives() { let doc = parse("@date\n@date DD-YYYY-MM\n@time\n@time 12h").unwrap(); assert!(matches!( doc.blocks[0], Block::Date { format: None, .. } )); assert!(matches!( doc.blocks[1], Block::Date { format: Some(ref f), .. } if f == "DD-YYYY-MM" )); assert!(matches!( doc.blocks[2], Block::Time { format: TimeFormatSpec::Hours24, .. } )); assert!(matches!( doc.blocks[3], Block::Time { format: TimeFormatSpec::Hours12, .. } )); } #[test] fn rejects_unknown_time_format() { assert!(parse("@time 24").is_err()); } #[test] fn blank_line_inserts_feed() { let doc = parse("A\n\nB").unwrap(); assert!(matches!(doc.blocks[1], Block::Feed(1))); } #[test] fn whitespace_only_line_inserts_feed() { let doc = parse("A\n \nB").unwrap(); assert!(matches!(doc.blocks[1], Block::Feed(1))); } #[test] fn document_ends_with_cut_ignores_trailing_blank_lines() { let doc = parse("Line\n@cut\n\n").unwrap(); assert!(document_ends_with_cut(&doc)); } #[test] fn document_without_cut_at_end() { let doc = parse("Line\n@feed 1").unwrap(); assert!(!document_ends_with_cut(&doc)); } #[test] fn blank_line_between_barcode_and_qr_is_feed() { let doc = parse("@barcode RASTER CODE128 X\n\n:center:@qr RASTER Y scale=4").unwrap(); assert!(matches!( doc.blocks.as_slice(), [ Block::Barcode { .. }, Block::Feed(1), Block::Qr { .. }, ] )); } #[test] fn dsl_marker_lines_are_not_feed() { for src in [ ":left:\nNext", ":center:\nNext", ":right:\nNext", ":centre:\nNext", "# Title\n", "---\n", "@cut\n", ] { let doc = parse(src).unwrap(); assert!( !doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))), "unexpected feed for {src:?}" ); } } #[test] fn parses_raster_barcode() { let doc = parse("@barcode RASTER CODE128 ABC").unwrap(); assert!(matches!( doc.blocks[0], Block::Barcode { mode: BarcodeMode::Raster, symbology: BarcodeSymbology::Code128, .. } )); } #[test] fn barcode_data_joins_words_until_attributes() { let doc = parse("@barcode RASTER CODE128 hallo wereld height=80").unwrap(); match &doc.blocks[0] { Block::Barcode { data, height, show_text, .. } => { assert_eq!(data, "hallo wereld"); assert_eq!(*height, 80); assert!(!*show_text); } other => panic!("expected barcode, got {other:?}"), } } #[test] fn barcode_show_text_defaults_false_and_can_enable() { let off = parse("@barcode CODE128 ABC").unwrap(); match &off.blocks[0] { Block::Barcode { show_text, .. } => assert!(!*show_text), other => panic!("expected barcode, got {other:?}"), } let on = parse("@barcode CODE128 ABC show_text=true").unwrap(); match &on.blocks[0] { Block::Barcode { show_text, .. } => assert!(*show_text), other => panic!("expected barcode, got {other:?}"), } } #[test] fn qr_data_joins_words_until_attributes() { let doc = parse("@qr hallo wereld size=6").unwrap(); match &doc.blocks[0] { Block::Qr { data, size, .. } => { assert_eq!(data, "hallo wereld"); assert_eq!(*size, 6); } other => panic!("expected qr, got {other:?}"), } } #[test] fn qr_url_with_query_equals_is_data_not_attribute() { let doc = parse( "@qr https://sleutels.kvt.nl/moirai/index.php?t=l&d=5CD146GMCC size=4 ecc=M align=center", ) .unwrap(); match &doc.blocks[0] { Block::Qr { data, size, ecc, align, .. } => { assert_eq!( data, "https://sleutels.kvt.nl/moirai/index.php?t=l&d=5CD146GMCC" ); assert_eq!(*size, 4); assert_eq!(*ecc, QrEcc::M); assert_eq!(*align, Align::Center); } other => panic!("expected qr, got {other:?}"), } } #[test] fn barcode_url_with_query_equals_is_data() { let doc = parse("@barcode RASTER CODE128 https://example.com/x?a=1&b=2 height=40").unwrap(); match &doc.blocks[0] { Block::Barcode { data, height, .. } => { assert_eq!(data, "https://example.com/x?a=1&b=2"); assert_eq!(*height, 40); } other => panic!("expected barcode, got {other:?}"), } } }