BlueGit

timfa posprint

checkboxes

timfa Tim Falken · pushed by timfa

Authored 2026-07-17 · 4 months ago

Hash
00ee9454fbf4881a2e2ca71815309f0a6389e69a
Parent
c8ba41d4
12 files changed +145 −62
docs/ARCHITECTURE.md +2 −2
@@ -107,7 +107,7 @@ While the print dialog is open, the main UI is disabled and editor autocomplete
107 107 struct Document { blocks: Vec<Block> }
108 108 enum Block {
109 109 Paragraph { align, inlines },
110 List { align, items },
110 List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
111 111 Heading { level, align, inlines },
112 112 Rule, Feed(u8), Cut,
113 113 Image { path, width, align },
@@ -116,7 +116,7 @@ enum Block {
116 116 Date { format, align },
117 117 Time { format, align },
118 118 }
119 enum Inline { Text(String), Param(String) }
119 enum Inline { Text(String), Param(String), CheckboxParam(String), Checkbox { checked } }
120 120
121 121 // io/
122 122 struct PosMetadata { title, page_width_mm, chars_per_line, codepage }
@@ -107,7 +107,7 @@ While the print dialog is open, the main UI is disabled and editor autocomplete
107struct Document { blocks: Vec<Block> }
107struct Document { blocks: Vec<Block> }
108enum Block {
108enum Block {
109 Paragraph { align, inlines },
109 Paragraph { align, inlines },
110 List { align, items },
110 List { align, items: Vec<ListItem> }, // ListItem { depth, inlines }
111 Heading { level, align, inlines },
111 Heading { level, align, inlines },
112 Rule, Feed(u8), Cut,
112 Rule, Feed(u8), Cut,
113 Image { path, width, align },
113 Image { path, width, align },
@@ -116,7 +116,7 @@ enum Block {
116 Date { format, align },
116 Date { format, align },
117 Time { format, align },
117 Time { format, align },
118}
118}
119enum Inline { Text(String), Param(String) }
119enum Inline { Text(String), Param(String), CheckboxParam(String), Checkbox { checked } }
120
120
121// io/
121// io/
122struct PosMetadata { title, page_width_mm, chars_per_line, codepage }
122struct PosMetadata { title, page_width_mm, chars_per_line, codepage }
docs/DSL-SPEC.md +21 −13
@@ -57,18 +57,26 @@ Total: ${Amount}
57 57 ### Bullet lists
58 58
59 59 ```markdown
60 - Milk
61 - Bread
62 - Eggs
60 - Groceries
61 - Milk
62 - Eggs
63 - Wash car
63 64 ```
64 65
65 Each line must start with `- ` (dash + space). Consecutive list lines form one list block. A blank line ends the list.
66 Each line must start with optional indent (2 spaces or 1 tab per level) then `- `. Consecutive list lines form one list block. A blank line ends the list.
66 67
67 Wrapped lines use a hanging indent:
68 | Depth | Printed bullet |
69 |-------|----------------|
70 | 0 (top) | `* ` |
71 | ≥ 1 | indented `- ` |
72
73 Wrapped lines use a hanging indent matching the bullet prefix width:
68 74
69 75 ```text
70 76 * this is a
71 77 long line
78 - nested item that
79 wraps too
72 80 ```
73 81
74 82 ### Parameters
@@ -76,7 +84,7 @@ Wrapped lines use a hanging indent:
76 84 | Syntax | Effect |
77 85 |--------|--------|
78 86 | `${Name}` | Text parameter placeholder (see Parameters) |
79 | `$[Name]` | Bool checkbox parameter → `[ ]` / `[√]` |
87 | `$[Name]` | Bool checkbox parameter → `[ ]` / `[x]` |
80 88
81 89 `${Name}` and `$[Name]` must not share the same name.
82 90
@@ -85,10 +93,10 @@ Wrapped lines use a hanging indent:
85 93 | Syntax | Printed result |
86 94 |--------|----------------|
87 95 | `[]` or `[ ]` | `[ ]` |
88 | `[x]` / `[X]` / `[√]` | `[√]` (CP437 byte `0xFB`) |
89 | `$[Name]` | `[ ]` or `[√]` from a bool parameter |
96 | `[x]` / `[X]` / `[x]` | `[x]` (CP437 byte `0xFB`) |
97 | `$[Name]` | `[ ]` or `[x]` from a bool parameter |
90 98
91 ASCII brackets + CP437 `√` stay inline in the native font. `${Name}` and `$[Name]` cannot share a name.
99 ASCII brackets + CP437 `x` stay inline in the native font. `${Name}` and `$[Name]` cannot share a name.
92 100
93 101 Parameters work inside any text, and inside barcode/QR/image directives (below).
94 102
@@ -212,7 +220,7 @@ Raster barcodes stretch horizontally to full printable width.
212 220
213 221 ```
214 222 ${ParameterName} # text
215 $[ParameterName] # boolean checkbox → [ ] / [√]
223 $[ParameterName] # boolean checkbox → [ ] / [x]
216 224 ```
217 225
218 226 - **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
@@ -275,8 +283,8 @@ Parse errors include 1-based line and column. Typical causes:
275 283 |-----|---------|
276 284 | `# heading` | Double width/height ON → text → OFF |
277 285 | `## heading` | Bold ON → text → OFF |
278 | `- item` | ASCII `* ` bullet + hanging wrap |
279 | `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[√]` (CP437-safe, inline) |
286 | `- item` / ` - nested` | Top: ASCII `* `; nested: indented `- ` + hanging wrap |
287 | `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[x]` (CP437-safe, inline) |
280 288 | `:center:` | Justification center |
281 289 | `@feed n` / blank line | ESC d n |
282 290 | `@cut` | GS V partial cut |
@@ -292,7 +300,7 @@ Full command details: [PRINTING.md](PRINTING.md).
292 300 ## Future extensions (not implemented)
293 301
294 302 - `@table` for columnar line items
295 - Nested lists / numbered lists
303 - Numbered lists
296 304 - Bluetooth / network printer transports
297 305 - Syntax highlighting in the editor
298 306
@@ -57,18 +57,26 @@ Total: ${Amount}
57### Bullet lists
57### Bullet lists
58
58
59```markdown
59```markdown
60- Milk
60- Groceries
61- Bread
61 - Milk
62- Eggs
62 - Eggs
63- Wash car
63```
64```
64
65
65Each line must start with `- ` (dash + space). Consecutive list lines form one list block. A blank line ends the list.
66Each line must start with optional indent (2 spaces or 1 tab per level) then `- `. Consecutive list lines form one list block. A blank line ends the list.
66
67
67Wrapped lines use a hanging indent:
68| Depth | Printed bullet |
69|-------|----------------|
70| 0 (top) | `* ` |
71| ≥ 1 | indented `- ` |
72
73Wrapped lines use a hanging indent matching the bullet prefix width:
68
74
69```text
75```text
70* this is a
76* this is a
71 long line
77 long line
78 - nested item that
79 wraps too
72```
80```
73
81
74### Parameters
82### Parameters
@@ -76,7 +84,7 @@ Wrapped lines use a hanging indent:
76| Syntax | Effect |
84| Syntax | Effect |
77|--------|--------|
85|--------|--------|
78| `${Name}` | Text parameter placeholder (see Parameters) |
86| `${Name}` | Text parameter placeholder (see Parameters) |
79| `$[Name]` | Bool checkbox parameter → `[ ]` / `[√]` |
87| `$[Name]` | Bool checkbox parameter → `[ ]` / `[x]` |
80
88
81`${Name}` and `$[Name]` must not share the same name.
89`${Name}` and `$[Name]` must not share the same name.
82
90
@@ -85,10 +93,10 @@ Wrapped lines use a hanging indent:
85| Syntax | Printed result |
93| Syntax | Printed result |
86|--------|----------------|
94|--------|----------------|
87| `[]` or `[ ]` | `[ ]` |
95| `[]` or `[ ]` | `[ ]` |
88| `[x]` / `[X]` / `[√]` | `[√]` (CP437 byte `0xFB`) |
96| `[x]` / `[X]` / `[x]` | `[x]` (CP437 byte `0xFB`) |
89| `$[Name]` | `[ ]` or `[√]` from a bool parameter |
97| `$[Name]` | `[ ]` or `[x]` from a bool parameter |
90
98
91ASCII brackets + CP437 `√` stay inline in the native font. `${Name}` and `$[Name]` cannot share a name.
99ASCII brackets + CP437 `x` stay inline in the native font. `${Name}` and `$[Name]` cannot share a name.
92
100
93Parameters work inside any text, and inside barcode/QR/image directives (below).
101Parameters work inside any text, and inside barcode/QR/image directives (below).
94
102
@@ -212,7 +220,7 @@ Raster barcodes stretch horizontally to full printable width.
212
220
213```
221```
214${ParameterName} # text
222${ParameterName} # text
215$[ParameterName] # boolean checkbox → [ ] / [√]
223$[ParameterName] # boolean checkbox → [ ] / [x]
216```
224```
217
225
218- **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
226- **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
@@ -275,8 +283,8 @@ Parse errors include 1-based line and column. Typical causes:
275|-----|---------|
283|-----|---------|
276| `# heading` | Double width/height ON → text → OFF |
284| `# heading` | Double width/height ON → text → OFF |
277| `## heading` | Bold ON → text → OFF |
285| `## heading` | Bold ON → text → OFF |
278| `- item` | ASCII `* ` bullet + hanging wrap |
286| `- item` / ` - nested` | Top: ASCII `* `; nested: indented `- ` + hanging wrap |
279| `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[√]` (CP437-safe, inline) |
287| `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[x]` (CP437-safe, inline) |
280| `:center:` | Justification center |
288| `:center:` | Justification center |
281| `@feed n` / blank line | ESC d n |
289| `@feed n` / blank line | ESC d n |
282| `@cut` | GS V partial cut |
290| `@cut` | GS V partial cut |
@@ -292,7 +300,7 @@ Full command details: [PRINTING.md](PRINTING.md).
292## Future extensions (not implemented)
300## Future extensions (not implemented)
293
301
294- `@table` for columnar line items
302- `@table` for columnar line items
295- Nested lists / numbered lists
303- Numbered lists
296- Bluetooth / network printer transports
304- Bluetooth / network printer transports
297- Syntax highlighting in the editor
305- Syntax highlighting in the editor
298
306
docs/HELP.md +19 −6
@@ -63,15 +63,28 @@ Consecutive non-empty lines form one paragraph.
63 63 ### Bullet lists
64 64
65 65 ```markdown
66 - first item
67 - second item
66 - Groceries
67 - Milk
68 - Eggs
69 - Wash car
68 70 ```
69 71
70 Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
72 Indent with two spaces (or a tab) per nesting level. Top-level items print as `* `; nested items print as `- ` with the same hanging wrap.
73
74 ```text
75 * Groceries
76 - Milk
77 - Eggs
78 * Wash car
79 ```
80
81 Long items wrap with a hanging indent:
71 82
72 83 ```text
73 84 * this is a
74 85 long line
86 - nested item that
87 wraps too
75 88 ```
76 89
77 90 ### Parameters
@@ -79,7 +92,7 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
79 92 | Syntax | Effect |
80 93 |--------|--------|
81 94 | `${Name}` | Text parameter (filled at print time) |
82 | `$[Name]` | Checkbox parameter → `[ ]` or `[√]` |
95 | `$[Name]` | Checkbox parameter → `[ ]` or `[x]` |
83 96
84 97 `${Name}` and `$[Name]` must not share the same name.
85 98
@@ -90,7 +103,7 @@ Inline checkboxes use ASCII brackets plus a CP437 check mark so they print in th
90 103 | Syntax | Result |
91 104 |--------|--------|
92 105 | `[]` or `[ ]` | `[ ]` |
93 | `[x]`, `[X]`, or `[√]` | `[√]` (CP437 `√`) |
106 | `[x]`, `[X]`, or `[x]` | `[x]` (CP437 `x`) |
94 107
95 108 ```markdown
96 109 [] Unchecked
@@ -99,7 +112,7 @@ Inline checkboxes use ASCII brackets plus a CP437 check mark so they print in th
99 112 $[Paid]
100 113 ```
101 114
102 `$[Paid]` is a **parameter**: in the Print dialog it is a true/false checkbox; on the receipt it becomes `[ ]` or `[√]`. CLI: `--set Paid=true`.
115 `$[Paid]` is a **parameter**: in the Print dialog it is a true/false checkbox; on the receipt it becomes `[ ]` or `[x]`. CLI: `--set Paid=true`.
103 116
104 117 Unicode ballot boxes are not used (they become CJK garbage on CP437 printers).
105 118
@@ -63,15 +63,28 @@ Consecutive non-empty lines form one paragraph.
63### Bullet lists
63### Bullet lists
64
64
65```markdown
65```markdown
66- first item
66- Groceries
67- second item
67 - Milk
68 - Eggs
69- Wash car
68```
70```
69
71
70Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
72Indent with two spaces (or a tab) per nesting level. Top-level items print as `* `; nested items print as `- ` with the same hanging wrap.
73
74```text
75* Groceries
76 - Milk
77 - Eggs
78* Wash car
79```
80
81Long items wrap with a hanging indent:
71
82
72```text
83```text
73* this is a
84* this is a
74 long line
85 long line
86 - nested item that
87 wraps too
75```
88```
76
89
77### Parameters
90### Parameters
@@ -79,7 +92,7 @@ Long items wrap with a hanging indent (printed/previewed as ASCII `*`):
79| Syntax | Effect |
92| Syntax | Effect |
80|--------|--------|
93|--------|--------|
81| `${Name}` | Text parameter (filled at print time) |
94| `${Name}` | Text parameter (filled at print time) |
82| `$[Name]` | Checkbox parameter → `[ ]` or `[√]` |
95| `$[Name]` | Checkbox parameter → `[ ]` or `[x]` |
83
96
84`${Name}` and `$[Name]` must not share the same name.
97`${Name}` and `$[Name]` must not share the same name.
85
98
@@ -90,7 +103,7 @@ Inline checkboxes use ASCII brackets plus a CP437 check mark so they print in th
90| Syntax | Result |
103| Syntax | Result |
91|--------|--------|
104|--------|--------|
92| `[]` or `[ ]` | `[ ]` |
105| `[]` or `[ ]` | `[ ]` |
93| `[x]`, `[X]`, or `[√]` | `[√]` (CP437 `√`) |
106| `[x]`, `[X]`, or `[x]` | `[x]` (CP437 `x`) |
94
107
95```markdown
108```markdown
96[] Unchecked
109[] Unchecked
@@ -99,7 +112,7 @@ Inline checkboxes use ASCII brackets plus a CP437 check mark so they print in th
99$[Paid]
112$[Paid]
100```
113```
101
114
102`$[Paid]` is a **parameter**: in the Print dialog it is a true/false checkbox; on the receipt it becomes `[ ]` or `[√]`. CLI: `--set Paid=true`.
115`$[Paid]` is a **parameter**: in the Print dialog it is a true/false checkbox; on the receipt it becomes `[ ]` or `[x]`. CLI: `--set Paid=true`.
103
116
104Unicode ballot boxes are not used (they become CJK garbage on CP437 printers).
117Unicode ballot boxes are not used (they become CJK garbage on CP437 printers).
105
118
docs/PRINTING.md +2 −2
@@ -28,8 +28,8 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
28 28 | Alignment | ESC a | Paragraphs, images, barcodes, QR |
29 29 | Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
30 30 | Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
31 | List bullet | ASCII `*` | `- item` lines in templates |
32 | Inline checkbox | ASCII `[ ]` / `[√]` (CP437 `0xFB`) | `[]` / `[x]` / `$[Name]` — same font as text |
31 | List bullet | `*` top-level, `-` nested | `- item` / ` - nested`; hanging wrap |
32 | Inline checkbox | ASCII `[ ]` / `[x]` (CP437 `0xFB`) | `[]` / `[x]` / `$[Name]` — same font as text |
33 33 | Partial cut | GS V 66 0 | `@cut` in template only |
34 34 | Barcode | GS k | Native symbologies; raster via GS v 0 |
35 35 | QR Code | GS ( k | Model 2; or raster GS v 0 |
@@ -28,8 +28,8 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
28| Alignment | ESC a | Paragraphs, images, barcodes, QR |
28| Alignment | ESC a | Paragraphs, images, barcodes, QR |
29| Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
29| Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
30| Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
30| Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
31| List bullet | ASCII `*` | `- item` lines in templates |
31| List bullet | `*` top-level, `-` nested | `- item` / ` - nested`; hanging wrap |
32| Inline checkbox | ASCII `[ ]` / `[√]` (CP437 `0xFB`) | `[]` / `[x]` / `$[Name]` — same font as text |
32| Inline checkbox | ASCII `[ ]` / `[x]` (CP437 `0xFB`) | `[]` / `[x]` / `$[Name]` — same font as text |
33| Partial cut | GS V 66 0 | `@cut` in template only |
33| Partial cut | GS V 66 0 | `@cut` in template only |
34| Barcode | GS k | Native symbologies; raster via GS v 0 |
34| Barcode | GS k | Native symbologies; raster via GS v 0 |
35| QR Code | GS ( k | Model 2; or raster GS v 0 |
35| QR Code | GS ( k | Model 2; or raster GS v 0 |
examples/print_checkbox_test.rs +1 −1
@@ -32,5 +32,5 @@ fn main() {
32 32 println!("Printing checkbox test to: {}", device.display_name);
33 33 let mut transport = open_printer(&device.target).expect("open printer");
34 34 print_bytes(&mut transport, &bytes).expect("print");
35 println!("OK — check paper for [ ] / [ ] / [√] / [√] (last from $[Paid]=true)");
35 println!("OK — check paper for [ ] / [ ] / [x] / [x] (last from $[Paid]=true)");
36 36 }
@@ -32,5 +32,5 @@ fn main() {
32 println!("Printing checkbox test to: {}", device.display_name);
32 println!("Printing checkbox test to: {}", device.display_name);
33 let mut transport = open_printer(&device.target).expect("open printer");
33 let mut transport = open_printer(&device.target).expect("open printer");
34 print_bytes(&mut transport, &bytes).expect("print");
34 print_bytes(&mut transport, &bytes).expect("print");
35 println!("OK — check paper for [ ] / [ ] / [√] / [√] (last from $[Paid]=true)");
35 println!("OK — check paper for [ ] / [ ] / [x] / [x] (last from $[Paid]=true)");
36}
36}
src/dsl/mod.rs +12 −5
@@ -32,7 +32,7 @@ pub enum Block {
32 32 },
33 33 List {
34 34 align: Align,
35 items: Vec<Vec<Inline>>,
35 items: Vec<ListItem>,
36 36 },
37 37 Heading {
38 38 level: u8,
@@ -73,6 +73,13 @@ pub enum Block {
73 73 },
74 74 }
75 75
76 /// One bullet in a [`Block::List`], with nesting depth (0 = top level).
77 #[derive(Debug, Clone, PartialEq, Eq)]
78 pub struct ListItem {
79 pub depth: u8,
80 pub inlines: Vec<Inline>,
81 }
82
76 83 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77 84 pub enum TimeFormatSpec {
78 85 #[default]
@@ -136,18 +143,18 @@ pub enum Inline {
136 143 Text(String),
137 144 /// Text parameter: `${Name}`.
138 145 Param(String),
139 /// Boolean checkbox parameter: `$[Name]` → `[ ]` or `[√]` at print time.
146 /// Boolean checkbox parameter: `$[Name]` → `[ ]` or `[x]` at print time.
140 147 CheckboxParam(String),
141 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` / `[√]` (checked).
148 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` / `[x]` (checked).
142 149 Checkbox {
143 150 checked: bool,
144 151 },
145 152 }
146 153
147 /// Checkbox glyphs for preview / wrap width. Print maps `√` (U+221A) to CP437 `0xFB`.
154 /// Checkbox glyphs for preview / wrap width. Print maps `x` (U+221A) to CP437 `0xFB`.
148 155 pub fn checkbox_glyph(checked: bool) -> &'static str {
149 156 if checked {
150 "[\u{221A}]" // √ — CP437 byte 0xFB when encoded for the printer
157 "[\u{221A}]" // x — CP437 byte 0xFB when encoded for the printer
151 158 } else {
152 159 "[ ]"
153 160 }
@@ -32,7 +32,7 @@ pub enum Block {
32 },
32 },
33 List {
33 List {
34 align: Align,
34 align: Align,
35 items: Vec<Vec<Inline>>,
35 items: Vec<ListItem>,
36 },
36 },
37 Heading {
37 Heading {
38 level: u8,
38 level: u8,
@@ -73,6 +73,13 @@ pub enum Block {
73 },
73 },
74}
74}
75
75
76/// One bullet in a [`Block::List`], with nesting depth (0 = top level).
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ListItem {
79 pub depth: u8,
80 pub inlines: Vec<Inline>,
81}
82
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub enum TimeFormatSpec {
84pub enum TimeFormatSpec {
78 #[default]
85 #[default]
@@ -136,18 +143,18 @@ pub enum Inline {
136 Text(String),
143 Text(String),
137 /// Text parameter: `${Name}`.
144 /// Text parameter: `${Name}`.
138 Param(String),
145 Param(String),
139 /// Boolean checkbox parameter: `$[Name]` → `[ ]` or `[√]` at print time.
146 /// Boolean checkbox parameter: `$[Name]` → `[ ]` or `[x]` at print time.
140 CheckboxParam(String),
147 CheckboxParam(String),
141 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` / `[√]` (checked).
148 /// Inline checkbox: `[]` / `[ ]` (empty) or `[x]` / `[X]` / `[x]` (checked).
142 Checkbox {
149 Checkbox {
143 checked: bool,
150 checked: bool,
144 },
151 },
145}
152}
146
153
147/// Checkbox glyphs for preview / wrap width. Print maps `√` (U+221A) to CP437 `0xFB`.
154/// Checkbox glyphs for preview / wrap width. Print maps `x` (U+221A) to CP437 `0xFB`.
148pub fn checkbox_glyph(checked: bool) -> &'static str {
155pub fn checkbox_glyph(checked: bool) -> &'static str {
149 if checked {
156 if checked {
150 "[\u{221A}]" // √ — CP437 byte 0xFB when encoded for the printer
157 "[\u{221A}]" // x — CP437 byte 0xFB when encoded for the printer
151 } else {
158 } else {
152 "[ ]"
159 "[ ]"
153 }
160 }
src/dsl/parser.rs +44 −11
@@ -1,6 +1,6 @@
1 1 use super::{
2 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ParseError, QrEcc,
3 QrMode,
2 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ListItem, ParseError,
3 QrEcc, QrMode,
4 4 };
5 5
6 6 pub fn parse(source: &str) -> Result<Document, ParseError> {
@@ -61,7 +61,7 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
61 61 }
62 62
63 63 if is_list_item_line(seg_text) {
64 let mut items = vec![parse_list_item_inlines(seg_text, line_no)?];
64 let mut items = vec![parse_list_item(seg_text, line_no)?];
65 65 while let Some(&next) = lines.peek() {
66 66 if is_blank_feed_line(next)
67 67 || next.starts_with('#')
@@ -74,7 +74,7 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
74 74 }
75 75 line_no += 1;
76 76 let next_line = lines.next().unwrap().trim_end();
77 items.push(parse_list_item_inlines(next_line, line_no)?);
77 items.push(parse_list_item(next_line, line_no)?);
78 78 }
79 79 blocks.push(Block::List {
80 80 align: *seg_align,
@@ -159,7 +159,7 @@ fn collect_param_kinds_from_block(
159 159 }
160 160 Block::List { items, .. } => {
161 161 for item in items {
162 for inline in item {
162 for inline in &item.inlines {
163 163 match inline {
164 164 Inline::Param(name) => {
165 165 text_names.insert(name.clone());
@@ -610,6 +610,19 @@ fn is_list_item_line(line: &str) -> bool {
610 610 line.trim_start().starts_with("- ")
611 611 }
612 612
613 /// Nesting depth from leading whitespace: two spaces (or one tab) per level.
614 fn list_item_depth(line: &str) -> u8 {
615 let mut spaces = 0u32;
616 for ch in line.chars() {
617 match ch {
618 ' ' => spaces += 1,
619 '\t' => spaces += 2,
620 _ => break,
621 }
622 }
623 spaces.div_euclid(2).min(u32::from(u8::MAX)) as u8
624 }
625
613 626 fn list_item_text(line: &str) -> &str {
614 627 line.trim_start()
615 628 .strip_prefix("- ")
@@ -617,8 +630,11 @@ fn list_item_text(line: &str) -> &str {
617 630 .unwrap_or(line.trim_end())
618 631 }
619 632
620 fn parse_list_item_inlines(line: &str, line_no: usize) -> Result<Vec<Inline>, ParseError> {
621 parse_inlines(list_item_text(line), line_no, 1)
633 fn parse_list_item(line: &str, line_no: usize) -> Result<ListItem, ParseError> {
634 Ok(ListItem {
635 depth: list_item_depth(line),
636 inlines: parse_inlines(list_item_text(line), line_no, 1)?,
637 })
622 638 }
623 639
624 640 fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
@@ -695,7 +711,7 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
695 711 Ok(out)
696 712 }
697 713
698 /// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[√]` at the start of `chars`.
714 /// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[x]` at the start of `chars`.
699 715 /// Returns `(checked, chars_consumed)`.
700 716 fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
701 717 if chars.first() != Some(&'[') {
@@ -799,9 +815,26 @@ mod tests {
799 815 panic!("expected list");
800 816 };
801 817 assert_eq!(items.len(), 3);
802 assert_eq!(inlines_to_text(&items[0]), "this");
803 assert_eq!(inlines_to_text(&items[1]), "is then");
804 assert_eq!(inlines_to_text(&items[2]), "a list");
818 assert_eq!(inlines_to_text(&items[0].inlines), "this");
819 assert_eq!(inlines_to_text(&items[1].inlines), "is then");
820 assert_eq!(inlines_to_text(&items[2].inlines), "a list");
821 assert_eq!(items[0].depth, 0);
822 }
823
824 #[test]
825 fn parses_nested_bullet_list() {
826 let doc = parse("- Groceries\n - Milk\n - Eggs\n- Wash car").unwrap();
827 let Block::List { items, .. } = &doc.blocks[0] else {
828 panic!("expected list");
829 };
830 assert_eq!(items.len(), 4);
831 assert_eq!(items[0].depth, 0);
832 assert_eq!(inlines_to_text(&items[0].inlines), "Groceries");
833 assert_eq!(items[1].depth, 1);
834 assert_eq!(inlines_to_text(&items[1].inlines), "Milk");
835 assert_eq!(items[2].depth, 1);
836 assert_eq!(items[3].depth, 0);
837 assert_eq!(inlines_to_text(&items[3].inlines), "Wash car");
805 838 }
806 839
807 840 #[test]
@@ -1,6 +1,6 @@
1use super::{
1use super::{
2 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ParseError, QrEcc,
2 Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, Inline, ListItem, ParseError,
3 QrMode,
3 QrEcc, QrMode,
4};
4};
5
5
6pub fn parse(source: &str) -> Result<Document, ParseError> {
6pub fn parse(source: &str) -> Result<Document, ParseError> {
@@ -61,7 +61,7 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
61 }
61 }
62
62
63 if is_list_item_line(seg_text) {
63 if is_list_item_line(seg_text) {
64 let mut items = vec![parse_list_item_inlines(seg_text, line_no)?];
64 let mut items = vec![parse_list_item(seg_text, line_no)?];
65 while let Some(&next) = lines.peek() {
65 while let Some(&next) = lines.peek() {
66 if is_blank_feed_line(next)
66 if is_blank_feed_line(next)
67 || next.starts_with('#')
67 || next.starts_with('#')
@@ -74,7 +74,7 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
74 }
74 }
75 line_no += 1;
75 line_no += 1;
76 let next_line = lines.next().unwrap().trim_end();
76 let next_line = lines.next().unwrap().trim_end();
77 items.push(parse_list_item_inlines(next_line, line_no)?);
77 items.push(parse_list_item(next_line, line_no)?);
78 }
78 }
79 blocks.push(Block::List {
79 blocks.push(Block::List {
80 align: *seg_align,
80 align: *seg_align,
@@ -159,7 +159,7 @@ fn collect_param_kinds_from_block(
159 }
159 }
160 Block::List { items, .. } => {
160 Block::List { items, .. } => {
161 for item in items {
161 for item in items {
162 for inline in item {
162 for inline in &item.inlines {
163 match inline {
163 match inline {
164 Inline::Param(name) => {
164 Inline::Param(name) => {
165 text_names.insert(name.clone());
165 text_names.insert(name.clone());
@@ -610,6 +610,19 @@ fn is_list_item_line(line: &str) -> bool {
610 line.trim_start().starts_with("- ")
610 line.trim_start().starts_with("- ")
611}
611}
612
612
613/// Nesting depth from leading whitespace: two spaces (or one tab) per level.
614fn list_item_depth(line: &str) -> u8 {
615 let mut spaces = 0u32;
616 for ch in line.chars() {
617 match ch {
618 ' ' => spaces += 1,
619 '\t' => spaces += 2,
620 _ => break,
621 }
622 }
623 spaces.div_euclid(2).min(u32::from(u8::MAX)) as u8
624}
625
613fn list_item_text(line: &str) -> &str {
626fn list_item_text(line: &str) -> &str {
614 line.trim_start()
627 line.trim_start()
615 .strip_prefix("- ")
628 .strip_prefix("- ")
@@ -617,8 +630,11 @@ fn list_item_text(line: &str) -> &str {
617 .unwrap_or(line.trim_end())
630 .unwrap_or(line.trim_end())
618}
631}
619
632
620fn parse_list_item_inlines(line: &str, line_no: usize) -> Result<Vec<Inline>, ParseError> {
633fn parse_list_item(line: &str, line_no: usize) -> Result<ListItem, ParseError> {
621 parse_inlines(list_item_text(line), line_no, 1)
634 Ok(ListItem {
635 depth: list_item_depth(line),
636 inlines: parse_inlines(list_item_text(line), line_no, 1)?,
637 })
622}
638}
623
639
624fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
640fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, ParseError> {
@@ -695,7 +711,7 @@ fn parse_inlines(input: &str, line: usize, col: usize) -> Result<Vec<Inline>, Pa
695 Ok(out)
711 Ok(out)
696}
712}
697
713
698/// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[√]` at the start of `chars`.
714/// Parse `[]`, `[ ]`, `[x]`, `[X]`, or `[x]` at the start of `chars`.
699/// Returns `(checked, chars_consumed)`.
715/// Returns `(checked, chars_consumed)`.
700fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
716fn try_parse_checkbox(chars: &[char]) -> Option<(bool, usize)> {
701 if chars.first() != Some(&'[') {
717 if chars.first() != Some(&'[') {
@@ -799,9 +815,26 @@ mod tests {
799 panic!("expected list");
815 panic!("expected list");
800 };
816 };
801 assert_eq!(items.len(), 3);
817 assert_eq!(items.len(), 3);
802 assert_eq!(inlines_to_text(&items[0]), "this");
818 assert_eq!(inlines_to_text(&items[0].inlines), "this");
803 assert_eq!(inlines_to_text(&items[1]), "is then");
819 assert_eq!(inlines_to_text(&items[1].inlines), "is then");
804 assert_eq!(inlines_to_text(&items[2]), "a list");
820 assert_eq!(inlines_to_text(&items[2].inlines), "a list");
821 assert_eq!(items[0].depth, 0);
822 }
823
824 #[test]
825 fn parses_nested_bullet_list() {
826 let doc = parse("- Groceries\n - Milk\n - Eggs\n- Wash car").unwrap();
827 let Block::List { items, .. } = &doc.blocks[0] else {
828 panic!("expected list");
829 };
830 assert_eq!(items.len(), 4);
831 assert_eq!(items[0].depth, 0);
832 assert_eq!(inlines_to_text(&items[0].inlines), "Groceries");
833 assert_eq!(items[1].depth, 1);
834 assert_eq!(inlines_to_text(&items[1].inlines), "Milk");
835 assert_eq!(items[2].depth, 1);
836 assert_eq!(items[3].depth, 0);
837 assert_eq!(inlines_to_text(&items[3].inlines), "Wash car");
805 }
838 }
806
839
807 #[test]
840 #[test]
src/editor_assist.rs +3 −3
@@ -302,7 +302,7 @@ mod tests {
302 302
303 303 #[test]
304 304 fn char_index_to_byte_handles_multibyte() {
305 let s = "a√b"; // √ is U+221A, three UTF-8 bytes
305 let s = "axb"; // x is U+221A, three UTF-8 bytes
306 306 assert_eq!(char_index_to_byte(s, 0), 0);
307 307 assert_eq!(char_index_to_byte(s, 1), 1);
308 308 assert_eq!(char_index_to_byte(s, 2), 4);
@@ -312,7 +312,7 @@ mod tests {
312 312
313 313 #[test]
314 314 fn floor_char_boundary_avoids_mid_glyph() {
315 let s = "a√b";
315 let s = "axb";
316 316 assert_eq!(floor_char_boundary(s, 2), 1);
317 317 assert_eq!(floor_char_boundary(s, 3), 1);
318 318 assert_eq!(floor_char_boundary(s, 4), 4);
@@ -321,7 +321,7 @@ mod tests {
321 321 #[test]
322 322 fn insert_and_prefix_survive_sqrt_cursor_misalign() {
323 323 let body = "[\u{221A}] done";
324 // Deliberately pass a mid-character byte index (inside √).
324 // Deliberately pass a mid-character byte index (inside x).
325 325 let (text, cur) = insert_at_cursor(body, 2, "!");
326 326 assert!(text.contains('!'));
327 327 assert!(text.is_char_boundary(cur));
@@ -302,7 +302,7 @@ mod tests {
302
302
303 #[test]
303 #[test]
304 fn char_index_to_byte_handles_multibyte() {
304 fn char_index_to_byte_handles_multibyte() {
305 let s = "a√b"; // √ is U+221A, three UTF-8 bytes
305 let s = "axb"; // x is U+221A, three UTF-8 bytes
306 assert_eq!(char_index_to_byte(s, 0), 0);
306 assert_eq!(char_index_to_byte(s, 0), 0);
307 assert_eq!(char_index_to_byte(s, 1), 1);
307 assert_eq!(char_index_to_byte(s, 1), 1);
308 assert_eq!(char_index_to_byte(s, 2), 4);
308 assert_eq!(char_index_to_byte(s, 2), 4);
@@ -312,7 +312,7 @@ mod tests {
312
312
313 #[test]
313 #[test]
314 fn floor_char_boundary_avoids_mid_glyph() {
314 fn floor_char_boundary_avoids_mid_glyph() {
315 let s = "a√b";
315 let s = "axb";
316 assert_eq!(floor_char_boundary(s, 2), 1);
316 assert_eq!(floor_char_boundary(s, 2), 1);
317 assert_eq!(floor_char_boundary(s, 3), 1);
317 assert_eq!(floor_char_boundary(s, 3), 1);
318 assert_eq!(floor_char_boundary(s, 4), 4);
318 assert_eq!(floor_char_boundary(s, 4), 4);
@@ -321,7 +321,7 @@ mod tests {
321 #[test]
321 #[test]
322 fn insert_and_prefix_survive_sqrt_cursor_misalign() {
322 fn insert_and_prefix_survive_sqrt_cursor_misalign() {
323 let body = "[\u{221A}] done";
323 let body = "[\u{221A}] done";
324 // Deliberately pass a mid-character byte index (inside √).
324 // Deliberately pass a mid-character byte index (inside x).
325 let (text, cur) = insert_at_cursor(body, 2, "!");
325 let (text, cur) = insert_at_cursor(body, 2, "!");
326 assert!(text.contains('!'));
326 assert!(text.contains('!'));
327 assert!(text.is_char_boundary(cur));
327 assert!(text.is_char_boundary(cur));
src/escpos.rs +7 −11
@@ -69,8 +69,8 @@ impl EscPosEncoder {
69 69 self.set_align(*align);
70 70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
71 71 for item in items {
72 let line = inlines_to_plain(item);
73 for part in text_wrap::wrap_bullet_item(&line, cols) {
72 let line = inlines_to_plain(&item.inlines);
73 for part in text_wrap::wrap_bullet_item_at_depth(&line, cols, item.depth) {
74 74 self.writeln(&part);
75 75 }
76 76 }
@@ -396,17 +396,13 @@ mod tests {
396 396 }
397 397
398 398 #[test]
399 fn encodes_bullet_list_with_hanging_indent() {
400 let doc = parse("- this is a long line").unwrap();
401 let meta = PosMetadata {
402 chars_per_line: Some(15),
403 ..Default::default()
404 };
405 let mut enc = EscPosEncoder::new(meta);
399 fn encodes_nested_bullet_list() {
400 let doc = parse("- outer\n - inner").unwrap();
401 let mut enc = EscPosEncoder::new(PosMetadata::default());
406 402 let bytes = enc.encode_document(&doc).unwrap();
407 403 let text = String::from_utf8_lossy(bytes);
408 assert!(text.contains("* this is a\n"));
409 assert!(text.contains(" long line\n"));
404 assert!(text.contains("* outer\n"));
405 assert!(text.contains(" - inner\n"));
410 406 }
411 407
412 408 #[test]
@@ -69,8 +69,8 @@ impl EscPosEncoder {
69 self.set_align(*align);
69 self.set_align(*align);
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
70 let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
71 for item in items {
71 for item in items {
72 let line = inlines_to_plain(item);
72 let line = inlines_to_plain(&item.inlines);
73 for part in text_wrap::wrap_bullet_item(&line, cols) {
73 for part in text_wrap::wrap_bullet_item_at_depth(&line, cols, item.depth) {
74 self.writeln(&part);
74 self.writeln(&part);
75 }
75 }
76 }
76 }
@@ -396,17 +396,13 @@ mod tests {
396 }
396 }
397
397
398 #[test]
398 #[test]
399 fn encodes_bullet_list_with_hanging_indent() {
399 fn encodes_nested_bullet_list() {
400 let doc = parse("- this is a long line").unwrap();
400 let doc = parse("- outer\n - inner").unwrap();
401 let meta = PosMetadata {
401 let mut enc = EscPosEncoder::new(PosMetadata::default());
402 chars_per_line: Some(15),
403 ..Default::default()
404 };
405 let mut enc = EscPosEncoder::new(meta);
406 let bytes = enc.encode_document(&doc).unwrap();
402 let bytes = enc.encode_document(&doc).unwrap();
407 let text = String::from_utf8_lossy(bytes);
403 let text = String::from_utf8_lossy(bytes);
408 assert!(text.contains("* this is a\n"));
404 assert!(text.contains("* outer\n"));
409 assert!(text.contains(" long line\n"));
405 assert!(text.contains(" - inner\n"));
410 }
406 }
411
407
412 #[test]
408 #[test]
src/params.rs +5 −2
@@ -174,7 +174,10 @@ pub fn substitute_document(
174 174 align: *align,
175 175 items: items
176 176 .iter()
177 .map(|item| substitute_inlines(item, values))
177 .map(|item| crate::dsl::ListItem {
178 depth: item.depth,
179 inlines: substitute_inlines(&item.inlines, values),
180 })
178 181 .collect(),
179 182 },
180 183 Block::Rule => Block::Rule,
@@ -240,7 +243,7 @@ fn collect_kinds_from_block(
240 243 }
241 244 Block::List { items, .. } => {
242 245 for item in items {
243 collect_kinds_from_inlines(item, kinds);
246 collect_kinds_from_inlines(&item.inlines, kinds);
244 247 }
245 248 }
246 249 Block::Image { path, .. } => collect_text_from_raw(path, kinds),
@@ -174,7 +174,10 @@ pub fn substitute_document(
174 align: *align,
174 align: *align,
175 items: items
175 items: items
176 .iter()
176 .iter()
177 .map(|item| substitute_inlines(item, values))
177 .map(|item| crate::dsl::ListItem {
178 depth: item.depth,
179 inlines: substitute_inlines(&item.inlines, values),
180 })
178 .collect(),
181 .collect(),
179 },
182 },
180 Block::Rule => Block::Rule,
183 Block::Rule => Block::Rule,
@@ -240,7 +243,7 @@ fn collect_kinds_from_block(
240 }
243 }
241 Block::List { items, .. } => {
244 Block::List { items, .. } => {
242 for item in items {
245 for item in items {
243 collect_kinds_from_inlines(item, kinds);
246 collect_kinds_from_inlines(&item.inlines, kinds);
244 }
247 }
245 }
248 }
246 Block::Image { path, .. } => collect_text_from_raw(path, kinds),
249 Block::Image { path, .. } => collect_text_from_raw(path, kinds),
src/preview.rs +2 −2
@@ -71,8 +71,8 @@ pub fn render_preview(
71 71 Block::List { align, items } => {
72 72 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
73 73 for item in items {
74 let text = substitute_inlines_for_preview(item, preview_params);
75 for line in text_wrap::wrap_bullet_item(&text, cols) {
74 let text = substitute_inlines_for_preview(&item.inlines, preview_params);
75 for line in text_wrap::wrap_bullet_item_at_depth(&text, cols, item.depth) {
76 76 lines.push(PreviewLine::Text {
77 77 content: line,
78 78 align: *align,
@@ -71,8 +71,8 @@ pub fn render_preview(
71 Block::List { align, items } => {
71 Block::List { align, items } => {
72 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
72 let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
73 for item in items {
73 for item in items {
74 let text = substitute_inlines_for_preview(item, preview_params);
74 let text = substitute_inlines_for_preview(&item.inlines, preview_params);
75 for line in text_wrap::wrap_bullet_item(&text, cols) {
75 for line in text_wrap::wrap_bullet_item_at_depth(&text, cols, item.depth) {
76 lines.push(PreviewLine::Text {
76 lines.push(PreviewLine::Text {
77 content: line,
77 content: line,
78 align: *align,
78 align: *align,
src/text_wrap.rs +27 −4
@@ -16,14 +16,31 @@ pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
16 16 }
17 17 }
18 18
19 /// ASCII bullet prefix — universally supported on ESC/POS printers.
19 /// ASCII top-level bullet — universally supported on ESC/POS printers.
20 20 pub const BULLET_FIRST_PREFIX: &str = "* ";
21 /// Indent for wrapped continuation lines (same width as [`BULLET_FIRST_PREFIX`]).
21 /// Indent for wrapped continuation lines at depth 0 (same width as [`BULLET_FIRST_PREFIX`]).
22 22 pub const BULLET_NEXT_PREFIX: &str = " ";
23 23
24 /// Word-wrap a bullet list item with hanging indentation.
24 /// Word-wrap a top-level bullet list item with hanging indentation (`* `).
25 25 pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec<String> {
26 wrap_hanging(text, max_cols, BULLET_FIRST_PREFIX, BULLET_NEXT_PREFIX)
26 wrap_bullet_item_at_depth(text, max_cols, 0)
27 }
28
29 /// Word-wrap a bullet at nesting `depth` (0 = `* `, nested = indented `- `).
30 pub fn wrap_bullet_item_at_depth(text: &str, max_cols: usize, depth: u8) -> Vec<String> {
31 let (first, next) = bullet_prefixes(depth);
32 wrap_hanging(text, max_cols, &first, &next)
33 }
34
35 fn bullet_prefixes(depth: u8) -> (String, String) {
36 let indent = " ".repeat(usize::from(depth));
37 if depth == 0 {
38 (BULLET_FIRST_PREFIX.to_string(), BULLET_NEXT_PREFIX.to_string())
39 } else {
40 let first = format!("{indent}- ");
41 let next = " ".repeat(first.chars().count());
42 (first, next)
43 }
27 44 }
28 45
29 46 /// Word-wrap `text` with different budgets for the first and subsequent lines.
@@ -226,4 +243,10 @@ mod tests {
226 243 let lines = wrap_bullet_item("this is a long line", 15);
227 244 assert_eq!(lines, vec!["* this is a", " long line"]);
228 245 }
246
247 #[test]
248 fn nested_bullet_uses_dash_and_indent() {
249 let lines = wrap_bullet_item_at_depth("this is a long line", 18, 1);
250 assert_eq!(lines, vec![" - this is a", " long line"]);
251 }
229 252 }
@@ -16,14 +16,31 @@ pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
16 }
16 }
17}
17}
18
18
19/// ASCII bullet prefix — universally supported on ESC/POS printers.
19/// ASCII top-level bullet — universally supported on ESC/POS printers.
20pub const BULLET_FIRST_PREFIX: &str = "* ";
20pub const BULLET_FIRST_PREFIX: &str = "* ";
21/// Indent for wrapped continuation lines (same width as [`BULLET_FIRST_PREFIX`]).
21/// Indent for wrapped continuation lines at depth 0 (same width as [`BULLET_FIRST_PREFIX`]).
22pub const BULLET_NEXT_PREFIX: &str = " ";
22pub const BULLET_NEXT_PREFIX: &str = " ";
23
23
24/// Word-wrap a bullet list item with hanging indentation.
24/// Word-wrap a top-level bullet list item with hanging indentation (`* `).
25pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec<String> {
25pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec<String> {
26 wrap_hanging(text, max_cols, BULLET_FIRST_PREFIX, BULLET_NEXT_PREFIX)
26 wrap_bullet_item_at_depth(text, max_cols, 0)
27}
28
29/// Word-wrap a bullet at nesting `depth` (0 = `* `, nested = indented `- `).
30pub fn wrap_bullet_item_at_depth(text: &str, max_cols: usize, depth: u8) -> Vec<String> {
31 let (first, next) = bullet_prefixes(depth);
32 wrap_hanging(text, max_cols, &first, &next)
33}
34
35fn bullet_prefixes(depth: u8) -> (String, String) {
36 let indent = " ".repeat(usize::from(depth));
37 if depth == 0 {
38 (BULLET_FIRST_PREFIX.to_string(), BULLET_NEXT_PREFIX.to_string())
39 } else {
40 let first = format!("{indent}- ");
41 let next = " ".repeat(first.chars().count());
42 (first, next)
43 }
27}
44}
28
45
29/// Word-wrap `text` with different budgets for the first and subsequent lines.
46/// Word-wrap `text` with different budgets for the first and subsequent lines.
@@ -226,4 +243,10 @@ mod tests {
226 let lines = wrap_bullet_item("this is a long line", 15);
243 let lines = wrap_bullet_item("this is a long line", 15);
227 assert_eq!(lines, vec!["* this is a", " long line"]);
244 assert_eq!(lines, vec!["* this is a", " long line"]);
228 }
245 }
246
247 #[test]
248 fn nested_bullet_uses_dash_and_indent() {
249 let lines = wrap_bullet_item_at_depth("this is a long line", 18, 1);
250 assert_eq!(lines, vec![" - this is a", " long line"]);
251 }
229}
252}