BlueGit

timfa posprint

Add inline checkboxes ([] / [ ] / [x]) as ASCII glyphs.

Parse empty and checked boxes; print/preview as CP437-safe [ ] and [x]. Include a one-shot print example for glyph checks.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-07-17 · 4 months ago

Hash
00d5035fa90320e86bf9bb8a63135cd28c4bffef
Parent
f49bc076
8 files changed +144 −2
docs/DSL-SPEC.md +13 −0
@@ -77,6 +77,15 @@ Wrapped lines use a hanging indent:
77 77 |--------|--------|
78 78 | `${Name}` | Parameter placeholder (see Parameters) |
79 79
80 ### Checkboxes
81
82 | Syntax | Printed glyph |
83 |--------|---------------|
84 | `[]` or `[ ]` | `[ ]` (empty) |
85 | `[x]` or `[X]` | `[x]` (checked) |
86
87 ASCII glyphs keep CP437 printers reliable; raster boxes are a future option if needed.
88
80 89 Parameters work inside any text, and inside barcode/QR/image directives (below).
81 90
82 91 **Example:**
@@ -85,6 +94,9 @@ Parameters work inside any text, and inside barcode/QR/image directives (below).
85 94 Receipt #${DocumentNumber}
86 95 Date: ${Date}
87 96
97 [x] Paid
98 [] Pending
99
88 100 Item: ${ItemName} ${LineTotal}
89 101 ```
90 102
@@ -257,6 +269,7 @@ Parse errors include 1-based line and column. Typical causes:
257 269 | `# heading` | Double width/height ON → text → OFF |
258 270 | `## heading` | Bold ON → text → OFF |
259 271 | `- item` | ASCII `* ` bullet + hanging wrap |
272 | `[]` / `[ ]` / `[x]` | ASCII checkbox glyphs |
260 273 | `:center:` | Justification center |
261 274 | `@feed n` / blank line | ESC d n |
262 275 | `@cut` | GS V partial cut |
@@ -77,6 +77,15 @@ Wrapped lines use a hanging indent:
77|--------|--------|
77|--------|--------|
78| `${Name}` | Parameter placeholder (see Parameters) |
78| `${Name}` | Parameter placeholder (see Parameters) |
79
79
80### Checkboxes
81
82| Syntax | Printed glyph |
83|--------|---------------|
84| `[]` or `[ ]` | `[ ]` (empty) |
85| `[x]` or `[X]` | `[x]` (checked) |
86
87ASCII glyphs keep CP437 printers reliable; raster boxes are a future option if needed.
88
80Parameters work inside any text, and inside barcode/QR/image directives (below).
89Parameters work inside any text, and inside barcode/QR/image directives (below).
81
90
82**Example:**
91**Example:**
@@ -85,6 +94,9 @@ Parameters work inside any text, and inside barcode/QR/image directives (below).
85Receipt #${DocumentNumber}
94Receipt #${DocumentNumber}
86Date: ${Date}
95Date: ${Date}
87
96
97[x] Paid
98[] Pending
99
88Item: ${ItemName} ${LineTotal}
100Item: ${ItemName} ${LineTotal}
89```
101```
90
102
@@ -257,6 +269,7 @@ Parse errors include 1-based line and column. Typical causes:
257| `# heading` | Double width/height ON → text → OFF |
269| `# heading` | Double width/height ON → text → OFF |
258| `## heading` | Bold ON → text → OFF |
270| `## heading` | Bold ON → text → OFF |
259| `- item` | ASCII `* ` bullet + hanging wrap |
271| `- item` | ASCII `* ` bullet + hanging wrap |
272| `[]` / `[ ]` / `[x]` | ASCII checkbox glyphs |
260| `:center:` | Justification center |
273| `:center:` | Justification center |
261| `@feed n` / blank line | ESC d n |
274| `@feed n` / blank line | ESC d n |
262| `@cut` | GS V partial cut |
275| `@cut` | GS V partial cut |
docs/HELP.md +16 −1
@@ -43,7 +43,7 @@ If the document does not end with `@cut` (ignoring blank lines after it), a red
43 43
44 44 ## Template language
45 45
46 A template is plain text: paragraphs, headings, lists, directives, and `${parameters}`. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
46 A template is plain text: paragraphs, headings, lists, checkboxes, directives, and `${parameters}`. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
47 47
48 48 ### Paragraphs
49 49
@@ -80,6 +80,21 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
80 80 |--------|--------|
81 81 | `${Name}` | Parameter (filled at print time) |
82 82
83 ### Checkboxes
84
85 Inline checkboxes (ASCII on print/preview):
86
87 | Syntax | Result |
88 |--------|--------|
89 | `[]` or `[ ]` | Empty box `[ ]` |
90 | `[x]` or `[X]` | Checked box `[x]` |
91
92 ```markdown
93 [] Unchecked
94 [ ] Also unchecked
95 [x] Done
96 ```
97
83 98 ### Horizontal rule
84 99
85 100 ```markdown
@@ -43,7 +43,7 @@ If the document does not end with `@cut` (ignoring blank lines after it), a red
43
43
44## Template language
44## Template language
45
45
46A template is plain text: paragraphs, headings, lists, directives, and `${parameters}`. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
46A template is plain text: paragraphs, headings, lists, checkboxes, directives, and `${parameters}`. There is **no** inline bold/italic/code markup — asterisks and backticks print literally.
47
47
48### Paragraphs
48### Paragraphs
49
49
@@ -80,6 +80,21 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
80|--------|--------|
80|--------|--------|
81| `${Name}` | Parameter (filled at print time) |
81| `${Name}` | Parameter (filled at print time) |
82
82
83### Checkboxes
84
85Inline checkboxes (ASCII on print/preview):
86
87| Syntax | Result |
88|--------|--------|
89| `[]` or `[ ]` | Empty box `[ ]` |
90| `[x]` or `[X]` | Checked box `[x]` |
91
92```markdown
93[] Unchecked
94[ ] Also unchecked
95[x] Done
96```
97
83### Horizontal rule
98### Horizontal rule
84
99
85```markdown
100```markdown
examples/checkbox-test.pos added +8 −0
@@ -0,0 +1,8 @@
1 {
2 "version": 1,
3 "metadata": {
4 "title": "Checkbox glyph test",
5 "page_width_mm": 58
6 },
7 "body": "# Checkbox test\n\n[] empty brackets\n[ ] space brackets\n[x] checked lowercase\n\n@feed 2\n@cut\n"
8 }
@@ -0,0 +1,8 @@
1{
2 "version": 1,
3 "metadata": {
4 "title": "Checkbox glyph test",
5 "page_width_mm": 58
6 },
7 "body": "# Checkbox test\n\n[] empty brackets\n[ ] space brackets\n[x] checked lowercase\n\n@feed 2\n@cut\n"
8}
examples/print_checkbox_test.rs added +34 −0
@@ -0,0 +1,34 @@
1 //! One-shot: list printers and print the checkbox glyph test template.
2 use std::path::PathBuf;
3
4 use posprint::io::PosFile;
5 use posprint::pipeline::encode_pos_file;
6 use posprint::print::{list_printers, open_printer, print_bytes, PrinterTarget};
7 use std::collections::HashMap;
8
9 fn main() {
10 let printers = list_printers().expect("list_printers");
11 println!("Found {} printer(s):", printers.len());
12 for (i, p) in printers.iter().enumerate() {
13 println!(" [{i}] {} ({})", p.display_name, p.id);
14 }
15 if printers.is_empty() {
16 eprintln!("No printers found — cannot print checkbox test.");
17 std::process::exit(1);
18 }
19
20 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("checkbox-test.pos");
21 let file = PosFile::load_from_path(&path).expect("load checkbox-test.pos");
22 let bytes = encode_pos_file(&file, path.parent(), &HashMap::new()).expect("encode");
23
24 // Prefer a non-spooler device if present (closer to ESC/POS raw), else first entry.
25 let device = printers
26 .iter()
27 .find(|p| !matches!(p.target, PrinterTarget::WinSpooler(_)))
28 .unwrap_or(&printers[0]);
29
30 println!("Printing checkbox test to: {}", device.display_name);
31 let mut transport = open_printer(&device.target).expect("open printer");
32 print_bytes(&mut transport, &bytes).expect("print");
33 println!("OK — check paper for: [] / [ ] / [x] rendered as [ ] [ ] [x]");
34 }
@@ -0,0 +1,34 @@
1//! One-shot: list printers and print the checkbox glyph test template.
2use std::path::PathBuf;
3
4use posprint::io::PosFile;
5use posprint::pipeline::encode_pos_file;
6use posprint::print::{list_printers, open_printer, print_bytes, PrinterTarget};
7use std::collections::HashMap;
8
9fn main() {
10 let printers = list_printers().expect("list_printers");
11 println!("Found {} printer(s):", printers.len());
12 for (i, p) in printers.iter().enumerate() {
13 println!(" [{i}] {} ({})", p.display_name, p.id);
14 }
15 if printers.is_empty() {
16 eprintln!("No printers found — cannot print checkbox test.");
17 std::process::exit(1);
18 }
19
20 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("checkbox-test.pos");
21 let file = PosFile::load_from_path(&path).expect("load checkbox-test.pos");
22 let bytes = encode_pos_file(&file, path.parent(), &HashMap::new()).expect("encode");
23
24 // Prefer a non-spooler device if present (closer to ESC/POS raw), else first entry.
25 let device = printers
26 .iter()
27 .find(|p| !matches!(p.target, PrinterTarget::WinSpooler(_)))
28 .unwrap_or(&printers[0]);
29
30 println!("Printing checkbox test to: {}", device.display_name);
31 let mut transport = open_printer(&device.target).expect("open printer");
32 print_bytes(&mut transport, &bytes).expect("print");
33 println!("OK — check paper for: [] / [ ] / [x] rendered as [ ] [ ] [x]");
34}
src/dsl/mod.rs +13 −0
@@ -135,6 +135,19 @@ pub enum QrEcc {
135 135 pub enum Inline {
136 136 Text(String),
137 137 Param(String),
138 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` (checked).
139 Checkbox {
140 checked: bool,
141 },
142 }
143
144 /// ASCII glyphs for checkboxes (CP437-safe on ESC/POS printers).
145 pub fn checkbox_glyph(checked: bool) -> &'static str {
146 if checked {
147 "[x]"
148 } else {
149 "[ ]"
150 }
138 151 }
139 152
140 153 impl BarcodeSymbology {
@@ -135,6 +135,19 @@ pub enum QrEcc {
135pub enum Inline {
135pub enum Inline {
136 Text(String),
136 Text(String),
137 Param(String),
137 Param(String),
138 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` (checked).
139 Checkbox {
140 checked: bool,
141 },
142}
143
144/// ASCII glyphs for checkboxes (CP437-safe on ESC/POS printers).
145pub fn checkbox_glyph(checked: bool) -> &'static str {
146 if checked {
147 "[x]"
148 } else {
149 "[ ]"
150 }
138}
151}
139
152
140impl BarcodeSymbology {
153impl BarcodeSymbology {
src/dsl/parser.rs +43 −0
@@ -563,8 +563,17 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
563 563 i = j + 1;
564 564 continue;
565 565 }
566 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
567 out.push(Inline::Checkbox { checked });
568 i += consumed;
569 continue;
570 }
566 571 let start = i;
567 572 while i < chars.len() && chars[i] != '$' {
573 // Stop before a checkbox so it becomes its own inline.
574 if try_parse_checkbox(&chars[i..]).is_some() {
575 break;
576 }
568 577 i += 1;
569 578 }
570 579 if i == start {
@@ -576,6 +585,20 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
576 585 Ok(out)
577 586 }
578 587
588 /// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`.
589 /// Returns `(checked, chars_consumed)`.
590 fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
591 if chars.first() != Some(&'[') {
592 return None;
593 }
594 match chars.get(1) {
595 Some(']') => Some((false, 2)),
596 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
597 Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)),
598 _ => None,
599 }
600 }
601
579 602 fn is_valid_param_name(name: &str) -> bool {
580 603 let mut chars = name.chars();
581 604 match chars.next() {
@@ -603,11 +626,31 @@ mod tests {
603 626 for inline in inlines {
604 627 match inline {
605 628 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
629 Inline::Checkbox { checked } => {
630 out.push_str(crate::dsl::checkbox_glyph(*checked));
631 }
606 632 }
607 633 }
608 634 out
609 635 }
610 636
637 #[test]
638 fn parses_inline_checkboxes() {
639 let doc = parse("[] empty\n[ ] spaced\n[x] done\n[X] also").unwrap();
640 assert_eq!(doc.blocks.len(), 1);
641 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
642 panic!("expected paragraph");
643 };
644 let glyphs: Vec<_> = inlines
645 .iter()
646 .filter_map(|i| match i {
647 Inline::Checkbox { checked } => Some(*checked),
648 _ => None,
649 })
650 .collect();
651 assert_eq!(glyphs, vec![false, false, true, true]);
652 }
653
611 654 #[test]
612 655 fn parses_heading_and_paragraph() {
613 656 let doc = parse("# Store\nHello world").unwrap();
@@ -563,8 +563,17 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
563 i = j + 1;
563 i = j + 1;
564 continue;
564 continue;
565 }
565 }
566 if let Some((checked, consumed)) = try_parse_checkbox(&chars[i..]) {
567 out.push(Inline::Checkbox { checked });
568 i += consumed;
569 continue;
570 }
566 let start = i;
571 let start = i;
567 while i < chars.len() && chars[i] != '$' {
572 while i < chars.len() && chars[i] != '$' {
573 // Stop before a checkbox so it becomes its own inline.
574 if try_parse_checkbox(&chars[i..]).is_some() {
575 break;
576 }
568 i += 1;
577 i += 1;
569 }
578 }
570 if i == start {
579 if i == start {
@@ -576,6 +585,20 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
576 Ok(out)
585 Ok(out)
577}
586}
578
587
588/// Parse `[]`, `[ ]`, `[x]`, or `[X]` at the start of `chars`.
589/// Returns `(checked, chars_consumed)`.
590fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
591 if chars.first() != Some(&'[') {
592 return None;
593 }
594 match chars.get(1) {
595 Some(']') => Some((false, 2)),
596 Some(' ') if chars.get(2) == Some(&']') => Some((false, 3)),
597 Some('x' | 'X') if chars.get(2) == Some(&']') => Some((true, 3)),
598 _ => None,
599 }
600}
601
579fn is_valid_param_name(name: &str) -> bool {
602fn is_valid_param_name(name: &str) -> bool {
580 let mut chars = name.chars();
603 let mut chars = name.chars();
581 match chars.next() {
604 match chars.next() {
@@ -603,11 +626,31 @@ mod tests {
603 for inline in inlines {
626 for inline in inlines {
604 match inline {
627 match inline {
605 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
628 Inline::Text(t) | Inline::Param(t) => out.push_str(t),
629 Inline::Checkbox { checked } => {
630 out.push_str(crate::dsl::checkbox_glyph(*checked));
631 }
606 }
632 }
607 }
633 }
608 out
634 out
609 }
635 }
610
636
637 #[test]
638 fn parses_inline_checkboxes() {
639 let doc = parse("[] empty\n[ ] spaced\n[x] done\n[X] also").unwrap();
640 assert_eq!(doc.blocks.len(), 1);
641 let Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
642 panic!("expected paragraph");
643 };
644 let glyphs: Vec<_> = inlines
645 .iter()
646 .filter_map(|i| match i {
647 Inline::Checkbox { checked } => Some(*checked),
648 _ => None,
649 })
650 .collect();
651 assert_eq!(glyphs, vec![false, false, true, true]);
652 }
653
611 #[test]
654 #[test]
612 fn parses_heading_and_paragraph() {
655 fn parses_heading_and_paragraph() {
613 let doc = parse("# Store\nHello world").unwrap();
656 let doc = parse("# Store\nHello world").unwrap();
src/escpos.rs +10 −0
@@ -354,6 +354,7 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
354 354 match inline {
355 355 Inline::Text(t) => out.push_str(t),
356 356 Inline::Param(t) => out.push_str(t),
357 Inline::Checkbox { checked } => out.push_str(crate::dsl::checkbox_glyph(*checked)),
357 358 }
358 359 }
359 360 out
@@ -397,6 +398,15 @@ mod tests {
397 398 assert!(text.contains(" long line\n"));
398 399 }
399 400
401 #[test]
402 fn encodes_inline_checkboxes_as_ascii() {
403 let doc = parse("[] [ ] [x]").unwrap();
404 let mut enc = EscPosEncoder::new(PosMetadata::default());
405 let bytes = enc.encode_document(&doc).unwrap();
406 let text = String::from_utf8_lossy(bytes);
407 assert!(text.contains("[ ] [ ] [x]\n"));
408 }
409
400 410 #[test]
401 411 fn encodes_init_and_text() {
402 412 let doc = parse("Hello").unwrap();
@@ -354,6 +354,7 @@ fn inlines_to_plain(inlines: &[Inline]) -> String {
354 match inline {
354 match inline {
355 Inline::Text(t) => out.push_str(t),
355 Inline::Text(t) => out.push_str(t),
356 Inline::Param(t) => out.push_str(t),
356 Inline::Param(t) => out.push_str(t),
357 Inline::Checkbox { checked } => out.push_str(crate::dsl::checkbox_glyph(*checked)),
357 }
358 }
358 }
359 }
359 out
360 out
@@ -397,6 +398,15 @@ mod tests {
397 assert!(text.contains(" long line\n"));
398 assert!(text.contains(" long line\n"));
398 }
399 }
399
400
401 #[test]
402 fn encodes_inline_checkboxes_as_ascii() {
403 let doc = parse("[] [ ] [x]").unwrap();
404 let mut enc = EscPosEncoder::new(PosMetadata::default());
405 let bytes = enc.encode_document(&doc).unwrap();
406 let text = String::from_utf8_lossy(bytes);
407 assert!(text.contains("[ ] [ ] [x]\n"));
408 }
409
400 #[test]
410 #[test]
401 fn encodes_init_and_text() {
411 fn encodes_init_and_text() {
402 let doc = parse("Hello").unwrap();
412 let doc = parse("Hello").unwrap();
src/params.rs +7 −1
@@ -21,6 +21,9 @@ pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap
21 21 .map(|inline| match inline {
22 22 Inline::Text(t) => Inline::Text(t.clone()),
23 23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
24 Inline::Checkbox { checked } => Inline::Checkbox {
25 checked: *checked,
26 },
24 27 })
25 28 .collect()
26 29 }
@@ -204,7 +207,7 @@ fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
204 207 Inline::Param(name) => {
205 208 names.insert(name.clone());
206 209 }
207 Inline::Text(_) => {}
210 Inline::Text(_) | Inline::Checkbox { .. } => {}
208 211 }
209 212 }
210 213 }
@@ -241,6 +244,9 @@ pub fn substitute_inlines_for_preview(
241 244 Inline::Param(name) => {
242 245 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
243 246 }
247 Inline::Checkbox { checked } => {
248 out.push_str(crate::dsl::checkbox_glyph(*checked));
249 }
244 250 }
245 251 }
246 252 out
@@ -21,6 +21,9 @@ pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap
21 .map(|inline| match inline {
21 .map(|inline| match inline {
22 Inline::Text(t) => Inline::Text(t.clone()),
22 Inline::Text(t) => Inline::Text(t.clone()),
23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
24 Inline::Checkbox { checked } => Inline::Checkbox {
25 checked: *checked,
26 },
24 })
27 })
25 .collect()
28 .collect()
26}
29}
@@ -204,7 +207,7 @@ fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
204 Inline::Param(name) => {
207 Inline::Param(name) => {
205 names.insert(name.clone());
208 names.insert(name.clone());
206 }
209 }
207 Inline::Text(_) => {}
210 Inline::Text(_) | Inline::Checkbox { .. } => {}
208 }
211 }
209 }
212 }
210}
213}
@@ -241,6 +244,9 @@ pub fn substitute_inlines_for_preview(
241 Inline::Param(name) => {
244 Inline::Param(name) => {
242 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
245 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
243 }
246 }
247 Inline::Checkbox { checked } => {
248 out.push_str(crate::dsl::checkbox_glyph(*checked));
249 }
244 }
250 }
245 }
251 }
246 out
252 out