# Document DSL specification

A lightweight, markdown-inspired syntax for POS receipt templates. The DSL compiles to an AST and then to ESC/POS bytes or a screen preview.

> **Implementation:** Parser in `src/dsl/parser.rs`. All constructs below are implemented unless listed under [Future extensions](#future-extensions-not-implemented).

**Design goals:** easy to author, line-oriented, explicit about POS-specific features (barcodes, cut, feed), parameter-friendly.

---

## Document structure

A document is a sequence of **blocks**. Blank lines become paper feeds (`@feed 1`). Blocks are not nested except for `${parameters}` inside text.

---

## Text blocks

### Paragraphs

Plain text (and `${parameters}`). One or more consecutive non-empty lines form a paragraph. There is **no** inline bold/italic/code markup. Consecutive spaces are preserved (not collapsed), including leading indentation, so authors can pad columns manually. Trailing spaces on a line are trimmed.

```markdown
Thank you for your purchase!
Visit us again soon.
Item               12.00
                          rightish note
```

### Headings

```markdown
# Store Name
## Receipt
```

- `#` → large / double-height text (ESC/POS emphasis)
- `##` → bold emphasis
- Maximum two levels in v1

### Alignment

Prefix a paragraph with alignment markers:

```markdown
:center:
Your Store Name

:right:
Total: ${Amount}
```

| Marker | Effect |
|--------|--------|
| `:left:` | Left (default) |
| `:center:` | Centered |
| `:right:` | Right-aligned |

**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.

```markdown
:left: ${Item}:right: ${Price}
```

Standalone `:center:` / `:right:` paragraphs (one alignment per line) still use printer justification.

### Bullet lists

```markdown
- Groceries
  - Milk
  - Eggs
- Wash car
```

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.

| Depth | Printed bullet |
|-------|----------------|
| 0 (top) | `* ` |
| ≥ 1 | indented `- ` |

Wrapped lines use a hanging indent matching the bullet prefix width:

```text
* this is a
  long line
  - nested item that
    wraps too
```

### Parameters

| Syntax | Effect |
|--------|--------|
| `${Name}` | Text parameter placeholder (see Parameters) |
| `$[Name]` | Bool checkbox parameter → `[ ]` / `[x]` |

`${Name}` and `$[Name]` must not share the same name.

### Checkboxes

| Syntax | Printed result |
|--------|----------------|
| `[]` or `[ ]` | `[ ]` |
| `[x]` / `[X]` | `[x]` |
| `$[Name]` | `[ ]` or `[x]` from a bool parameter |

ASCII brackets + `x` stay inline in the native CP437 font. Do not use Unicode ☐ / √ — many ESC/POS printers map those to CJK glyphs. `${Name}` and `$[Name]` cannot share a name.

Parameters work inside any text, and inside barcode/QR/image directives (below).

**Example:**

```markdown
Receipt #${DocumentNumber}
Date: ${Date}

$[Paid] Paid
[] Pending

Item: ${ItemName}     ${LineTotal}
```

### Horizontal rule

```markdown
---
```

Renders a dashed or solid separator line across the print width.

---

## Directives (block-level)

Directives start with `@` at the beginning of a line.

### Feed (blank lines)

```markdown
@feed 3
```

Advances paper by *n* lines.

### Cut

```markdown
@cut
```

Partial cut after content (if printer supports). Often placed at document end.

### Image

```markdown
@image path/to/logo.png
@image ${LogoPath} width=50%
@image assets/qr-promo.png width=384
```

| Attribute | Description |
|-----------|-------------|
| `path` (positional) | File path relative to `.pos` file or absolute; may be `${Param}` |
| `width` | `NN%` of printable width, or absolute dots (e.g. `384`) |
| `align` | `left` (default), `center`, `right` |

Images are converted to monochrome raster data and scaled to width (never wider than `printable_dots`).

### Date / time

```markdown
@date
@date DD-MM-YYYY
@time
@time 12h
@time 24h
```

| Directive | Behaviour |
|-----------|-----------|
| `@date` | System regional short date (`%x`) |
| `@date PATTERN` | Custom pattern (`YYYY`, `MM`, `DD`, …) |
| `@time` / `@time 24h` | 24-hour `HH:MM` |
| `@time 12h` | 12-hour with AM/PM |

### Barcode

```markdown
@barcode CODE128 ${Sku}
@barcode EAN13 ${EanCode} height=80
@barcode RASTER CODE128 ${Sku}
@barcode RASTER CODE93 ABC-1234
```

| Field | Values |
|-------|--------|
| Mode | Optional `RASTER` prefix; otherwise native ESC/POS |
| Symbology | Native: `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A`, `UPC-E`, `ITF`, `CODABAR`. Raster-only: `CODE93`, `CODE11` |
| Data | Literal or `${Param}`; multiple words joined until the first `key=value` attribute |
| `height` | Module / PNG height in dots (default: 64) |
| `align` | `left`, `center`, `right` |
| `show_text` | Native only: print HRI text under barcode (default: off; set `show_text=true` to enable) |

Raster barcodes stretch horizontally to full printable width.

### QR code

```markdown
@qr https://example.com/receipt/${DocumentNumber}
@qr ${PaymentUrl} size=6 ecc=H
@qr RASTER ${PaymentUrl} version=5 scale=4 ecc=M
```

| Attribute | Native | Raster |
|-----------|--------|--------|
| Data | URL/text; may include `${Param}`; multiple words joined until the first `key=value` attribute | Same |
| `size` | Module size 1–16 (default 4) | — |
| `scale` | — | Pixels per module (default 4) |
| `version` | — | QR version 1–40 (optional) |
| `ecc` | `L`, `M`, `Q`, `H` (default `M`) | Same |
| `align` | `left`, `center`, `right` | Same |

---

## Parameters

### Syntax

```
${ParameterName}   # text
$[ParameterName]   # boolean checkbox → [ ] / [x]
```

- **Names:** `[A-Za-z_][A-Za-z0-9_]*` (ASCII letters, digits, underscore)
- **Case-sensitive:** `${DocNo}` and `${docno}` are different
- **No mixed types:** the same name must not appear as both `${…}` and `$[…]`
- **Uniqueness at input:** all occurrences of the same name share one value entered at print time

### Where parameters are allowed

| Location | Example |
|----------|---------|
| Text | `Order ${OrderId}` / `$[Paid] Paid` |
| Barcode data | `@barcode CODE128 ${OrderId}` (`${…}` only) |
| QR data | `@qr ${VerifyUrl}` (`${…}` only) |
| Image path | `@image ${LogoPath}` (`${…}` only) |

### Print-time behavior

1. Before print, scan AST for all `${…}` and `$[…]` tokens.
2. Deduplicate by name (kinds must not conflict — enforced at parse).
3. Show dialog: text field per `${…}`, checkbox per `$[…]` (or require CLI `--set`).
4. Bool values: `true`/`false` (also `1`/`0`, `yes`/`no`).
4. Pre-fill from last print session (in-memory).
5. Substitute into AST, then encode/print.

Missing parameter at print time: block print and highlight unresolved names.

---

## Comments

```markdown
<!-- this is not printed -->
```

HTML-style comments are stripped before parse.

---

## Blank lines

A blank line (or whitespace-only line) inserts `Feed(1)` — same paper advance as `@feed 1`. On print this becomes `ESC d 1` (reliable after raster graphics).

---

## Error reporting

Parse errors include 1-based line and column. Typical causes:

- Invalid barcode symbology
- Invalid `${}` name
- Missing required directive argument
- Unknown `@time` format

---

## ESC/POS mapping (summary)

| DSL | ESC/POS |
|-----|---------|
| `# heading` | Double width/height ON → text → OFF |
| `## heading` | Bold ON → text → OFF |
| `- item` / `  - nested` | Top: ASCII `* `; nested: indented `- ` + hanging wrap |
| `[]` / `[ ]` / `[x]` / `$[Name]` | ASCII `[ ]` / `[x]` (CP437-safe, inline) |
| `:center:` | Justification center |
| `@feed n` / blank line | ESC d n |
| `@cut` | GS V partial cut |
| `@barcode` | GS k or GS v 0 raster |
| `@qr` | GS ( k or GS v 0 raster |
| `@image` | GS v 0 raster bit image |
| `@date` / `@time` | Plain text lines |

Full command details: [PRINTING.md](PRINTING.md).

---

## Future extensions (not implemented)

- `@table` for columnar line items
- Numbered lists
- Bluetooth printer transport (after OS pairing; connected devices only)
- Syntax highlighting in the editor

---

## Example document

```markdown
# ${StoreName}
:center:

123 Main Street

---
@date
@time
Receipt: ${DocumentNumber}

- Item one
- Item two

:right:
TOTAL: ${GrandTotal}

@barcode CODE128 ${DocumentNumber}
@feed 2
@qr RASTER https://shop.example.com/r/${DocumentNumber} scale=4

Thank you!
@feed 4
@cut
```
