BlueGit

timfa posprint

Merge branch 'feature/inline-align-space-pad'

timfa Tim Falken · pushed by timfa

Authored 2026-07-22 · 3 months ago

Hash
121490a7cde85d788fdb99e1081d871316b821fd
16 files changed +354 −27
Cargo.lock +1 −1
@@ -2786,7 +2786,7 @@ checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
2786 2786
2787 2787 [[package]]
2788 2788 name = "posprint"
2789 version = "0.5.3"
2789 version = "0.5.4"
2790 2790 dependencies = [
2791 2791 "barcoders",
2792 2792 "base64",
@@ -2786,7 +2786,7 @@ checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
2786
2786
2787[[package]]
2787[[package]]
2788name = "posprint"
2788name = "posprint"
2789version = "0.5.3"
2789version = "0.5.4"
2790dependencies = [
2790dependencies = [
2791 "barcoders",
2791 "barcoders",
2792 "base64",
2792 "base64",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
1 1 [package]
2 2 name = "posprint"
3 version = "0.5.3"
3 version = "0.5.4"
4 4 edition = "2021"
5 5 rust-version = "1.88"
6 6 description = "Designer for POS-print documents"
@@ -1,6 +1,6 @@
1[package]
1[package]
2name = "posprint"
2name = "posprint"
3version = "0.5.3"
3version = "0.5.4"
4edition = "2021"
4edition = "2021"
5rust-version = "1.88"
5rust-version = "1.88"
6description = "Designer for POS-print documents"
6description = "Designer for POS-print documents"
README.md +1 −1
@@ -6,7 +6,7 @@ Cross-platform designer for POS (point-of-sale) receipt documents. Edit template
6 6
7 7 ## Status
8 8
9 **v0.5.3** — `noconfirm` + trusted domains; no console flash; loopback referrer; last successful printer preference; spooler temp-file lock fix.
9 **v0.5.4** — Same-line `:left:`/`:right:`/`:center:` via space padding to paper width.
10 10
11 11 ## Build and run
12 12
@@ -6,7 +6,7 @@ Cross-platform designer for POS (point-of-sale) receipt documents. Edit template
6
6
7## Status
7## Status
8
8
9**v0.5.3** — `noconfirm` + trusted domains; no console flash; loopback referrer; last successful printer preference; spooler temp-file lock fix.
9**v0.5.4** — Same-line `:left:`/`:right:`/`:center:` via space padding to paper width.
10
10
11## Build and run
11## Build and run
12
12
docs/ARCHITECTURE.md +1 −0
@@ -114,6 +114,7 @@ While the print dialog is open, the main UI is disabled and editor autocomplete
114 114 struct Document { blocks: Vec<Block> }
115 115 enum Block {
116 116 Paragraph { align, inlines },
117 AlignedRow { parts }, // same-line :left:/:center:/:right: → space pad
117 118 List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
118 119 Heading { level, align, inlines },
119 120 Rule, Feed(u8), Cut,
@@ -114,6 +114,7 @@ While the print dialog is open, the main UI is disabled and editor autocomplete
114struct Document { blocks: Vec<Block> }
114struct Document { blocks: Vec<Block> }
115enum Block {
115enum Block {
116 Paragraph { align, inlines },
116 Paragraph { align, inlines },
117 AlignedRow { parts }, // same-line :left:/:center:/:right: → space pad
117 List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
118 List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
118 Heading { level, align, inlines },
119 Heading { level, align, inlines },
119 Rule, Feed(u8), Cut,
120 Rule, Feed(u8), Cut,
docs/DSL-SPEC.md +8 −0
@@ -56,6 +56,14 @@ Total: ${Amount}
56 56 | `:center:` | Centered |
57 57 | `:right:` | Right-aligned |
58 58
59 **Same line, multiple markers:** ESC/POS can only justify a whole line (`ESC a`), so `:left: appel:right:10` cannot be true dual-alignment. posprint pads with spaces to `chars_per_line` (after `${Param}` substitution) so left/center/right text shares one printed line. Marker order is normalized to Left → Center → Right (e.g. `:right:10:left:appel` prints as `appel` … `10`). If the parts do not fit, they fall back to separate lines.
60
61 ```markdown
62 :left: ${Item}:right: ${Price}
63 ```
64
65 Standalone `:center:` / `:right:` paragraphs (one alignment per line) still use printer justification.
66
59 67 ### Bullet lists
60 68
61 69 ```markdown
@@ -56,6 +56,14 @@ Total: ${Amount}
56| `:center:` | Centered |
56| `:center:` | Centered |
57| `:right:` | Right-aligned |
57| `:right:` | Right-aligned |
58
58
59**Same line, multiple markers:** ESC/POS can only justify a whole line (`ESC a`), so `:left: appel:right:10` cannot be true dual-alignment. posprint pads with spaces to `chars_per_line` (after `${Param}` substitution) so left/center/right text shares one printed line. Marker order is normalized to Left → Center → Right (e.g. `:right:10:left:appel` prints as `appel` … `10`). If the parts do not fit, they fall back to separate lines.
60
61```markdown
62:left: ${Item}:right: ${Price}
63```
64
65Standalone `:center:` / `:right:` paragraphs (one alignment per line) still use printer justification.
66
59### Bullet lists
67### Bullet lists
60
68
61```markdown
69```markdown
docs/HELP.md +2 −0
@@ -63,6 +63,8 @@ Consecutive non-empty lines form one paragraph. Multiple spaces in a row are kep
63 63
64 64 `:left:`, `:center:`, or `:right:` before a paragraph.
65 65
66 On **one line**, you can combine markers (e.g. `:left: Appel:right: 10`). That prints as one row with spaces so the right text sits at the end of the paper width. Writing `:right:10:left:Appel` is treated the same (left then right). If both sides are too long for the line, they print on separate lines instead.
67
66 68 ### Bullet lists
67 69
68 70 ```markdown
@@ -63,6 +63,8 @@ Consecutive non-empty lines form one paragraph. Multiple spaces in a row are kep
63
63
64`:left:`, `:center:`, or `:right:` before a paragraph.
64`:left:`, `:center:`, or `:right:` before a paragraph.
65
65
66On **one line**, you can combine markers (e.g. `:left: Appel:right: 10`). That prints as one row with spaces so the right text sits at the end of the paper width. Writing `:right:10:left:Appel` is treated the same (left then right). If both sides are too long for the line, they print on separate lines instead.
67
66### Bullet lists
68### Bullet lists
67
69
68```markdown
70```markdown
packaging/arch/PKGBUILD +1 −1
@@ -1,6 +1,6 @@
1 1 # Maintainer: posprint contributors
2 2 pkgname=posprint
3 pkgver=0.5.3
3 pkgver=0.5.4
4 4 pkgrel=1
5 5 pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
6 6 arch=('x86_64')
@@ -1,6 +1,6 @@
1# Maintainer: posprint contributors
1# Maintainer: posprint contributors
2pkgname=posprint
2pkgname=posprint
3pkgver=0.5.3
3pkgver=0.5.4
4pkgrel=1
4pkgrel=1
5pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
5pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
6arch=('x86_64')
6arch=('x86_64')
packaging/aur/.SRCINFO +2 −2
@@ -1,6 +1,6 @@
1 1 pkgbase = posprint
2 2 pkgdesc = Designer for POS-print documents with live preview and USB ESC/POS printing
3 pkgver = 0.5.3
3 pkgver = 0.5.4
4 4 pkgrel = 1
5 5 url = https://gitlab.com/Timfa/posprint
6 6 arch = x86_64
@@ -21,7 +21,7 @@ pkgbase = posprint
21 21 depends = freetype2
22 22 depends = libglvnd
23 23 options = !lto
24 source = https://gitlab.com/Timfa/posprint/-/archive/0.5.3/posprint-0.5.3.tar.gz
24 source = https://gitlab.com/Timfa/posprint/-/archive/0.5.4/posprint-0.5.4.tar.gz
25 25 sha256sums = SKIP
26 26
27 27 pkgname = posprint
@@ -1,6 +1,6 @@
1pkgbase = posprint
1pkgbase = posprint
2 pkgdesc = Designer for POS-print documents with live preview and USB ESC/POS printing
2 pkgdesc = Designer for POS-print documents with live preview and USB ESC/POS printing
3 pkgver = 0.5.3
3 pkgver = 0.5.4
4 pkgrel = 1
4 pkgrel = 1
5 url = https://gitlab.com/Timfa/posprint
5 url = https://gitlab.com/Timfa/posprint
6 arch = x86_64
6 arch = x86_64
@@ -21,7 +21,7 @@ pkgbase = posprint
21 depends = freetype2
21 depends = freetype2
22 depends = libglvnd
22 depends = libglvnd
23 options = !lto
23 options = !lto
24 source = https://gitlab.com/Timfa/posprint/-/archive/0.5.3/posprint-0.5.3.tar.gz
24 source = https://gitlab.com/Timfa/posprint/-/archive/0.5.4/posprint-0.5.4.tar.gz
25 sha256sums = SKIP
25 sha256sums = SKIP
26
26
27pkgname = posprint
27pkgname = posprint
packaging/aur/PKGBUILD +1 −1
@@ -1,6 +1,6 @@
1 1 # Maintainer: posprint contributors
2 2 pkgname=posprint
3 pkgver=0.5.3
3 pkgver=0.5.4
4 4 pkgrel=1
5 5 pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
6 6 arch=('x86_64')
@@ -1,6 +1,6 @@
1# Maintainer: posprint contributors
1# Maintainer: posprint contributors
2pkgname=posprint
2pkgname=posprint
3pkgver=0.5.3
3pkgver=0.5.4
4pkgrel=1
4pkgrel=1
5pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
5pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
6arch=('x86_64')
6arch=('x86_64')
src/align_row.rs added +168 −0
@@ -0,0 +1,168 @@
1 //! Space-pad multi-align text onto one Font A column row.
2 //!
3 //! ESC/POS `ESC a` justifies whole lines only; same-line `:left:` + `:right:`
4 //! (and optional `:center:`) must be simulated with spaces to `chars_per_line`.
5
6 use crate::dsl::Align;
7
8 #[derive(Debug, Clone, Default, PartialEq, Eq)]
9 pub struct AlignedColumns {
10 pub left: Option<String>,
11 pub center: Option<String>,
12 pub right: Option<String>,
13 }
14
15 /// Map ordered `(Align, text)` parts into Left / Center / Right columns.
16 /// Later segments for the same align win (silent replace).
17 pub fn columns_from_parts(parts: &[(Align, String)]) -> AlignedColumns {
18 let mut cols = AlignedColumns::default();
19 for (align, text) in parts {
20 let text = text.clone();
21 match align {
22 Align::Left => cols.left = Some(text),
23 Align::Center => cols.center = Some(text),
24 Align::Right => cols.right = Some(text),
25 }
26 }
27 cols
28 }
29
30 /// Build one fixed-width line, or `None` when content cannot fit without overlap.
31 pub fn layout_aligned_row(
32 left: Option<&str>,
33 center: Option<&str>,
34 right: Option<&str>,
35 cols: usize,
36 ) -> Option<String> {
37 if cols == 0 {
38 return None;
39 }
40 let left = left.unwrap_or("");
41 let center = center.unwrap_or("");
42 let right = right.unwrap_or("");
43 let left_len = left.chars().count();
44 let center_len = center.chars().count();
45 let right_len = right.chars().count();
46
47 if left_len + center_len + right_len > cols {
48 return None;
49 }
50
51 // Fast path: classic label … amount (no center).
52 if center_len == 0 {
53 let gap = cols - left_len - right_len;
54 return Some(format!("{left}{}{right}", " ".repeat(gap)));
55 }
56
57 let mut buf = vec![' '; cols];
58 for (i, ch) in left.chars().enumerate() {
59 buf[i] = ch;
60 }
61 if right_len > 0 {
62 let start = cols - right_len;
63 for (i, ch) in right.chars().enumerate() {
64 buf[start + i] = ch;
65 }
66 }
67
68 let center_start = (cols - center_len) / 2;
69 for (i, ch) in center.chars().enumerate() {
70 let idx = center_start + i;
71 // Overlaps left or right region → cannot pad safely.
72 if idx < left_len || (right_len > 0 && idx >= cols - right_len) {
73 return None;
74 }
75 if buf[idx] != ' ' {
76 return None;
77 }
78 buf[idx] = ch;
79 }
80
81 Some(buf.into_iter().collect())
82 }
83
84 /// Prefer a single padded line; on overflow return Left → Center → Right lines.
85 pub fn layout_aligned_row_or_lines(columns: &AlignedColumns, cols: usize) -> Vec<(Align, String)> {
86 let left = columns.left.as_deref();
87 let center = columns.center.as_deref();
88 let right = columns.right.as_deref();
89
90 if let Some(line) = layout_aligned_row(left, center, right, cols) {
91 return vec![(Align::Left, line)];
92 }
93
94 let mut lines = Vec::new();
95 if let Some(t) = columns.left.as_ref().filter(|s| !s.is_empty()) {
96 lines.push((Align::Left, t.clone()));
97 }
98 if let Some(t) = columns.center.as_ref().filter(|s| !s.is_empty()) {
99 lines.push((Align::Center, t.clone()));
100 }
101 if let Some(t) = columns.right.as_ref().filter(|s| !s.is_empty()) {
102 lines.push((Align::Right, t.clone()));
103 }
104 lines
105 }
106
107 #[cfg(test)]
108 mod tests {
109 use super::*;
110
111 #[test]
112 fn left_right_gap_matches_cols() {
113 let line = layout_aligned_row(Some("appel"), None, Some("10"), 32).unwrap();
114 assert_eq!(line.chars().count(), 32);
115 assert!(line.starts_with("appel"));
116 assert!(line.ends_with("10"));
117 assert_eq!(&line[5..30], &" ".repeat(25));
118 }
119
120 #[test]
121 fn right_then_left_parts_normalize_order() {
122 let cols = columns_from_parts(&[
123 (Align::Right, "10".into()),
124 (Align::Left, "appel".into()),
125 ]);
126 assert_eq!(cols.left.as_deref(), Some("appel"));
127 assert_eq!(cols.right.as_deref(), Some("10"));
128 let line = layout_aligned_row_or_lines(&cols, 32);
129 assert_eq!(line.len(), 1);
130 assert_eq!(line[0].0, Align::Left);
131 assert!(line[0].1.starts_with("appel"));
132 assert!(line[0].1.ends_with("10"));
133 }
134
135 #[test]
136 fn longer_right_shortens_gap() {
137 let short = layout_aligned_row(Some("A"), None, Some("1"), 10).unwrap();
138 let long = layout_aligned_row(Some("A"), None, Some("12345"), 10).unwrap();
139 assert_eq!(short.chars().count(), 10);
140 assert_eq!(long.chars().count(), 10);
141 assert!(short.contains(" ")); // 8 spaces
142 assert_eq!(&long[1..5], " "); // 4 spaces
143 }
144
145 #[test]
146 fn overflow_falls_back_to_separate_lines() {
147 let cols = AlignedColumns {
148 left: Some("AAAAAAAAAA".into()),
149 center: None,
150 right: Some("BBBBBBBBBBBB".into()),
151 };
152 let lines = layout_aligned_row_or_lines(&cols, 10);
153 assert_eq!(lines.len(), 2);
154 assert_eq!(lines[0], (Align::Left, "AAAAAAAAAA".into()));
155 assert_eq!(lines[1], (Align::Right, "BBBBBBBBBBBB".into()));
156 }
157
158 #[test]
159 fn center_between_left_and_right() {
160 let line = layout_aligned_row(Some("L"), Some("MID"), Some("R"), 11).unwrap();
161 assert_eq!(line, "L MID R");
162 }
163
164 #[test]
165 fn center_overlap_with_left_returns_none() {
166 assert!(layout_aligned_row(Some("LEFTSIDE"), Some("CENTER"), None, 12).is_none());
167 }
168 }
@@ -0,0 +1,168 @@
1//! Space-pad multi-align text onto one Font A column row.
2//!
3//! ESC/POS `ESC a` justifies whole lines only; same-line `:left:` + `:right:`
4//! (and optional `:center:`) must be simulated with spaces to `chars_per_line`.
5
6use crate::dsl::Align;
7
8#[derive(Debug, Clone, Default, PartialEq, Eq)]
9pub struct AlignedColumns {
10 pub left: Option<String>,
11 pub center: Option<String>,
12 pub right: Option<String>,
13}
14
15/// Map ordered `(Align, text)` parts into Left / Center / Right columns.
16/// Later segments for the same align win (silent replace).
17pub fn columns_from_parts(parts: &[(Align, String)]) -> AlignedColumns {
18 let mut cols = AlignedColumns::default();
19 for (align, text) in parts {
20 let text = text.clone();
21 match align {
22 Align::Left => cols.left = Some(text),
23 Align::Center => cols.center = Some(text),
24 Align::Right => cols.right = Some(text),
25 }
26 }
27 cols
28}
29
30/// Build one fixed-width line, or `None` when content cannot fit without overlap.
31pub fn layout_aligned_row(
32 left: Option<&str>,
33 center: Option<&str>,
34 right: Option<&str>,
35 cols: usize,
36) -> Option<String> {
37 if cols == 0 {
38 return None;
39 }
40 let left = left.unwrap_or("");
41 let center = center.unwrap_or("");
42 let right = right.unwrap_or("");
43 let left_len = left.chars().count();
44 let center_len = center.chars().count();
45 let right_len = right.chars().count();
46
47 if left_len + center_len + right_len > cols {
48 return None;
49 }
50
51 // Fast path: classic label … amount (no center).
52 if center_len == 0 {
53 let gap = cols - left_len - right_len;
54 return Some(format!("{left}{}{right}", " ".repeat(gap)));
55 }
56
57 let mut buf = vec![' '; cols];
58 for (i, ch) in left.chars().enumerate() {
59 buf[i] = ch;
60 }
61 if right_len > 0 {
62 let start = cols - right_len;
63 for (i, ch) in right.chars().enumerate() {
64 buf[start + i] = ch;
65 }
66 }
67
68 let center_start = (cols - center_len) / 2;
69 for (i, ch) in center.chars().enumerate() {
70 let idx = center_start + i;
71 // Overlaps left or right region → cannot pad safely.
72 if idx < left_len || (right_len > 0 && idx >= cols - right_len) {
73 return None;
74 }
75 if buf[idx] != ' ' {
76 return None;
77 }
78 buf[idx] = ch;
79 }
80
81 Some(buf.into_iter().collect())
82}
83
84/// Prefer a single padded line; on overflow return Left → Center → Right lines.
85pub fn layout_aligned_row_or_lines(columns: &AlignedColumns, cols: usize) -> Vec<(Align, String)> {
86 let left = columns.left.as_deref();
87 let center = columns.center.as_deref();
88 let right = columns.right.as_deref();
89
90 if let Some(line) = layout_aligned_row(left, center, right, cols) {
91 return vec![(Align::Left, line)];
92 }
93
94 let mut lines = Vec::new();
95 if let Some(t) = columns.left.as_ref().filter(|s| !s.is_empty()) {
96 lines.push((Align::Left, t.clone()));
97 }
98 if let Some(t) = columns.center.as_ref().filter(|s| !s.is_empty()) {
99 lines.push((Align::Center, t.clone()));
100 }
101 if let Some(t) = columns.right.as_ref().filter(|s| !s.is_empty()) {
102 lines.push((Align::Right, t.clone()));
103 }
104 lines
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110
111 #[test]
112 fn left_right_gap_matches_cols() {
113 let line = layout_aligned_row(Some("appel"), None, Some("10"), 32).unwrap();
114 assert_eq!(line.chars().count(), 32);
115 assert!(line.starts_with("appel"));
116 assert!(line.ends_with("10"));
117 assert_eq!(&line[5..30], &" ".repeat(25));
118 }
119
120 #[test]
121 fn right_then_left_parts_normalize_order() {
122 let cols = columns_from_parts(&[
123 (Align::Right, "10".into()),
124 (Align::Left, "appel".into()),
125 ]);
126 assert_eq!(cols.left.as_deref(), Some("appel"));
127 assert_eq!(cols.right.as_deref(), Some("10"));
128 let line = layout_aligned_row_or_lines(&cols, 32);
129 assert_eq!(line.len(), 1);
130 assert_eq!(line[0].0, Align::Left);
131 assert!(line[0].1.starts_with("appel"));
132 assert!(line[0].1.ends_with("10"));
133 }
134
135 #[test]
136 fn longer_right_shortens_gap() {
137 let short = layout_aligned_row(Some("A"), None, Some("1"), 10).unwrap();
138 let long = layout_aligned_row(Some("A"), None, Some("12345"), 10).unwrap();
139 assert_eq!(short.chars().count(), 10);
140 assert_eq!(long.chars().count(), 10);
141 assert!(short.contains(" ")); // 8 spaces
142 assert_eq!(&long[1..5], " "); // 4 spaces
143 }
144
145 #[test]
146 fn overflow_falls_back_to_separate_lines() {
147 let cols = AlignedColumns {
148 left: Some("AAAAAAAAAA".into()),
149 center: None,
150 right: Some("BBBBBBBBBBBB".into()),
151 };
152 let lines = layout_aligned_row_or_lines(&cols, 10);
153 assert_eq!(lines.len(), 2);
154 assert_eq!(lines[0], (Align::Left, "AAAAAAAAAA".into()));
155 assert_eq!(lines[1], (Align::Right, "BBBBBBBBBBBB".into()));
156 }
157
158 #[test]
159 fn center_between_left_and_right() {
160 let line = layout_aligned_row(Some("L"), Some("MID"), Some("R"), 11).unwrap();
161 assert_eq!(line, "L MID R");
162 }
163
164 #[test]
165 fn center_overlap_with_left_returns_none() {
166 assert!(layout_aligned_row(Some("LEFTSIDE"), Some("CENTER"), None, 12).is_none());
167 }
168}
src/dsl/mod.rs +5 −0
@@ -30,6 +30,11 @@ pub enum Block {
30 30 align: Align,
31 31 inlines: Vec<Inline>,
32 32 },
33 /// Multiple `:left:` / `:center:` / `:right:` text segments on one source line.
34 /// Printed as one space-padded row (ESC/POS cannot dual-justify on one line).
35 AlignedRow {
36 parts: Vec<(Align, Vec<Inline>)>,
37 },
33 38 List {
34 39 align: Align,
35 40 items: Vec<ListItem>,
@@ -30,6 +30,11 @@ pub enum Block {
30 align: Align,
30 align: Align,
31 inlines: Vec<Inline>,
31 inlines: Vec<Inline>,
32 },
32 },
33 /// Multiple `:left:` / `:center:` / `:right:` text segments on one source line.
34 /// Printed as one space-padded row (ESC/POS cannot dual-justify on one line).
35 AlignedRow {
36 parts: Vec<(Align, Vec<Inline>)>,
37 },
33 List {
38 List {
34 align: Align,
39 align: Align,
35 items: Vec<ListItem>,
40 items: Vec<ListItem>,
src/dsl/parser.rs +57 −20
@@ -36,6 +36,21 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
36 36 continue;
37 37 }
38 38
39 // Same-line multi-align plain text → one AlignedRow (space-padded at print time).
40 if segments.len() > 1
41 && segments
42 .iter()
43 .all(|(_, seg_text)| is_plain_paragraph_segment(seg_text))
44 {
45 let mut parts = Vec::with_capacity(segments.len());
46 for (seg_align, seg_text) in &segments {
47 current_align = *seg_align;
48 parts.push((*seg_align, parse_inlines(seg_text, line_no, 1)?));
49 }
50 blocks.push(Block::AlignedRow { parts });
51 continue;
52 }
53
39 54 for (idx, (seg_align, seg_text)) in segments.iter().enumerate() {
40 55 current_align = *seg_align;
41 56 let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1;
@@ -157,6 +172,21 @@ fn collect_param_kinds_from_block(
157 172 }
158 173 }
159 174 }
175 Block::AlignedRow { parts } => {
176 for (_, inlines) in parts {
177 for inline in inlines {
178 match inline {
179 Inline::Param(name) => {
180 text_names.insert(name.clone());
181 }
182 Inline::CheckboxParam(name) => {
183 bool_names.insert(name.clone());
184 }
185 _ => {}
186 }
187 }
188 }
189 }
160 190 Block::List { items, .. } => {
161 191 for item in items {
162 192 for inline in &item.inlines {
@@ -245,6 +275,15 @@ fn strip_comments(source: &str) -> String {
245 275 out
246 276 }
247 277
278 /// True when a segment is ordinary paragraph text (eligible for AlignedRow).
279 fn is_plain_paragraph_segment(seg_text: &str) -> bool {
280 !is_blank_feed_line(seg_text)
281 && !seg_text.starts_with('#')
282 && seg_text.trim() != "---"
283 && !seg_text.trim_start().starts_with('@')
284 && !is_list_item_line(seg_text)
285 }
286
248 287 /// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start.
249 288 /// Returns the alignment and optional remaining content on the same line.
250 289 fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> {
@@ -970,29 +1009,27 @@ mod tests {
970 1009 #[test]
971 1010 fn multiple_align_prefixes_on_one_line() {
972 1011 let doc = parse(":left:left :right:right").unwrap();
973 assert_eq!(doc.blocks.len(), 2);
974 assert!(matches!(
975 doc.blocks[0],
976 Block::Paragraph {
977 align: Align::Left,
978 ..
979 }
980 ));
981 assert!(matches!(
982 doc.blocks[1],
983 Block::Paragraph {
984 align: Align::Right,
985 ..
986 }
987 ));
988 let Block::Paragraph { inlines: left, .. } = &doc.blocks[0] else {
989 panic!();
1012 assert_eq!(doc.blocks.len(), 1);
1013 let Block::AlignedRow { parts } = &doc.blocks[0] else {
1014 panic!("expected AlignedRow, got {:?}", doc.blocks[0]);
990 1015 };
991 let Block::Paragraph { inlines: right, .. } = &doc.blocks[1] else {
1016 assert_eq!(parts.len(), 2);
1017 assert_eq!(parts[0].0, Align::Left);
1018 assert_eq!(parts[1].0, Align::Right);
1019 assert_eq!(inlines_to_text(&parts[0].1), "left");
1020 assert_eq!(inlines_to_text(&parts[1].1), "right");
1021 }
1022
1023 #[test]
1024 fn right_before_left_keeps_source_part_order_in_ast() {
1025 let doc = parse(":right:10:left:appel").unwrap();
1026 let Block::AlignedRow { parts } = &doc.blocks[0] else {
992 1027 panic!();
993 1028 };
994 assert_eq!(inlines_to_text(left), "left");
995 assert_eq!(inlines_to_text(right), "right");
1029 assert_eq!(parts[0].0, Align::Right);
1030 assert_eq!(inlines_to_text(&parts[0].1), "10");
1031 assert_eq!(parts[1].0, Align::Left);
1032 assert_eq!(inlines_to_text(&parts[1].1), "appel");
996 1033 }
997 1034
998 1035 #[test]
@@ -36,6 +36,21 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
36 continue;
36 continue;
37 }
37 }
38
38
39 // Same-line multi-align plain text → one AlignedRow (space-padded at print time).
40 if segments.len() > 1
41 && segments
42 .iter()
43 .all(|(_, seg_text)| is_plain_paragraph_segment(seg_text))
44 {
45 let mut parts = Vec::with_capacity(segments.len());
46 for (seg_align, seg_text) in &segments {
47 current_align = *seg_align;
48 parts.push((*seg_align, parse_inlines(seg_text, line_no, 1)?));
49 }
50 blocks.push(Block::AlignedRow { parts });
51 continue;
52 }
53
39 for (idx, (seg_align, seg_text)) in segments.iter().enumerate() {
54 for (idx, (seg_align, seg_text)) in segments.iter().enumerate() {
40 current_align = *seg_align;
55 current_align = *seg_align;
41 let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1;
56 let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1;
@@ -157,6 +172,21 @@ fn collect_param_kinds_from_block(
157 }
172 }
158 }
173 }
159 }
174 }
175 Block::AlignedRow { parts } => {
176 for (_, inlines) in parts {
177 for inline in inlines {
178 match inline {
179 Inline::Param(name) => {
180 text_names.insert(name.clone());
181 }
182 Inline::CheckboxParam(name) => {
183 bool_names.insert(name.clone());
184 }
185 _ => {}
186 }
187 }
188 }
189 }
160 Block::List { items, .. } => {
190 Block::List { items, .. } => {
161 for item in items {
191 for item in items {
162 for inline in &item.inlines {
192 for inline in &item.inlines {
@@ -245,6 +275,15 @@ fn strip_comments(source: &str) -> String {
245 out
275 out
246}
276}
247
277
278/// True when a segment is ordinary paragraph text (eligible for AlignedRow).
279fn is_plain_paragraph_segment(seg_text: &str) -> bool {
280 !is_blank_feed_line(seg_text)
281 && !seg_text.starts_with('#')
282 && seg_text.trim() != "---"
283 && !seg_text.trim_start().starts_with('@')
284 && !is_list_item_line(seg_text)
285}
286
248/// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start.
287/// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start.
249/// Returns the alignment and optional remaining content on the same line.
288/// Returns the alignment and optional remaining content on the same line.
250fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> {
289fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> {
@@ -970,29 +1009,27 @@ mod tests {
970 #[test]
1009 #[test]
971 fn multiple_align_prefixes_on_one_line() {
1010 fn multiple_align_prefixes_on_one_line() {
972 let doc = parse(":left:left :right:right").unwrap();
1011 let doc = parse(":left:left :right:right").unwrap();
973 assert_eq!(doc.blocks.len(), 2);
1012 assert_eq!(doc.blocks.len(), 1);
974 assert!(matches!(
1013 let Block::AlignedRow { parts } = &doc.blocks[0] else {
975 doc.blocks[0],
1014 panic!("expected AlignedRow, got {:?}", doc.blocks[0]);
976 Block::Paragraph {
977 align: Align::Left,
978 ..
979 }
980 ));
981 assert!(matches!(
982 doc.blocks[1],
983 Block::Paragraph {
984 align: Align::Right,
985 ..
986 }
987 ));
988 let Block::Paragraph { inlines: left, .. } = &doc.blocks[0] else {
989 panic!();
990 };
1015 };
991 let Block::Paragraph { inlines: right, .. } = &doc.blocks[1] else {
1016 assert_eq!(parts.len(), 2);
1017 assert_eq!(parts[0].0, Align::Left);
1018 assert_eq!(parts[1].0, Align::Right);
1019 assert_eq!(inlines_to_text(&parts[0].1), "left");
1020 assert_eq!(inlines_to_text(&parts[1].1), "right");
1021 }
1022
1023 #[test]
1024 fn right_before_left_keeps_source_part_order_in_ast() {
1025 let doc = parse(":right:10:left:appel").unwrap();
1026 let Block::AlignedRow { parts } = &doc.blocks[0] else {
992 panic!();
1027 panic!();
993 };
1028 };
994 assert_eq!(inlines_to_text(left), "left");
1029 assert_eq!(parts[0].0, Align::Right);
995 assert_eq!(inlines_to_text(right), "right");
1030 assert_eq!(inlines_to_text(&parts[0].1), "10");
1031 assert_eq!(parts[1].0, Align::Left);
1032 assert_eq!(inlines_to_text(&parts[1].1), "appel");
996 }
1033 }
997
1034
998 #[test]
1035 #[test]
src/escpos.rs +47 −0
@@ -2,6 +2,7 @@ use std::path::Path;
2 2
3 3 use image::GrayImage;
4 4
5 use crate::align_row::{columns_from_parts, layout_aligned_row_or_lines};
5 6 use crate::dsl::{
6 7 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc, QrMode,
7 8 };
@@ -65,6 +66,20 @@ impl EscPosEncoder {
65 66 self.writeln(&part);
66 67 }
67 68 }
69 Block::AlignedRow { parts } => {
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
71 let plain_parts: Vec<(Align, String)> = parts
72 .iter()
73 .map(|(align, inlines)| (*align, inlines_to_plain(inlines)))
74 .collect();
75 let columns = columns_from_parts(&plain_parts);
76 for (align, line) in layout_aligned_row_or_lines(&columns, cols) {
77 self.set_align(align);
78 for part in text_wrap::wrap_text(&line, cols) {
79 self.writeln(&part);
80 }
81 }
82 }
68 83 Block::List { align, items } => {
69 84 self.set_align(*align);
70 85 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
@@ -469,6 +484,38 @@ mod tests {
469 484 assert!(bytes.windows(5).any(|w| w == b"Hello"));
470 485 }
471 486
487 #[test]
488 fn encodes_inline_left_right_as_one_padded_line() {
489 let doc = parse(":left:appel:right:10").unwrap();
490 let mut enc = EscPosEncoder::new(PosMetadata {
491 chars_per_line: Some(32),
492 ..Default::default()
493 });
494 let bytes = enc.encode_document(&doc).unwrap();
495 let text = String::from_utf8_lossy(bytes);
496 let expected = format!("appel{}10\n", " ".repeat(25));
497 assert!(
498 text.contains(&expected),
499 "expected one padded line, got: {text:?}"
500 );
501 assert!(
502 !text.contains("appel\n"),
503 "left segment must not be its own line: {text:?}"
504 );
505 }
506
507 #[test]
508 fn encodes_right_before_left_reordered() {
509 let doc = parse(":right:10:left:appel").unwrap();
510 let mut enc = EscPosEncoder::new(PosMetadata {
511 chars_per_line: Some(32),
512 ..Default::default()
513 });
514 let bytes = enc.encode_document(&doc).unwrap();
515 let text = String::from_utf8_lossy(bytes);
516 assert!(text.contains(&format!("appel{}10\n", " ".repeat(25))));
517 }
518
472 519 #[test]
473 520 fn encodes_date_directive() {
474 521 let doc = parse("@date DD-YYYY-MM").unwrap();
@@ -2,6 +2,7 @@ use std::path::Path;
2
2
3use image::GrayImage;
3use image::GrayImage;
4
4
5use crate::align_row::{columns_from_parts, layout_aligned_row_or_lines};
5use crate::dsl::{
6use crate::dsl::{
6 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc, QrMode,
7 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, QrEcc, QrMode,
7};
8};
@@ -65,6 +66,20 @@ impl EscPosEncoder {
65 self.writeln(&part);
66 self.writeln(&part);
66 }
67 }
67 }
68 }
69 Block::AlignedRow { parts } => {
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
71 let plain_parts: Vec<(Align, String)> = parts
72 .iter()
73 .map(|(align, inlines)| (*align, inlines_to_plain(inlines)))
74 .collect();
75 let columns = columns_from_parts(&plain_parts);
76 for (align, line) in layout_aligned_row_or_lines(&columns, cols) {
77 self.set_align(align);
78 for part in text_wrap::wrap_text(&line, cols) {
79 self.writeln(&part);
80 }
81 }
82 }
68 Block::List { align, items } => {
83 Block::List { align, items } => {
69 self.set_align(*align);
84 self.set_align(*align);
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
85 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
@@ -469,6 +484,38 @@ mod tests {
469 assert!(bytes.windows(5).any(|w| w == b"Hello"));
484 assert!(bytes.windows(5).any(|w| w == b"Hello"));
470 }
485 }
471
486
487 #[test]
488 fn encodes_inline_left_right_as_one_padded_line() {
489 let doc = parse(":left:appel:right:10").unwrap();
490 let mut enc = EscPosEncoder::new(PosMetadata {
491 chars_per_line: Some(32),
492 ..Default::default()
493 });
494 let bytes = enc.encode_document(&doc).unwrap();
495 let text = String::from_utf8_lossy(bytes);
496 let expected = format!("appel{}10\n", " ".repeat(25));
497 assert!(
498 text.contains(&expected),
499 "expected one padded line, got: {text:?}"
500 );
501 assert!(
502 !text.contains("appel\n"),
503 "left segment must not be its own line: {text:?}"
504 );
505 }
506
507 #[test]
508 fn encodes_right_before_left_reordered() {
509 let doc = parse(":right:10:left:appel").unwrap();
510 let mut enc = EscPosEncoder::new(PosMetadata {
511 chars_per_line: Some(32),
512 ..Default::default()
513 });
514 let bytes = enc.encode_document(&doc).unwrap();
515 let text = String::from_utf8_lossy(bytes);
516 assert!(text.contains(&format!("appel{}10\n", " ".repeat(25))));
517 }
518
472 #[test]
519 #[test]
473 fn encodes_date_directive() {
520 fn encodes_date_directive() {
474 let doc = parse("@date DD-YYYY-MM").unwrap();
521 let doc = parse("@date DD-YYYY-MM").unwrap();
src/lib.rs +1 −0
@@ -1,3 +1,4 @@
1 pub mod align_row;
1 2 pub mod cli;
2 3 pub mod config;
3 4 pub mod datetime;
@@ -1,3 +1,4 @@
1pub mod align_row;
1pub mod cli;
2pub mod cli;
2pub mod config;
3pub mod config;
3pub mod datetime;
4pub mod datetime;
src/params.rs +11 −0
@@ -165,6 +165,12 @@ pub fn substitute_document(
165 165 align: *align,
166 166 inlines: substitute_inlines(inlines, values),
167 167 },
168 Block::AlignedRow { parts } => Block::AlignedRow {
169 parts: parts
170 .iter()
171 .map(|(align, inlines)| (*align, substitute_inlines(inlines, values)))
172 .collect(),
173 },
168 174 Block::Heading { level, align, inlines } => Block::Heading {
169 175 level: *level,
170 176 align: *align,
@@ -241,6 +247,11 @@ fn collect_kinds_from_block(
241 247 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
242 248 collect_kinds_from_inlines(inlines, kinds);
243 249 }
250 Block::AlignedRow { parts } => {
251 for (_, inlines) in parts {
252 collect_kinds_from_inlines(inlines, kinds);
253 }
254 }
244 255 Block::List { items, .. } => {
245 256 for item in items {
246 257 collect_kinds_from_inlines(&item.inlines, kinds);
@@ -165,6 +165,12 @@ pub fn substitute_document(
165 align: *align,
165 align: *align,
166 inlines: substitute_inlines(inlines, values),
166 inlines: substitute_inlines(inlines, values),
167 },
167 },
168 Block::AlignedRow { parts } => Block::AlignedRow {
169 parts: parts
170 .iter()
171 .map(|(align, inlines)| (*align, substitute_inlines(inlines, values)))
172 .collect(),
173 },
168 Block::Heading { level, align, inlines } => Block::Heading {
174 Block::Heading { level, align, inlines } => Block::Heading {
169 level: *level,
175 level: *level,
170 align: *align,
176 align: *align,
@@ -241,6 +247,11 @@ fn collect_kinds_from_block(
241 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
247 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
242 collect_kinds_from_inlines(inlines, kinds);
248 collect_kinds_from_inlines(inlines, kinds);
243 }
249 }
250 Block::AlignedRow { parts } => {
251 for (_, inlines) in parts {
252 collect_kinds_from_inlines(inlines, kinds);
253 }
254 }
244 Block::List { items, .. } => {
255 Block::List { items, .. } => {
245 for item in items {
256 for item in items {
246 collect_kinds_from_inlines(&item.inlines, kinds);
257 collect_kinds_from_inlines(&item.inlines, kinds);
src/preview.rs +47 −0
@@ -3,6 +3,7 @@ use std::path::Path;
3 3
4 4 use image::GrayImage;
5 5
6 use crate::align_row::{columns_from_parts, layout_aligned_row_or_lines};
6 7 use crate::dsl::{
7 8 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
8 9 };
@@ -68,6 +69,28 @@ pub fn render_preview(
68 69 });
69 70 }
70 71 }
72 Block::AlignedRow { parts } => {
73 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
74 let plain_parts: Vec<(Align, String)> = parts
75 .iter()
76 .map(|(align, inlines)| {
77 (
78 *align,
79 substitute_inlines_for_preview(inlines, preview_params),
80 )
81 })
82 .collect();
83 let columns = columns_from_parts(&plain_parts);
84 for (align, line) in layout_aligned_row_or_lines(&columns, cols) {
85 for wrapped in text_wrap::wrap_text(&line, cols) {
86 lines.push(PreviewLine::Text {
87 content: wrapped,
88 align,
89 style: TextStyle::Normal,
90 });
91 }
92 }
93 }
71 94 Block::List { align, items } => {
72 95 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
73 96 for item in items {
@@ -485,6 +508,30 @@ mod tests {
485 508 assert_eq!(*align, Align::Center);
486 509 }
487 510
511 #[test]
512 fn inline_left_right_is_one_preview_line() {
513 let doc = parse(":left:appel:right:10").unwrap();
514 let meta = PosMetadata {
515 chars_per_line: Some(32),
516 ..Default::default()
517 };
518 let model = render_preview(&doc, &meta, None, &HashMap::new());
519 let text_lines: Vec<_> = model
520 .lines
521 .iter()
522 .filter_map(|l| match l {
523 PreviewLine::Text { content, align, .. } => Some((content.as_str(), *align)),
524 _ => None,
525 })
526 .collect();
527 assert_eq!(text_lines.len(), 1);
528 assert_eq!(text_lines[0].1, Align::Left);
529 assert_eq!(
530 text_lines[0].0,
531 format!("appel{}10", " ".repeat(25))
532 );
533 }
534
488 535 #[test]
489 536 fn heading_wraps_in_preview_on_narrow_paper() {
490 537 let doc = parse("# Proof of Transfer").unwrap();
@@ -3,6 +3,7 @@ use std::path::Path;
3
3
4use image::GrayImage;
4use image::GrayImage;
5
5
6use crate::align_row::{columns_from_parts, layout_aligned_row_or_lines};
6use crate::dsl::{
7use crate::dsl::{
7 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
8 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
8};
9};
@@ -68,6 +69,28 @@ pub fn render_preview(
68 });
69 });
69 }
70 }
70 }
71 }
72 Block::AlignedRow { parts } => {
73 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
74 let plain_parts: Vec<(Align, String)> = parts
75 .iter()
76 .map(|(align, inlines)| {
77 (
78 *align,
79 substitute_inlines_for_preview(inlines, preview_params),
80 )
81 })
82 .collect();
83 let columns = columns_from_parts(&plain_parts);
84 for (align, line) in layout_aligned_row_or_lines(&columns, cols) {
85 for wrapped in text_wrap::wrap_text(&line, cols) {
86 lines.push(PreviewLine::Text {
87 content: wrapped,
88 align,
89 style: TextStyle::Normal,
90 });
91 }
92 }
93 }
71 Block::List { align, items } => {
94 Block::List { align, items } => {
72 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
95 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
73 for item in items {
96 for item in items {
@@ -485,6 +508,30 @@ mod tests {
485 assert_eq!(*align, Align::Center);
508 assert_eq!(*align, Align::Center);
486 }
509 }
487
510
511 #[test]
512 fn inline_left_right_is_one_preview_line() {
513 let doc = parse(":left:appel:right:10").unwrap();
514 let meta = PosMetadata {
515 chars_per_line: Some(32),
516 ..Default::default()
517 };
518 let model = render_preview(&doc, &meta, None, &HashMap::new());
519 let text_lines: Vec<_> = model
520 .lines
521 .iter()
522 .filter_map(|l| match l {
523 PreviewLine::Text { content, align, .. } => Some((content.as_str(), *align)),
524 _ => None,
525 })
526 .collect();
527 assert_eq!(text_lines.len(), 1);
528 assert_eq!(text_lines[0].1, Align::Left);
529 assert_eq!(
530 text_lines[0].0,
531 format!("appel{}10", " ".repeat(25))
532 );
533 }
534
488 #[test]
535 #[test]
489 fn heading_wraps_in_preview_on_narrow_paper() {
536 fn heading_wraps_in_preview_on_narrow_paper() {
490 let doc = parse("# Proof of Transfer").unwrap();
537 let doc = parse("# Proof of Transfer").unwrap();