# bobina — full documentation for agents

> Generated by tools/gen_llms_full.py from the files below; the index is llms.txt.


<!-- file: README.md -->

# bobina

Print Markdown on thermal roll printers — receipts, lists, labels, QR codes, payment codes (Pix, UPI, SEPA…), photos —
with calibrated defaults, a preview you can trust, and **nudges instead of blocks**.

```bash
bobina print "# MARKET\n- [ ] milk\n- [ ] bread"
bobina print list.bob.md
bobina template new receipt sale.bob.md && bobina print sale.bob.md
```

Every command that prints shows a **confirmation screen** first (the dry run): a terminal preview
on the real 32-column grid, paper length, counters it will use, and nudges with the evidence
behind them. `p` prints; `--yes` skips it. **Without a terminal (scripts, agents, ssh) add `--yes`**:
otherwise nobody can answer and the print stops with `E107` (exit 7). `-n` shows the screen and prints nothing.
Agents: start at [llms.txt](llms.txt) (or [llms-full.txt](llms-full.txt), everything in one file); a ready skill
is in [skills/bobina/SKILL.md](skills/bobina/SKILL.md).

```
┌─ preview · mtp-ii-58 · 58 mm ──┐
│                                │
│M A R K E T                     │
│                                │
│☐  milk                         │
│☐  bread                        │
└────────────────────────────────┘
 ~3.1 cm of paper · 1 native rows, 2 raster · 2.9 KB
 [p] print   [s] save as…   [q] quit
```

## Why

Cheap 58/80 mm printers are good enough for a lot — if something takes care of their limits.
bobina was calibrated on a minimum-quality printer (Goldensky MTP-II): every default comes from
a printed and photographed test, so what works there works on better printers. You can ask for
anything; bobina only warns, and tells you why (`warning[Q101] … (evidence: N6)`).

- **One engine** for check, preview and print: the PNG preview is the exact dot pattern sent.
- **Native when the printer does it well, raster when it does not** — per line, decided by the
  printer profile (glyphs the font lacks, italic, inverted bands, drawn checkboxes).
- **Readable documents**: plain Markdown plus Pandoc-style attributes. See [docs/FORMAT.md](docs/FORMAT.md).
- **Safe data**: values from CSV or `--set` are printed literally and can never inject Markdown,
  template code or printer commands; templates run in a sandbox.

## Install

```bash
curl -LsSf https://raw.githubusercontent.com/rafaelbressan/bobina/main/get.sh | sh   # installs uv if missing
# or: uv tool install bobina · pipx install bobina · a .deb or Homebrew: docs/INSTALL.md
bobina init                   # printer, profile, locale, roll, test strip
bobina init --yes             # agents, scripts: no questions, no print
```

Bluetooth printing needs Linux and the system Python (`get.sh` picks it). The .deb, pipx, the boot service and a
checkout: [docs/INSTALL.md](docs/INSTALL.md).
Printer on another machine? `bobina init --command "ssh tower bobina send --yes -"`. No printer at hand?
`bobina init --yes --printer ./out.bin`: every job's bytes are appended to `out.bin` (a file printer).
Dates and money: the first `check`, `preview` or `print` takes the locale from the time zone and saves it
(`M203`); `bobina config set locale en-US` changes it.

## The format in one screen

````markdown
---
locale: pt-BR
counters:
  ticket: { start: 1, format: "A-{:03}" }
fonts:
  body: native                 # the printer's own font (fast)
  hand: Z003                   # any alias you like
---
# TICKET {{ seq.ticket }} {.invert .center}

{{ now | date("full") }}        <!-- quinta-feira, 5 de novembro de 2026 -->

- [ ] open task
- [x] done task (struck)

| Item | Qty | Price |
|---|--:|--:|
| Bread | 6 | {{ 4.8 | currency("BRL") }} |

```qr
https://example.com
```

```pay {scheme=pix to="you@example.com" name="Shop" city="Rio" amount=10.00}
```

Signed, [Ana]{font=hand size=32px}

--- {.cut}
````

`bobina help format` has the rest: sizes (`small`…`huge`, physical mm), dividers, barcodes,
Data Matrix, PDF417, images (dither and gamma), rotation, upside-down text, templates and data.

## One label per row

A document with `{{ blanks }}` plus a table (CSV, TSV, JSON, Excel) prints one label per row; the
columns fill the blanks. Step by step: [docs/guides/batch-printing.md](docs/guides/batch-printing.md);
in the terminal: `bobina help data`.

```bash
bobina check jar-label.bob.md --data pantry.csv                 # paper length, problems, the columns: no print
bobina print jar-label.bob.md --data pantry.csv --where shelf=A --copies-from jars --yes  # jars=0: no label
bobina print tag.bob.md --data stock.xlsx --sheet Estoque --yes  # a sheet other than the first
bobina print shelf-tag.bob.md --data a=prices.xlsx --join b=catalog.json --on name --yes  # {{ a.price }} {{ b.id }}
bobina print note.bob.md --set produto=Feijão --set validade=2027-01-31 --yes   # one value, no table
bobina preview jar-label.bob.md --data pantry.csv -o 'labels/{product}.png'    # one PNG per label
```

A `{{ name }}` that is not a column prints empty and is reported (`M130`, with the columns the data has).

## Commands

| Command | Does |
|---|---|
| `print [FILE \| "TEXT" \| -]` | render → confirm → print. `--data rows.csv` (above), `--set KEY=VALUE`, `--copies N` (identical), `--repeat N` (new counter values each), `-o job.bin` (save, do not print); stops after each label (`--no-step`) |
| `print --last` / `--again` | reprint the last job: identical bytes / re-rendered (new `now` and counters); with `-o FILE` save instead |
| `check FILE` | problems, paper length, native/raster rows, nothing printed (`--data`, `--json` → `{"stats", "problems"}`, `--strict`) |
| `preview FILE \| "TEXT"` | exact PNG (`-o out.png`); `--data rows.csv -o 'dir/{column}.png'` one per label; `--realistic` simulates ink spread |
| `view FILE` | preview in the terminal |
| `edit [FILE] [--template NAME]` | write in your editor, confirm, print |
| `template list \| show \| new` | receipt, label, todo, card, note, and a shop gallery: [guides/templates.md](docs/guides/templates.md) |
| `seq list \| set \| reset` | persistent counters (`{{ seq.NAME }}`); `seq set ticket 100`: the next print uses 100 |
| `init` | first run; again to change one part |
| `printer scan \| add \| list \| use \| remove \| show \| set` | printers live in `~/.config/bobina/config.toml` |
| `config list \| get \| set \| unset \| edit` | the other settings (`config set step off`) |
| `status`, `mode [esc\|tspl\|cpcl]` | printer state; command language |
| `calibrate compare PHOTO FILE` | how close the preview is to the paper |
| `calibrate tear` / `calibrate feed` | where the tear bar is; whether feeds after images need the safe mode |
| `paper [new 15m \| used 3m]` | paper left on the roll (the printer only reports "out") |
| `profile list \| show`, `fonts list`, `send FILE.bin` | profiles, tested fonts, raw bytes |
| `mcp` | a server for AI agents (MCP; `uv tool install 'bobina[mcp]'`, then `claude mcp add bobina -- bobina mcp`): [docs/mcp.md](docs/mcp.md) |

`bob` is the same binary. Short aliases exist for typing (`bobina help aliases`); docs always use
full names. Exit codes: 0 ok · 1 usage · 2 document · 3 strict nudges · 4 unreachable · 5 printer
not ready · 6 language · 7 confirmation needed/declined · 8 security · 9 a payment or contact code left out (Q111,
Q112) · 10 newer release.

## Repository

| Path | What |
|---|---|
| `src/bobina/` | the package (engine, layout, ESC/POS, preview, CLI) and built-in profiles, templates, fonts |
| `docs/` | [`FORMAT.md`](docs/FORMAT.md) (the `.bob.md` spec), [`CLI.md`](docs/CLI.md) (commands, options, problems, exit codes), [`SECURITY.md`](docs/SECURITY.md) (threat model), [`guides/batch-printing.md`](docs/guides/batch-printing.md), [`guides/tables.md`](docs/guides/tables.md), [`TESTED.md`](docs/TESTED.md) (what was and was not tested on paper) |
| `examples/` | documents and data used by the guides (`examples/batch/`) |
| `spec/conformance/` | test tickets with expected bitmaps — a `bob/1` implementation renders them identically |
| `tests/` | unit, security and golden tests (no printer needed) |
| `docs/printers/` | measured capabilities of each profiled printer (`mtp-ii-58.md`) |
| `contrib/` | Bluetooth boot service for Linux (`install.sh` sets it up) |
| `tools/` | maintenance scripts: public export and personal-data scan |

## Status

Pre-release (v0.x). MIT licensed (bundled fonts keep their own licenses: `src/bobina/fonts/LICENSES.md`). Baseline profile: `mtp-ii-58` (measured); 32 more imported from escpos-printer-db, not measured on paper (`bobina profile list`; calibrate before trusting them). Realistic preview is an estimate until
the profile is calibrated from photos (`preview.calibrated = false`).

## Hardware notes (MTP-II)

| Symptom | Likely cause |
|---|---|
| `printer unreachable` | printer off or asleep: press POWER until the yellow LED is steady |
| Blank output | roll upside down (the side that darkens with a fingernail faces the head) |
| Turns off when printing | battery: charge it; first use: remove the film on the battery contacts |
| Prints garbage | another app sent a different command language (TSPL/CPCL) as text; the MTP-II itself only speaks ESC/POS |
| Self-test | printer off → hold FEED, press POWER, release at the beep |
| The last line stops at the tear bar, or a `--marks tear` line is off | `bobina calibrate tear` (a ruler: tear it and read the mm), then `bobina calibrate feed` (does the printer obey a paper feed right after an image?) |


<!-- file: docs/agents.md -->

# bobina for agents

bobina is made to be run by programs and AI agents as well as by people: every print shows a confirmation screen,
every problem has a code, and every command that returns data has `--json`.

## The four rules

1. **No terminal, add `--yes`.** `bobina print FILE --yes`. Without it nobody can answer the confirmation screen
   and the print stops with `E107` (exit 7). `print -n` shows the screen and prints nothing.
2. **Look before paper.** `bobina check FILE` (paper length and problems), `bobina view FILE` (the preview in the
   terminal), `bobina preview FILE -o out.png` (the exact image). Print only what the user asked for.
3. **Read the codes.** Warnings never block: each one has a code, a suggestion and the evidence. `bobina help CODE`
   says what to do; [problems/README.md](docs/problems/README.md) lists every code.
4. **Try without hardware.** `bobina printer add test --path out.bin` is a file printer: each job's bytes are
   appended to `out.bin`.

## Machine output

- `bobina check FILE --json` (and `print`, `preview`) gives `{"stats", "problems"}`; `--problems json|jsonl`
  writes problems to stderr. Schemas: [schemas/README.md](docs/schemas/README.md).
- `bobina help --json` describes every command, option, topic and problem code.
- Tables: `bobina help table` (`--json`): where each `{…}` goes (`style=receipt` under the table, a column's
  settings in its title cell) and the columns per line in each font.
- Exit codes: 0 ok, 1 usage, 2 document, 3 strict, 4 unreachable, 5 printer not ready, 6 language,
  7 confirmation, 8 security, 9 a payment or contact code left out (`Q111`, `Q112`), 10 a newer release (`bobina update --check`). [CLI.md](docs/CLI.md#exit-codes) has the table.
- Servers, bots and cron: `BOBINA_NONINTERACTIVE=1`, one process per job
  ([CLI.md](docs/CLI.md#long-jobs-and-limits)).

## Files for agents

- [llms.txt](llms.txt): the index, with the facts an agent needs first; [llms-full.txt](llms-full.txt): the
  docs in one file.
- [skills/bobina/SKILL.md](skills/bobina/SKILL.md): a ready skill (when to print, what never to do).

## The MCP server (`bobina mcp`)

`bobina mcp` gives agents bobina as tools (check, preview, print with `confirm: true` after the user agreed,
paper): setup and the tool list in [mcp.md](docs/mcp.md).


<!-- file: docs/CLI.md -->

# bobina — CLI conventions (draft v0.4)

Language: **English everywhere** (messages, help, docs, spec).

## Principles

1. **Agnostic core, opinionated defaults.** Anything the user asks for explicitly is executed as asked. Calibrated defaults (from the printer profile) only fill in what was not specified.
2. **Nudges, not blocks.** Warnings go to stderr with a suggestion and the evidence behind it; they never stop a print. `--quiet` silences them, `--strict` turns them into errors (CI/automation).
3. **What you check is what you print.** `check`, `preview` and `print` share one engine. Every printing command accepts `--dry-run`.
4. **Nothing prints without confirmation.** Every command that prints shows the confirmation screen first and waits for `p`. `--yes` (`-y`) skips it, explicitly.
5. **Readable by humans and agents.** Full command names are canonical. Human-readable output by default, `--json` on every command that returns data, stable exit codes.
6. **Discoverable.** `bobina help`, `bobina <command> --help`, `bobina help format`, `bobina help table`, `bobina help data`, `bobina help pay`, `bobina <thing> list`,
   `bobina help E302` (what a problem code means and what to do; docs/problems/), `bobina help --json` (the CLI for
   programs). JSON outputs have schemas in docs/schemas/.

<!-- 'Names' left out here: see docs/CLI.md -->

## Commands

| Command | Does | Alias |
|---|---|---|
| `print [FILE \| - \| "TEXT"]` | render, confirm and print a `.bob.md` document, inline text, or stdin; `--last` reopens the last confirmation | `p` |
| `check FILE` | lint: line breaks, truncated words, unsupported glyphs, paper length, black coverage, nudges | `c` |
| `preview FILE -o OUT.png` | exact bitmap, or `--realistic` (calibrated dot gain) | `pv` |
| `view FILE` | preview in the terminal (block/braille characters) | `v` |
| `edit [FILE] [--template NAME]` | write in your editor → confirmation screen → print | `e` |
| `status` | paper / cover / error / language mode; `--list` explains every state; file and command printers: none (exit 0) | `s` |
| `mode [esc \| tspl \| cpcl]` | show or switch the printer command language | `m` |
| `send FILE.bin` | send raw bytes untouched (escape hatch) | — |
| `fonts list \| test \| mark \| scripts \| get` | recommended fonts, the font test registry; fonts for other scripts (`get thai`, `get hi`, `get menu.bob.md`: download now, offline later) | — |
| `seq list \| set \| reset` | persistent counters used by `{{ seq.NAME }}` | — |
| `init` | first run: printer, profile, locale, roll, a test strip with the calibration ([below](#first-run-init)) | — |
| `printer scan \| add \| list \| use \| remove \| show \| set \| unset` | find and store printers; `set NAME KEY VALUE` | — |
| `config list \| get \| set \| unset \| edit` | every setting and its value (`--all`: advanced too); `edit` checks the file; a bad value is a note, never a stop | — |
| `profile list \| show \| use` | printer profiles | — |
| `template list \| show \| new` | ready-made documents (receipt, label, todo, card, shop tags…) | — |
| `calibrate compare\|tear\|feed` | photo vs preview; tear bar distance (ruler); feeds after images (3 lines) | — |
| `help [COMMAND \| TOPIC \| CODE]` | help; topics: format, table, data, pay, contact, icons, nudges, aliases | — |
| `mcp` | a server for AI agents (Model Context Protocol): [mcp.md](docs/mcp.md) | — |
| `chat`, `ai` | an AI whose answers print: [chat.md](docs/chat.md) | — |

Everyday use: `bobina print "buy bread"`, `bobina print list.bob.md`, `echo "hi" | bobina print --yes`.

## First run (`init`)

`bobina init` finds the printer (Bluetooth, USB, a file, ssh), confirms its profile and the locale, asks the
roll (as `paper new`), then offers one test strip with the calibration and asks what the paper shows. Run again to
change one part. `--yes` (or `BOBINA_NONINTERACTIVE`) asks and prints nothing: the first printer found
(`--printer` chooses), its profile, the locale; the roll stays unset (`P104`). `--json`: `bobina.init/1`.
`--printer` takes a name from `bobina printer list`, a Bluetooth address, a device (`/dev/usb/lp0`), a file for a
test printer (`--printer ./test.bin`) or the name a printer nearby gives itself.

## Confirmation screen

Shown by every printing command (it is the dry run):

```
┌─ preview · mtp-ii-58 · 58 mm ────┐
│ MARKET               05/11/2026  │
│ ☐ milk                           │
│ ☐ bread                          │
└──────────────────────────────────┘
 ~7.2 cm of paper · 4 native blocks, 1 raster
 seq.ticket: will use A-042 (reserved for this print; given back if it is not printed)
 warning[F204] line 3: font "Z003" at 16px is illegible → use ≥ 28px  (evidence: F1-16)

 [p] print   [e] edit again   [s] save as…   [q] quit
```

- Enter alone never prints.
- `print --last` reopens the confirmation of the last document (identical content, same reserved values); `--again` re-renders it (new `now`, new `seq`).
  With `--yes` either one prints at once and says where (`reprinted on loja: ~1.5 cm (identical bytes)`); with
  `-o FILE` it saves the bytes to that file instead and prints nothing (`--again -o` spends no seq numbers).
- No terminal attached (pipes, cron, agents) and no `--yes` → shows the confirmation on stderr, prints nothing, exit code 7.
- `--copies N`: N identical copies. `--repeat N`: N renders, each with new counter values. The screen shows the total ("10 tickets: A-042 to A-051").

<!-- 'Drafts and editor (`edit`)' left out here: see docs/CLI.md -->

## Inline text is an implicit document

`bobina print "TEXT"` (and stdin) is treated exactly like a `.bob.md` file with that content: same parser, same check, same nudges.

- `--plain` disables Markdown (prints the text literally, still word-wrapped).
- `\n` in the argument is a newline (typing multi-line text in a shell is awkward): `bobina print "# MARKET\n- [ ] milk"`.
- Backslash before a Markdown character escapes it, as in CommonMark (`\*`, `\#`).
- `check` warns when text looks literal but would be interpreted (e.g. a lone `*`, `#` without a space, a log line starting with `---`).

## Batches (`--data`)

One design with `{{ blanks }}` + a table whose columns have the same names = one label per row. Step by step,
with pictures: [`docs/guides/batch-printing.md`](docs/guides/batch-printing.md).

## Saving instead of printing (`-o`)

`-o FILE` (`--output FILE`) saves instead of printing. An existing FILE is replaced only with `--force`, and a file
the job reads (document, image, data) is never replaced. Without `-o`, `preview` writes `DOCUMENT.preview.png`. In `print` it saves the bytes the printer would get (any
name; `.bin` by convention), to send later with `bobina send`. In `preview` it saves the picture of the strip:
`.png`, `.jpg`, `.pdf`, `.webp`, `.bmp`, `.gif` or `.tif`, chosen by the extension.

**One file per label**: put a placeholder in the name (like ffmpeg's `frame%04d.png`):

| Placeholder | Becomes | Needs data? |
|---|---|---|
| `{n}`, `{n:03}` | label number in the whole job: 1, 2 … / 001, 002 … | no |
| `{i}`, `{i:02}` | number inside its document (restarts for each file) | no |
| `{file}` | document name without the extension (`jar`, `cover`) | no |
| `{part}` | the `--then` part | no |
| `{column}`, `{b.column}` | a value of that row (`{item}` → `rice`) | yes |
| `{column\|slug}` … | the value in another case: `lower`, `upper`, `slug`, `snake`, `kebab`, `camel`, `pascal`, `deaccent`, `titlecase` | yes |

```
bobina preview a.bob.md b.bob.md -o 'out-{n}.png'                     # out-1.png out-2.png
bobina preview cover.bob.md --then jar.bob.md --data kitchen.csv -o 'out/{file}-{i:02}.jpg'
bobina preview jar.bob.md --data kitchen.csv -o 'tag-{item}.png'      # tag-rice.png …
bobina print jar.bob.md --data kitchen.csv -o 'jar-{n}.bin'           # each file is a whole printable job
bobina preview jar.bob.md --data kitchen.csv --pages -o batch.pdf     # one PDF, one page per label
```

Values from data are cleaned for file names (`../../x` cannot leave the folder; `/ \ : * ? " < > |` become `_`).
Two labels that would get the same name are an error (add `{n}` or `{i}`); existing files are replaced only with
`--force`; a missing `{column}` lists the available names. Folders in the name are created.

## Label by label (`--step`)

A print of several labels stops after each one, so you can tear it off:

```
 ✓ 3/10 printed: tear it off
 [Enter] next (4/10 · Honey)   [a] all 7 left   [r] again   [s] skip   [q] stop
```

`r` reprints the last, `q` says how to print the rest (`--rows 4-10`); unprinted labels give their numbers
back. Only at a terminal with a real printer: not with `-o`, a file printer, agents or `--yes`
(unless `--step` is written). `--compact` prints at once (`P105`). `--no-step`: this print at once; `--step 3`:
stop every 3; `bobina config set step off`: always at once.

## One strip (`--compact`, `--then`, several files)

Every label normally ends with the feed to the tear bar, so you can tear each one off. To print several things as
one job — one preview, one confirmation, one paper count — give several files, or split the command into
**parts** with `--then`:

```
bobina print a.bob.md b.bob.md @shelf                        # three documents, one job
bobina print jar.bob.md --data kitchen.csv --compact \
  --then jar.bob.md --data laundry.xlsx --sheet Laundry \
  --then receipt.bob.md --no-compact --compact-all
```

**Rules** (like ffmpeg: options belong to the part they are written in; the specific beats the general):

1. A **part** is everything between two `--then`: one or more files and their options (`--data`, `--where`,
   `--copies-from`, `--set`, `--ask`, `--page` …). The options apply to every file of that part.
2. `--compact` / `--no-compact` set a part; `--compact-all` is the default for every part. Both flags in one part
   is an error.
3. **Joins**: inside a compact part, labels are glued at a ✂ cut. Between two parts there is a ✂ cut only if
   **both** are compact; otherwise the paper feeds to the tear bar. The end of the job always feeds.
4. Job options (the table below) may be written in any part. Counters (`{{ seq.x }}`) continue across parts and
   files; copies of a row repeat its number.

The terminal preview always draws where one label ends: `┄┄ ⟶ ┄┄` where the
paper goes to the tear bar, `✂ ┄┄┄` at a cut.

**On paper, no mark by default** (a cut is just space). To see on the strip where one order ends and the next
begins, `--marks cut` prints a fine dashed line (1 dot, 4 on / 4 off) at every cut, `--marks tear` prints it so
that the final feed leaves it on the tear bar (it uses the `tear_mm` measured by `bobina calibrate tear`; 5 mm
without one), `--marks both` does both; `bobina config set marks both` makes it the default. The marks change
no length, and the confirmation screen says which ones go on paper.

| Command | Strip (⟶ tear feed, ✂ cut line) |
|---|---|
| `a b --then c d --compact` | A ⟶ B ⟶ C ✂ D ⟶ |
| `a b --then c --then d --compact` | A ⟶ B ⟶ C ⟶ D ⟶ (D's neighbour is not compact) |
| `a b --then c --no-compact --then d --compact-all` | A ✂ B ⟶ C ⟶ D ⟶ |
| `jar --data kitchen.csv --compact --then jar --data laundry.xlsx` | jar 1 ✂ jar 2 ✂ jar 3 ⟶ jar 4 ⟶ jar 5 ⟶ |

**Which options belong where** (tested in `tests/test_strip_rules.py`):

| Kind | Options | Rule |
|---|---|---|
| Part | `--set`, `--data`, `--sheet`, `--rows`, `--where`, `--copies-from`, `--repeat`, `--copies`, `--ask`, `--page`, `--plain`, `--allow-net`, `--allow`, `--compact`/`--no-compact` | apply to the files of the part they are written in, never to the next part |
| Job flag | `--compact-all`, `--sandbox`, `--yes`, `--dry-run`, `--strict`, `-q`, `--json`, `--no-color`, `--step`/`--no-step` | may be written in any part, apply to the whole job |
| Job default | `--set-all KEY=VALUE`, `--allow-all CODES` | every part gets them; a part's own `--set`/`--allow` wins |
| Job value | `--printer`, `--profile`, `-o`, `--editor`, `--marks` | one value per job; two different values are an error |
| Not with documents | `--last`, `--again` | reprint the last job; an error with targets or `--then` |

**Errors and warnings in a long job.** Every part is built and checked before the printer is touched, and every
problem is reported at once, in one format (the same in every command):

```
3 errors, 1 warning — nothing printed
✗ error   part 2 (nope.bob.md): file not found: nope.bob.md
✗ error   part 4 (jar.bob.md): --where: no column 'color' (columns: item, n)
✗ error   [M310] part 5 (bad.bob.md): templates cannot read files (include/import are disabled)
! warning [I101] part 3 (photo.bob.md), line 3: image 'missing.png': No such file or directory
            → paths are relative to the document
```

One error anywhere and nothing prints; the exit code is the most serious one (security 8 > document 2 > usage 1).
Warnings never stop the job by themselves: on the confirmation screen you decide (`p` prints without the missing
image, `q` gives up); with `--yes` they are shown and the job prints anyway; with `--strict` any warning stops
everything (exit 3), also with `--yes` (`--yes` only skips the confirmation screen). So either the whole strip prints or nothing does. Literal text `--then` cannot be printed:
it always separates parts. `--dry-run` shows the whole strip (up to 12 labels on
the terminal; `bobina preview -o strip.png` has all of them) and every warning; the confirmation screen shows the
same before `p`. Only one part can read stdin (`-`).

Several targets are files, `@names`, images or URLs; plain words are refused (`bobina print hello world` →
use quotes: `bobina print "hello world"`). `--last` reprints a multi-part job as it was; `--again` re-renders
only single documents. The tested cases are in `tests/test_strip_rules.py`.

## Saved labels (`library`, `@NAME`)

Labels printed often are saved once and printed by name, without opening an editor:

```
bobina library add shelf shelf-label.bob.md --note "pantry shelf"
bobina library add bread "# BREAD\nbest before {{ today | add(days=3) | date }}"
bobina library list                         # @shelf  pantry shelf  fields: item (--set or --ask)
bobina print @shelf --set item=Rice         # or --ask; preview and confirmation as usual
bobina library show shelf · bobina library rm shelf
```

An entry is a snapshot in `~/.config/bobina/library/` plus the folder it came from, so relative images keep
working; `@NAME` works anywhere a FILE does (`print`, `check`, `preview`). Names are letters, digits, `.`, `_`
and `-`: never paths. `--force` replaces an entry.

## Filling a template on the terminal (`--ask`)

```
$ bobina print --ask receipt.bob.md
Fill in the fields (Enter = default / leave empty):
shop (required) e.g. Padaria do Zé: Padaria do Zé
items (required) - list of [item, quantity, unit price]
  one row per line: item; qty; price  (empty line to finish)
  1> pão; 2; 1.50
  2> café; 1; 4
  3>
currency - ISO 4217 code [BRL]:
date [automatic]:
```

Only the fields still missing are asked; answers are literal data, like `--set`. Then the usual preview and
confirmation follow.

## Images, SVG and PDF as the target

`bobina print photo.jpg`, `bobina print logo.svg`, `bobina print label.pdf --page 2` (or `--page 1-3`; default: all
pages, one image per page) build a one-image document and go through the same preview and confirmation. Vector
files are rendered at the paper width and thresholded (crisp text and lines). Typical use: export a label from
another app (Dlabel, a browser, Office) as PDF and print it with bobina's calibration.

A file is recognized by its content, not only its name. Anything else (Word, Excel, PostScript/EPS, binary
files, a broken image) is refused with the list of supported formats and a hint to export as PDF: printing it
would waste paper on garbage, so this is an error, not a nudge. Inside a document the same problems are
nudges (`I101`) and the rest prints; a document with nothing left to print adds `L105`.

`bobina print https://… --allow-net` does the same for an https image. Network images are off unless the command
line says `--allow-net`, never from a document by itself; private and local addresses are refused (see
`docs/SECURITY.md`). `--sandbox`: a shared document's images only from its folder and `image_dirs` (config.toml, `I108`).

## Shape

```
bobina [global options] <command> [arguments] [command options]
```

Global options:

| Option | Effect |
|---|---|
| `--profile NAME` | printer profile (default: configured; base `mtp-ii-58`) |
| `--printer ADDRESS` | target device (default: from config/profile) |
| `--quiet` | no nudges |
| `--strict` | nudges become errors (exit 3) |
| `--json` | structured output |
| `--dry-run` | never touch the printer |
| `--yes`, `-y` | print without the confirmation screen |
| `--verbose` / `--debug` | more detail / dump bytes sent |
| `--no-color` | no color (also honors `NO_COLOR`) |
| `--help`, `--version` | |

Short flags are allowed only for the most common options (`-o` output, `-q`, `-n` dry-run, `-y`, `-h`) and, like command aliases, are never used in docs or generated output.

Configuration precedence: **flag > document front matter > `~/.config/bobina/config.toml` > profile > built-in default**.

<!-- 'Help layout' left out here: see docs/CLI.md -->

## Lists

Pattern: `bobina <thing> list` — table for humans, `--json` for machines.
`bobina status --list`, `bobina fonts list`, `bobina profile list`, `bobina template list`, `bobina help nudges`.

## Nudges

Flow of warnings, refusals and prints: [`docs/diagrams/nudges-flow.md`](docs/diagrams/nudges-flow.md).

One format on stderr, with a stable code so they can be filtered or allowed:

```
warning[B101] line 12: 1px stroke prints broken on profile mtp-ii-58 → use 2px  (evidence: R4-01)
warning[F204] line 3: font "Z003" at 16px is illegible → use ≥ 28px or Atkinson 16px  (evidence: F1-16)
```

- Code = category + number: `B` drawing, `F` font, `Q` barcodes/QR, `L` layout, `I` image, `P` printer, `M` markup.
- Always: where, what, suggestion, evidence (the test id that justifies it).
- `--quiet` silences all; `--allow B101,F204` (or front matter `allow: [B101]`) silences specific ones.

## History (`bobina history`)

Every `bobina print` is recorded, whatever happens: printed, cancelled, failed, saved (`-o`), dry run or stopped by
`--strict`. One JSON line per job in `~/.local/state/bobina/history.jsonl` (schema `bobina.history/1`): id, time,
duration, outcome and exit code, printer and profile, labels, length, ✂ cuts and tear feeds, the parts (file names),
counters used, every problem (same fields as `--problems json`) and the sha256 of the bytes sent.

```
bobina history                              # newest first, one line per job (like git log --oneline)
bobina history --long --limit 5             # every detail
bobina history --outcome failed --since 2026-11-01
bobina history show last                    # or an id, or the start of one
bobina history stats                        # jobs by outcome, labels, paper per week, frequent problems
bobina history --json · bobina history clear --yes
bobina history export --format csv --since 7d -o jobs.csv   # jsonl (default) or csv, all matching jobs
```

**For log and audit systems.** `history export` writes the stored lines (JSONL) or CSV with fixed columns, oldest
first: `id, time, command, outcome, exit, duration_s, printer, profile, labels, labels_printed, length_mm, cuts,
tears, saved_to, files, problems, argv` (new columns only ever go at the end). `--log FILE` on any command (or
`log_file` in config.toml) appends that run's problems as JSON lines (schema `bobina.log/1`: time, job id,
command, exit, code, severity, message, line, source), also with `-q`; masked like the history, and a log that
cannot be written is a note, never an error.

Private by default: the text of labels is not kept; on the stored command line, inline text becomes `text`,
`--set`/`--set-all`/`--where` keep only the key (`KEY=***`, they can be a Pix key or a phone number) and option
values are kept only for file and number options. Problem messages are stored with every value given to the job,
long digit runs and e-mails replaced by `***`. Abbreviated options are refused, so none slips past this. `bobina config set history off` turns it off;
`history_max` (default 5000) bounds it.

## Problems: one format, four renderings

Every error, warning and note has a code from the catalog (`bobina help nudges`; errors are `E1xx`–`E5xx`) and
the same fields. `--problems` (any command; or `BOBINA_PROBLEMS`) chooses how they are written to stderr:

| Format | For | Example |
|---|---|---|
| `pretty` (default) | people | `! warning [I101] part 3 (f.bob.md), line 3: image 'missing.png' …` + `→ hint` |
| `plain` | grep, scripts | `warning I101 part 3 (f.bob.md) line 3: image 'missing.png' … -- hint` |
| `json` | one document | `{"outcome": "nothing printed", "problems": [ … ]}` |
| `jsonl` | logs | one object per problem per line |

Fields (schema `bobina.problem/1`): `code`, `severity` (`error`/`warning`/`note`), `message`, `suggestion`,
`line` (in the document, or null), `evidence` (the printed test behind a limit), `outcome` (`nothing printed`,
`printing anyway (--yes)`, `nothing printed (dry run)`, `nothing saved` for preview, empty for check and view …)
and, in multi-part jobs, `source`, `part` (number) and `file`. Exit codes are below; the most serious problem decides it.

The problems always go to **stderr**, so stdout stays free for the data of the command: `--problems json > f`
saves the human summary, not the JSON. To keep the problems of a document in a file, use `check --json`, which
writes them to stdout in the same shape, next to the paper figures:
`bobina check doc.bob.md --json > problems.json` → `{"stats": {…}, "problems": [ … ]}`. `print --json` and
`preview --json` write the same, next to what happened (`outcome`, `exit`, `saved_to`; `files` for preview): one
object on stdout, schemas in docs/schemas. `view`, `edit`, `send`, `mode` and `mcp` write no data: there `--json`
does nothing and a note says so.

**A policy for every run** (`[problems]` in config.toml): `bobina config set problems.allow L102,F301` silences
codes everywhere, `problems.error M130` makes those codes stop the job (exit 3, as `--strict` for them only),
`problems.strict on` makes every warning stop it (`--no-strict` for one run), `problems.format plain` picks the
format. The command line wins (`--allow M130` beats `problems.error M130`; `--problems` beats `BOBINA_PROBLEMS`,
which beats `problems.format`), and a document's `allow:` beats the config. Errors and security refusals are never
silenced. The MCP server reads the
same config (its JSON format stays). `bobina config unset problems` puts the whole group back, after asking
(`--yes`), and prints the command that restores it.

## Two commands at the same time

Two terminals, a script and the tower over ssh may run bobina at once. Its own files stay whole:

- **seq numbers** never repeat (see FORMAT.md, counters): each print reserves its numbers under a lock.
- **One job per printer.** A second print waits for the first ("waiting for the printer: another bobina job is
  using it…") instead of fighting for the Bluetooth link. After `busy_timeout` seconds (printer entry in
  `config.toml`, default 300) it stops with `E405` and nothing is sent. `bobina status` during a print answers
  `E405` at once.
- **Paper, history, saved labels, config, --last**: every change is made under a lock and written whole (temporary
  file + rename), so a reader never sees half a file and two changes never lose one another.
- **A damaged file is an error, not a fresh start** (`E209`, with the file name): an empty `counters.json` would
  restart the numbering. bobina never overwrites it; fix it or move it away. The paper odometer only advises: a
  damaged `paper.json` is shown on the confirmation screen and the print goes on.

## Long jobs and limits

- **Previews of long strips are split.** Above ~2.5 m (20000 dots) one image does not open in most viewers:
  `preview -o tira.png` writes `tira-1.png`, `tira-2.png` … and says so. Each page is drawn and saved on its own
  (one page in memory); previews are 1-bit PNGs.
- **`--last` keeps the exact bytes and the preview of the labels the terminal showed** (up to 12), not a drawing of
  the whole job.
- **Nothing waits forever.** A download has 20 s in all (DNS included), a device file (`transport = "file"`) and
  a `command` printer have `timeout` (printer entry, default 120 s), `bluetoothctl` calls are bounded. stdin takes
  up to 10 MB (a document), `bobina send -` up to 64 MB.
- **Servers, bots, cron: `BOBINA_NONINTERACTIVE=1`.** bobina never asks on the terminal: `--ask` and the
  confirmation stop at once with `E107` (pass `--yes` and `--set`); the notice before a font download is the
  note `F304` in the problems, never a terminal line. Also give the target explicitly and start
  bobina with stdin closed (`stdin=DEVNULL`): with no target, bobina reads a document from stdin.
- **One process per job.** bobina keeps some settings per process (problem format, Pillow's image size limit,
  caches), so call it as a command, not as a library from several threads. A server runs one `bobina`
  subprocess per job (`start_new_session=True`), behind a queue per printer; that also bounds the memory of each
  job.

## Agents

Agents and the files written for them: [agents.md](docs/agents.md); the MCP server `bobina mcp`: [mcp.md](docs/mcp.md).

## Exit codes

| Code | Meaning |
|---|---|
| 0 | ok |
| 1 | usage error |
| 2 | document error (parse) |
| 3 | nudges with `--strict` |
| 4 | printer unreachable / Bluetooth; `fonts get` could not download |
| 5 | printer error state (no paper, cover open) |
| 6 | printer language mismatch (e.g. printer in TSPL, document needs ESC/POS) |
| 7 | confirmation required (no terminal and no `--yes`) or declined |
| 8 | security error (template sandbox violation, see FORMAT.md §7) |
| 9 | the job went out (printed, saved, shown) without a part it exists for: a payment or contact code that was not built (`Q111`, `Q112`). The rest printed; `--allow Q111,Q112` makes it 0 |
| 10 | `bobina update --check`: a newer release exists |

## Install and files

- Install and upgrade: [INSTALL.md](docs/INSTALL.md) (`bobina update`).
- Config: `~/.config/bobina/config.toml` (`bobina config list`).
- Profiles: built-in + `~/.config/bobina/profiles/*.toml` (`bobina profile show NAME`).
- State (counters, drafts, last print): `~/.local/state/bobina/`.
- Downloaded fonts for other scripts: `~/.local/share/bobina/fonts/` (`BOBINA_DATA_DIR`); `bobina config set font_downloads off` (or `BOBINA_FONT_DOWNLOADS=0`) turns automatic downloads off.

<!-- 'Decided' left out here: see docs/CLI.md -->

## Implementation notes

- Printers: `transport = bluetooth` (status checked before printing: exit 5 if cover open/paper out), `command`, `file`.
- Confirmation is read from `/dev/tty`, so `cat x | bobina print` still asks.
- The last print is kept in `~/.local/state/bobina/last/` (`--last`, `--again`).
- **Calibration** (also on the `init` strip): `bobina calibrate tear` prints a ruler with no feed after it; the mm at
  the torn edge (`bobina calibrate tear 5`) + 6 mm (`tear_margin_mm`) ends every job. `bobina calibrate feed`: lines
  A–B 10 mm drawn, B–C a 10 mm ESC J right after B; `touching` (the MTP-II) keeps the safe mode, `apart` turns it
  off. **Safe by default**: an unmeasured printer sends feeds after images as white rows, waits until idle
  at the end (per-printer keys `blank_rows_after_raster`, `idle_before_tail`).
- **What a profile turns on** (`bobina profile show NAME` lists it). Three features follow the ESC/POS spec and are
  tested on the bytes only; a job that uses one gets the note `P301` (docs/TESTED.md):
  - Code pages: `encoding = "codepage"` and a `[codepages]` table (codec = `ESC t` number, in order of preference):
    accented text stays native, switching page where a character needs it. **⚠ not tested on paper.** With
    `encoding = "utf-8"` (the MTP-II) text goes as UTF-8; with `"ascii"` only ASCII is native, the rest raster.
  - Automatic cutter: `cutter = "full"` or `"partial"` cuts (`GS V`, where the paper is) after the final feed of each
    label; `--compact` labels stay glued, to be cut by hand.
    **⚠ not tested on paper.** `bobina calibrate tear` then measures the distance to the blade.
  - Native barcodes on imported profiles (`barcode.native` from the printer database). **⚠ not tested on paper.**
- `calibrate compare` finds the paper in the photo, scales it to the printable width and reports length error, row-profile correlation and a 0–100 score, plus a side-by-side PNG (exact | realistic | photo).
- `bobina paper`: a paper odometer per printer. `paper new 15m` (`1500cm`, `50ft`; or `--diameter 40mm --core 12mm --thickness 0.06`) when a roll is loaded, `--width 57mm` to warn (`P103`) when the roll is narrower; a package code (`57x30`) is refused with a question; every confirmed print adds its length; the confirmation shows the metres left, `P101` when the roll is almost over (< 1 m or 10%), `P102` when the print is longer than what is left. `paper used 3m` sets the total used, `paper used +30cm` adds to it (prints from other apps, raw `send` jobs and the self-test are not counted). On "paper out" the error suggests `paper new`.


<!-- file: docs/FORMAT.md -->

# The `.bob.md` format — `bob/1` (draft v0.4)

Status: **draft**. Becomes `bob/1` once frozen. Every feature below is marked
**✓ implemented** (covered by tests) or **◇ planned** (part of the format, not implemented yet;
using it gives the note `M103` or `M102`, never an error).

A `.bob.md` file describes a print for a thermal roll printer. It is valid Markdown (it reads well on GitHub
or Obsidian) and maps predictably onto narrow, low-resolution printers.

## 0. Principles

- **Plain Markdown first.** Any Markdown file is a valid `.bob.md`.
- **Readable over terse.** Names are full English words (`invert`, `align=center`), lowercase, never codes.
- **Reuse standards.** CommonMark + Pandoc-style attributes for markup, Jinja for variables, Unicode CLDR for
  dates and numbers, BCP 47 for languages, IANA for time zones.
- **The document says what, the printer profile says how.** Native command or raster, dots per millimetre and
  every limit come from the profile, so the same file prints on 58 mm and 80 mm, 203 and 300 dpi.
- **Nudges, not blocks.** Anything questionable prints with a warning that carries a suggestion and the test
  that justifies it. Only security violations stop a print (§9).
- **What you check is what you print.** The preview is the exact dot pattern sent to the printer.

File extension: **`.bob.md`** (canonical); `.bob` is accepted. Encoding: UTF-8.

## 1. Front matter (optional) ✓

```yaml
---
bob: 1                         # format version (informational for now)
profile: mtp-ii-58             # printer profile; the CLI or the printer config can override it
locale: pt-BR                  # BCP 47: month names, numbers and money, all in it (`lang:` too); default: the machine's (§7.1)
timezone: America/Sao_Paulo    # IANA; default: the system zone
align: left                    # default alignment: left | center | right | justify
size: normal                   # default text size (§5)
fonts:                         # font roles and aliases (§4)
  body: native
  title: native
  code: IBM Plex Mono
  hand: Z003
image: { dither: floyd-steinberg, gamma: 1.8 }   # photo defaults (§6.5)
tasks: { done: strike }        # strike (default) | check | plain (§2)
counters:                      # persistent sequences (§7.3)
  ticket: { start: 1, format: "A-{:03}" }
allow: [F301]                  # nudge codes accepted for this document (silenced)
template: receipt              # fill a template (§8); the other keys become its fields
labels: { pt: { total: Total } }   # override a template's fixed labels
---
```

Every key is optional. Any other key is a **variable** available to the body (`shop: Padaria` → `{{ shop }}`).

## 2. Markdown ✓

| Markdown | Result |
|---|---|
| `#`, `##`, `###` (and deeper, styled as `###`) | headings in the **printer font**: 2×2 bold, 1×2 bold, bold (profile `native.headings`); a raster font with `fonts.title` |
| paragraph | word-wrapped by bobina, never by the printer (the printer splits words) |
| a newline inside a paragraph | a **line break** (as in Obsidian), not a space |
| `**bold**` `*italic*` `~~strike~~` `` `mono` `` | inline styles (table cells too); italic and strike are drawn as raster on printers without them |
| `- item`, `1. item`, nested lists | bullet `•`, right-aligned numbers; nested items and continuation lines align under the item text |
| `- [ ] todo`, `- [x] done` | drawn checkboxes; done items struck through. `tasks.done: check` = box only, `plain` = `[ ]`/`[x]` in the printer font (fastest) |
| `\| a \| b \|` tables | printer-font grid, bold titles and a rule (empty titles: none); one `{…}` under it: `style=plain\|receipt\|lines\|grid\|header-invert\|zebra`, `font=Terminus size=16px` (~48 columns on 58 mm), `.compact`, `orientation=`; a column's `{width=9ch prefix="R$ "}` ends its title cell: [guides/tables.md](docs/guides/tables.md); a cell's or row's `{.invert}`, `span=all`: [table-cells](docs/guides/table-cells.md); [receipts](docs/guides/receipts.md); `bobina help table` |
| `---` | divider (§3) |
| `> quote` | `│ ` prefix |
| `::: {.box}` … `:::`, `:::: {.columns}` | a frame ([layout](docs/guides/layout.md)) ⚠ not tested on paper; blocks side by side ([layout-columns](docs/guides/layout-columns.md), `bobina help layout`) ⚠ not tested on paper |
| `![alt](photo.jpg){…}` | image (§6.5) |
| `:fragile:`, `:wash-30:` … | an **icon**, 2 columns (`{size=3x}`: big); names and meanings: [guides/icons.md](docs/guides/icons.md). Never from code or data; unknown: `M161` |
| `<!-- comment -->` | ignored |
| `\*`, `\#` … | CommonMark escapes: the character is printed literally |

## 3. Attributes `{…}` ✓

Pandoc syntax: `.class`, `key=value`, `key="quoted value"`. They go:
- at the end of a heading or paragraph line: `# SALE {.invert .center}`; in a paragraph, its line and those above back to the previous `{…}`
- on a span: `Total: [R$ 42,00]{.bold size=large}`
- on a line of their own: it applies to the **block above** (tables, images, objects): a table followed by `{.compact}` (blank line or not)
- on a divider: `--- {.dashed thickness=2}`

`Table 4 {.center}` / `Waiter: Ana {.right}` / `Thanks` on 3 lines: centred, right, left.

| Class | Effect |
|---|---|
| `.left` `.center` `.right` `.justify` | alignment (justify spreads spaces on the character grid, or pixels in raster) |
| `.bold` `.italic` `.underline` `.strike` | style for the whole block or span |
| `.invert` | on a block: a **continuous** white-on-black band (raster); on a span: inverted words (native) |
| `.flip` | upside down (native `ESC {`, rows sent in reverse order; raster when a row is not native) |
| `.mono` | monospace (the printer font is already monospace) |
| `.compact` | tables: do not stretch |
| `.solid .dashed .dotted .double .wavy .cut` | divider style (`.cut` adds scissors: a place to tear) |

| Key | Effect | Status |
|---|---|---|
| `size=` | §5 | ✓ |
| `font=` | a role, alias or family name (§4) | ✓ |
| `align=` | same as the alignment classes | ✓ |
| `rotate=` | clockwise, like CSS: `90`, `180`, `270` exact; other angles allowed (nudge `B102`); always raster | ✓ |
| `render=raster\|native` | force how a block is printed (text blocks and QR codes) | ✓ |
| `thickness=` | divider stroke in dots (minimum 2, nudge `B101`) | ✓ |
| `leading=` | space between lines: `leading=18` dots, `18px` or `2mm`. Printer font: line height + N (`ESC 3`) | ✓ |
| `tracking=` | extra space after each character, in dots (≤ 32). Printer font: `ESC SP n`, ×2 at 2× width (not on the MTP-II: `native.tracking_unscaled_at`) | ✓ |
| `indent=` | left indent: `indent=4` columns, or `indent=3mm` / `24px`; wrapped lines stay aligned | ✓ |

Unknown classes or keys and those a block does not take (`leading=` on a table…) give `M101` and are ignored.

## 4. Fonts ✓

Three levels, from general to specific:

1. **Roles** in front matter — `body` (paragraphs, lists), `title` (headings), `code` (inline `code` in raster blocks).
2. **Aliases** — any other name in `fonts:` (`hand: Z003`), used with `{font=hand}` on a block or a span.
3. **Family names** — `{font="Atkinson Hyperlegible"}`.

`native` (the default for `body` and `title`) is the printer's internal font: fastest, sharpest, lightest on the
battery. Any other font makes that block raster. A native block with a raster span becomes raster too, drawn
with the printer-font look.

Fonts are looked up among the **bundled** fonts first (same result on every machine: Atkinson Hyperlegible,
IBM Plex Mono, Barlow Condensed, Terminus, Spleen, DejaVu Sans), then among installed fonts (fontconfig).
A font that cannot be found falls back to Atkinson Hyperlegible (`F203`).

Quality nudges, from the printed tests of the profile:
- below a font's **tested minimum** → `F201` with the minimum and the evidence;
- an **untested** font: bobina measures its stem at the requested size and warns below 2 dots (`F202`);
- inverted raster text thinner than bold 20 px → `F204`;
- a character the printer font lacks (emoji, arrows, `☐`) → that **line only** becomes raster (`F301`, a note);
  a character no font has → printed as a box (`F302`).

**Other scripts** (Thai, Indic, Khmer, Myanmar, Ethiopic, CJK): the first time a document needs one, bobina
downloads its Noto font (pinned, 38 KB for Thai, up to 8.3 MB for CJK), says so first (font, OFL license, size,
source; `F304`) and keeps it in `~/.local/share/bobina/fonts/` for offline use. No network, or `bobina config set
font_downloads off`: boxes and `F305` (`bobina fonts get thai`, a language or a document). Han follows `lang:` (ja, ko, zh-TW), else nearby kana or hangul, else Simplified Chinese. These lines, and Arabic or
Hebrew ones, are drawn whole (joined, stacked, right to left), never letter by letter.

`bobina fonts test "FAMILY"` prints a size ladder; `bobina fonts mark "FAMILY" PX` records your minimum.

| Size at 203 dpi | Height | What works (tests F1, F2, R5) |
|---|---|---|
| < 12 px | < 1.5 mm | nothing legible |
| 12–13 px | ~1.5 mm | bitmap fonts made for it (Terminus, Spleen) |
| 14–19 px | ~2 mm | regular sans/mono with a large x-height (Atkinson) |
| ≥ 20 px | 2.5 mm | most fonts, serifs, thin weights, bold inverted text |
| ≥ 28 px | 3.5 mm | script and decorative fonts |

## 5. Sizes ✓

Named sizes are **physical**; the profile converts them with its `dpi`:

| Name | Height | 203 dpi | 300 dpi | Printer font (mtp-ii-58) |
|---|---|---|---|---|
| `small` | 1.5 mm | 12 px | 18 px | 1×1 |
| `normal` | 2.5 mm | 20 px | 30 px | 1×1 |
| `large` | 3.5 mm | 28 px | 41 px | 2×2 |
| `title` | 5 mm | 40 px | 59 px | 2×2 |
| `huge` | 8 mm | 64 px | 94 px | 3×3 |

Exact sizes: `size=20px` or `size=3mm` (raster fonts; the printer font uses the nearest multiplier, `F303`) and
printer multipliers `size=2x`, `size=1x2` (width × height; above 4× prints jagged).

## 6. Objects (fenced blocks)

The info string carries the type and attributes: ` ```qr {width=half .right} `. Every object (image, code, `pay`,
`contact`) is centred unless `.left`/`.right`; `width=full|half|third|50%|30mm|200` sizes it (codes: the largest
integer module); `caption="…"` follows it unless `caption-align=left|center|right`.

### 6.1 QR code ✓

````markdown
```qr {ecc=M}
https://example.com
```
````

`module=` dots per module (profile default 4; minimum 3 native, 4 raster → `Q101`), `ecc=L|M|Q|H` (`L` → `Q102`),
`width=` (native: module ≤ 16), `render=raster`, `caption="Menu"`. Content that fits no QR → `Q109`, nothing printed.
An image keeps its 2-module quiet zone on the paper (`Q103`: a smaller module). The MTP-II's own QR always
has 5-dot modules (version 3–7): `width=` prints an image that wide; `module=` or more data, an image with `Q113`.

### 6.2 Barcodes ✓

````markdown
```barcode {type=code128}
ABC-123
```
````

`type=code128` (default) `ean13 ean8 upca code39 code93 codabar itf` — native on the printer, with an exact
preview. `module=` (minimum 2), `height=` dots (default 80), `text=below|above|both|none`, `width=` (module ≤ 6). `orientation=auto|horizontal|vertical`:
`auto` turns a barcode wider than the paper into a **vertical** one along the paper, so it is never cut (`Q110`,
a warning, since you may not want it); vertical barcodes are raster with module ≥ 4 along the paper and a
10-module white margin (measured: 2 and 3 did not scan). CODE39 gets the firmware's mod-43 check character in the
bars (not in the text). 1–250 printable ASCII characters; types the profile does not support → `Q106`; weak types
(ITF) → `Q107`.

### 6.3 Payment codes (`pay`) ✓

````markdown
```pay {scheme=upi to="shop@okbank" name="Chai Point" amount=120 note="Order 42"}
```
````

One block for every payment scheme, with the same attributes: `to=` who receives, `name=`, `amount=` (`24.90` or
`24,90`, in the scheme's currency), `ref=` your reference, `note=` text for the payer; a few schemes take an extra
(`city=` Pix, `bic=` SEPA, `currency=` PayPal, `label=` other). `caption=auto|none|"text"`: `auto` prints a line
under the code with the scheme and the amount (`Pix · R$ 10,00`), or the name. The QR attributes (`width=`,
`module=`, `ecc=`) work too. Pix is one scheme like the others: `pay {scheme=pix to=… name=… city=…}`. Attributes
take `{{ }}`, so a receipt per row carries its own amount. Without `amount=` (or with 0) the code is open: the payer
types it.

| Scheme | `to=` | Tested in the app |
|---|---|---|
| `pix` (Brazil, BR Code with CRC16) | Pix key: CPF/CNPJ (check digits verified), e-mail, +55 phone, random key | ✅ banking apps, 05/11 (CPF, e-mail, phone keys) |
| `upi` (India, `upi://pay`; `name=` required) | UPI ID (`shop@okbank`) | ⚠ not tested in a payment app |
| `epc` (SEPA / GiroCode, EPC069-12 v002; `name=` required) | IBAN (check digits verified) | ⚠ not tested in a payment app |
| `promptpay` (Thailand, EMVCo) | phone, 13-digit tax ID or e-wallet ID | ⚠ not tested in a payment app |
| `paynow` (Singapore, SGQR; `name=` required) | UEN or mobile (+65…) | ⚠ not tested in a payment app |
| `bitcoin` (BIP21) | address | ✅ a bitcoin wallet, 09/11 |
| `lightning` | BOLT11 invoice, LNURL or lightning address | ⚠ not tested in a payment app |
| `paypal` `revolut` `wise` `picpay` `mercadopago` | user name or the app's link | ✅ each app, 09/11 |
| `cashapp` `venmo` | `$cashtag` or user name | ⚠ not tested in a payment app |
| `other` (WeChat Pay, Alipay, DuitNow, Yape, QRIS…) | — the payload read from the app's own QR, in the block body | ⚠ reprinted unchecked |

A missing or invalid attribute (an IBAN with a wrong check digit, a UPI ID without `@`, more decimals than the
currency has) gives `Q111` with a working example, and the code is not printed: the rest of the document is, and
the command exits with 9 so a script or agent knows (`--allow Q111` for 0). A scheme nobody has scanned with its
real app gives the note `P302`; scan a print before customers use it (docs/TESTED.md). No brand logos (they need
a licence). Each scheme's fields, official names and limits: `bobina help pay SCHEME` (`--json` too) and
[pay.md](docs/pay.md). A value over a limit is an error (`Q111` says how much to cut), never cut.
An amount that reads two ways (`amount=1.890`) is `Q111` too: write `1890`, `1.890,00` or `1.89`.
The same value in `| paymoney`, or in `| currency` without a locale (§7.1), is printed as typed with `M202`.

### 6.4 Data Matrix and PDF417 ✓

````markdown
```datamatrix {width=third}
batch 42
```

```pdf417 {module=2 columns=4}
long text
```
````

Raster (the printer has no native Data Matrix; its native PDF417 does not work). Data Matrix: `module=` (≥ 4),
`size=`. PDF417: `module=`, `ratio=`, `columns=`.

### 6.5 Images ✓

`![alt](photo.jpg){width=50% dither=atkinson gamma=1.5 .left}` or a fence ` ```image {…} ` with the path inside.

- Path relative to the document; `data:image/…;base64,…` embeds the image (≤ 10 MB).
- Formats: PNG, JPEG, GIF (first frame), WebP, BMP, TIFF; **SVG** and **PDF pages** (`page=N`, default 1) are
  rendered straight at the target width (extras `bobina[svg]`, `bobina[pdf]`; missing → `I105`); they print as
  line art unless `.dither` or `dither=`.
- `https://` URLs only when the command line has `--allow-net` (`I103` otherwise); public hosts only,
  no redirects, ≤ 10 MB (`I106`); every fetch is reported (`I104`). A document cannot enable the network.
- `width=` as on every object (default: the paper width), `dither=floyd-steinberg|atkinson|bayer|threshold`,
  `gamma=` (defaults from front matter `image:`, then the profile — tuned on printed ramps).
- A drawing prints black and white, a photo dithered (`I109` says which; a plain background does not count);
  `.dither`, `.threshold` or `threshold=60%` choose.
- `rotate=` any angle, then `mirror=x|y|xy` (`.mirror`: x): fitted whole (`I110`). `caption="…"`/`caption=alt`: a line under.
- Images above 40 megapixels are refused (`I101`), unreadable ones give `I101` and the rest prints.

### 6.6 Text ✓

` ```text ` (or no type) prints the lines as they are, in the printer font, wrapping only lines wider than the paper
(`L103`). `rotate=90` turns the block. Any other language name (` ```python `) prints the same way with `M102`.

### 6.7 Raw bytes ✓

````markdown
```raw
1b 40   # hex bytes sent as-is; comments after #
```
````

The escape hatch: no checks, no preview (`P201`). Never accepted from variables (§7.4).

### 6.8 Contact codes (`contact`) ✓

````markdown
```contact whatsapp
+55 11 90000-0000
```
````

The network after `contact`; the value in the body: a phone with its country code, a user name or the app's link.
It prints a QR of the network's public link and a caption. `vcard` and `mecard` take `key: value` lines. A value
that makes no link is `Q112` (code left out, exit 9); every network gives `P303` until scanned with its app.
Networks and values: `bobina help contact` and [contact.md](docs/contact.md).

### 6.9 Planned objects ◇

Shapes.

## 7. Variables (Jinja) ✓

The body is a **Jinja** template, evaluated once in a **sandbox**: `if`, `for`, `set x = …`, `with` and `{{ }}` only
(others: `M311`), no files, no network. Comments are `<# … #>` (so `{#id}` stays a
Pandoc attribute).

Available: front-matter variables, template fields, `now` and `today` (time zone aware), `seq` (§7.3), `range`,
`namespace`, `label` (§8), and Jinja's built-in filters plus:

| Filter | Example (`locale: pt-BR`) |
|---|---|
| `date(style\|pattern)` | `{{ now \| date("full") }}` → quinta-feira, 5 de novembro de 2026 |
| `time`, `datetime` | `{{ now \| datetime("short") }}` → 05/11/2026 09:49 |
| `add(days=, hours=, minutes=, weeks=, months=, years=)` | `{{ now \| add(days=7) \| date("dd/MM") }}` → 12/11 |
| `currency(code)` | `{{ 1234.5 \| currency("BRL") }}` → R$ 1.234,50 |
| `number(decimals)`, `percent` | `{{ 1234.5 \| number }}` → 1.234,5 |
| `int`, `float` | `{{ "3 dias" \| int }}` → 3 |
| `letters` | `{{ 28 \| letters }}` → AB |
| `markdown` | interprets a value as Markdown (§7.4) |
| `upper`, `lower`, `capitalize`, `title`, `trim`, `truncate(n)`, `replace(a, b)` | Jinja's own: `{{ "arroz" \| upper }}` → ARROZ |
| `titlecase` | by the document language: `{{ "arroz DA fazenda" \| titlecase }}` → Arroz da Fazenda (`en`: Bread of the Day) |
| `deaccent` | `{{ "São João" \| deaccent }}` → Sao Joao |
| `camel`, `pascal`, `snake`, `kebab`, `slug` | `{{ "Arroz da Fazenda" \| snake }}` → arroz_da_fazenda (accents removed) |
| `smallcaps` | `{{ "Arroz" \| smallcaps }}` → Aʀʀᴏᴢ (Unicode small capitals: printed as an image line, `F301`; accented letters stay lowercase) |

Number filters read what a person types: `24.90`, `24,90`, `R$ 1.890,00`, `3 dias`. A value that is not a number
or is ambiguous (`1234.567`, `3 5`) gives `M202`: `currency`/`number`/`percent` print it as typed, `int`/`float`
give their default (0) and `add` counts it as 0, never a silent R$ 0,00. `percent` reads `10%` as 0.10.

Every filter keeps data as data: `{{ value | upper }}` from `--data`/`--set` is still printed literally and still
cannot become an image path (`M312`), and neither can a value joined into a path (`'img/' ~ value`).

### 7.1 Dates and languages

One locale for dates, numbers and money (`US$ 24,90`, `09/11/2026` in `pt-BR`): the document's `locale:`, else
`locale` in config.toml (`bobina config set locale TAG`), saved on first use from the time zone (`America/Sao_Paulo`:
`pt-BR`; `LANG`'s language if official there) or else a non-English `LANG`, said once (`M203`); else English
(`M204`). Only the document's `locale:` reads a typed `1.890` as a price (else `M202`); unknown: `M205`. No font
for the script (downloads off): English words, its country's formats (`en-TH`, `F306`).

Styles `short`, `medium`, `long`, `full` follow the document `locale` (the same line prints "Thursday, November 5,
2026" in `en-US`). Patterns use CLDR syntax (`dd/MM/yyyy HH:mm`); a pattern containing `%` is strftime, with month
and day names still localized. Moment.js tokens are not supported: `YYYY` and `DD` give `M201`.

### 7.2 Undefined variables

Printed as empty with `M130`.

### 7.3 Counters

A counter is an integer kept between prints; its appearance is formatting.

```yaml
counters:
  ticket: { start: 1, step: 1, format: "A-{:03}" }   # A-001, A-002 …  (one {:spec}, Python format)
  senha:  { format: "Senha {:d}" }                   # Senha 1, Senha 2 …  (the text goes in the format)
  box:    { start: 1, stop: 26, style: letters }     # A … Z, then M140 (wrap: true restarts)
  code:   { start: 255, style: hex }                 # FF, 100 …
```

| Write | Meaning |
|---|---|
| `{{ seq.ticket }}` | **one** value for the whole print (the same in the title and in the QR) |
| `{% for n in seq.ticket.take(10) %}` | ten new values in one print |
| `{% for n in range(1, 11) %}` | a local loop, not persisted |

Previews, `check` and `--dry-run` only show the next values. A print reserves its numbers when it is built, so two
prints never share one; a job not printed gives them back unless a later print took some after them, and a number
is never printed twice ([guides/counters.md](docs/guides/counters.md)). The CLI adds `--repeat N` (N
renders, new values each) and `--copies N` (identical copies); `bobina seq` lists and resets them, and
`bobina seq set NAME N` starts one at N, even before its first print.

### 7.4 Data is literal

**The author is trusted; data is not.** Values from `--data` (CSV), `--set` and any future server input:
- are inserted as **literal text** after Markdown parsing: `# PROMO` prints a hash, `{.invert}` prints braces,
  `:fragile:` prints the word;
- are never evaluated as templates;
- can never produce a `raw` block (`M314` for variables inside `raw`), choose an image path (`M312`), or carry
  control characters (removed from all text and barcode data before encoding).

`| markdown`: the author's values (front matter, literals) get all but `raw` (`M121`); others get
text markup only, after parsing (no `{…}`; images `M122`; code blocks, `:::`, link definitions `M123`). Template violations are **errors**: files (`M310`), unsafe attributes and `.format()` (`M311`), more than 2000 loop
iterations or 2 MB of output (`M313`), template paths outside the document folder and
`~/.config/bobina/templates` (`M315`). See `docs/SECURITY.md`.

## 8. Templates ✓

A template is a `.bob.md` whose front matter declares its fields:

```yaml
---
fields:
  shop:  { required: true, example: "Padaria do Zé" }
  items: { required: true, type: table, columns: [item, qty, price] }
  pix:   { help: "Pix key: adds a Pix QR for the total" }
  date:  { default: "{{ now | datetime('short') }}" }
labels:
  en: { total: TOTAL, thanks: "Thank you!" }
  pt: { total: TOTAL, thanks: "Obrigado!" }
---
```

- `required: true` → empty gives `M131` (a warning in the confirmation screen); a `default:` may be an expression.
- `was: [old_name]` → a document that still uses a renamed field gets `M101` naming the new one.
- `labels` are picked by the document language (`{{ label.total }}`) and overridable with `labels:` in the document.
- Using one: `template: receipt` in front matter, the other keys are the fields. Lookup: a `.bob.md` path inside the
  document folder, `~/.config/bobina/templates/NAME.bob.md`, then the built-ins: `receipt` (items, total, optional
  Pix), `label`, `todo`, `card`, `note` and a gallery of shop tags (`bobina template list`; recipes in
  [guides/templates.md](docs/guides/templates.md)).
- `--ask` (on `print`, `check`, `preview`) asks the fields still missing on the terminal, in the order the
  template declares them, showing `help`, `example` and the default (`[automatic]` for expressions);
  `type: table` fields take one row per line (`item; qty; price`, empty line to finish). A document without
  `fields:` gets its undeclared `{{ variables }}` asked. Answers are data, exactly like `--set` (literal,
  never Markdown or template code); fields already set by the front matter, `--set` or `--data` columns are
  not asked; a required field left empty prints with `M131`. No terminal → usage error.
- `bobina template show NAME` lists the fields; `bobina template new NAME FILE` writes a starter with every field
  marked `# required` / `# optional`.

## 9. Rendering contract

- bobina decides every line break; the printer never wraps.
- Per line, native when the profile says the printer does it well, raster otherwise — a raster line looks like the
  native ones (the printer font is emulated); `render=` forces it.
- A print starts with the profile's top margin (fixes the faded start), separates blocks by `block_gap_dots`, and
  ends with enough feed for the last line to clear the tear bar with room to spare (profile `feed_after_dots`,
  or the printer's measured `tear_mm` + 6 mm; `tear_margin_mm` in the printer's config.toml changes the 6 mm).
- Errors stop a print only for parsing (`DOC`) and security (`M31x`); everything else is a nudge.

<!-- '10. Conformance' left out here: see docs/FORMAT.md -->

## Appendix A — nudge codes

Categories: **B** drawing · **F** fonts · **Q** codes · **L** layout · **I** images · **P** printer · **M** markup and
templates. `bobina help nudges` prints the same list; `allow: [CODE]` or `--allow CODE` silences one.

Errors (`E…`) stop the job: nothing prints. Exit codes are in `docs/CLI.md`.

`E101` command line usage · `E102` this command takes one document · `E103` a job option was given twice with
different values · `E104` --then / --compact misuse · `E105` --last / --again misuse, or nothing printed yet · `E106`
only one part can read stdin · `E107` a terminal is needed (confirmation or --ask) · `E201` file not found or
unreadable · `E202` file type not supported as a target · `E203` image, PDF page or page range not usable · `E204`
network target needs --allow-net · `E205` nothing to print · `E206` saved label (library) problem · `E207` unknown
template, profile, font or help topic · `E208` output file problem (exists, format) · `E209` a bobina state file is
damaged or busy (counters, paper, library, config) · `E301` data file unreadable or in an unsupported format · `E302`
no data rows (or none match --rows/--where) · `E303` unknown column or sheet · `E304` invalid value (--rows,
--copies-from, --set, length) · `E305` job too large (1000 labels, 100 copies) · `E401` no printer configured or
unknown printer · `E402` printer unreachable · `E403` printer not ready (paper, cover, error) · `E405` printer busy:
another bobina job kept it too long · `E406` `bobina init` found no printer to set up · `E501` document error · `E601`
no AI found, or an unknown AI name · `E602` the AI did not answer · `E701` could not check for a new bobina
(`bobina update`)

Nudges:

| Code | Severity | Meaning |
|---|---|---|
| `B101` | warning | stroke thinner than 2 dots prints broken |
| `B102` | note | free rotation angles look jagged |
| `F201` | warning | font below its tested minimum size |
| `F202` | warning | untested font with strokes thinner than 2 dots |
| `F203` | warning | font not found, a bundled font was used |
| `F204` | warning | inverted raster text too thin or small |
| `F205` | warning | font size out of range (6 to 400 px), clamped |
| `F301` | note | glyph not in the printer font: line printed as an image |
| `F302` | warning | glyph missing in every available font |
| `F303` | note | size not supported natively, nearest native size used |
| `F304` | note | font for another script downloaded (once; used offline from then on) |
| `F305` | warning | font for this script not downloaded (off, or no network): letters print as boxes |
| `F306` | note | no font for the locale's script (none, or downloads off): English words, its formats |
| `Q101` | warning | QR module too small to scan reliably |
| `Q102` | warning | QR error correction L reads with difficulty |
| `Q103` | warning | QR wider than the paper |
| `Q104` | warning | barcode wider than the paper |
| `Q105` | note | barcode preview is approximate (no encoder for this type) |
| `Q106` | warning | barcode type not supported by this printer |
| `Q107` | warning | barcode type prints but phones struggle to read it |
| `Q108` | warning | barcode module too thin to scan |
| `Q109` | warning | invalid barcode content |
| `Q110` | warning | barcode turned vertical to fit the paper |
| `Q111` | warning | payment code not built: an attribute is missing or invalid (left out, exit 9) |
| `Q112` | warning | contact code not built: the network or its value is wrong (left out, exit 9) |
| `Q113` | note | native QR with fixed modules: this QR printed as an image |
| `L101` | warning | word longer than the line was split |
| `L102` | note | long print |
| `L103` | warning | preformatted line longer than the paper was wrapped |
| `L104` | warning | rotated block wider than the paper was cropped |
| `L105` | warning | nothing printable: every block was skipped |
| `L106` | note | table turned vertical |
| `L107` | warning | table columns narrowed to fit the paper |
| `L108` | note | the width each table column got (`check` only) |
| `L109` | warning | box title cut (…) |
| `L110` | note | a column that did not fit moved to a new row |
| `L111` | warning | no room for a box or columns: printed without them |
| `I101` | warning | image not found, unreadable or in an unsupported format |
| `I102` | note | image downscaled to the paper width |
| `I103` | warning | network image skipped (the server would see the print; `--allow-net` if trusted) |
| `I104` | note | image fetched from the network (the server sees the print) |
| `I105` | warning | PDF/SVG support not installed |
| `I106` | warning | network source refused (private address, redirect, type, size) |
| `I107` | warning | `![](a b.png)` is not an image (path with a space): write `![](<a b.png>)` |
| `I108` | warning | image outside its folder and `image_dirs` (`--sandbox`, MCP) |
| `I109` | note | an image read as a drawing (black and white) or a photo (dithered) |
| `I110` | note | a slanted image prints smaller, to fit its corners |
| `P101` | warning | the paper roll is almost over (estimate) |
| `P102` | warning | the print is longer than the paper left on the roll (estimate) |
| `P103` | warning | the roll is not as wide as this printer's paper (`paper new --width`; recorded anyway) |
| `P104` | note | roll length not set: no paper estimate |
| `P105` | note | `--compact`: labels print at once, without stops |
| `P106` | note | `--step` without a terminal: labels print at once |
| `P201` | warning | raw bytes bypass every check and are not previewed |
| `P301` | note | this job uses a feature not tested on paper yet |
| `P302` | note | a payment code nobody has scanned with its app yet |
| `P303` | note | a contact code nobody has scanned with its app yet |
| `P401` | note | no Bluetooth or USB search here (says why) |
| `P402` | note | the name does not settle the profile: one was taken |
| `P403` | warning | a USB printer this user cannot write to |
| `P404` | warning | config.toml names a profile bobina does not know |
| `M101` | warning | unknown attribute |
| `M102` | note | unknown block type, printed as preformatted text |
| `M103` | note | attribute not implemented yet (ignored) |
| `M104` | note | a `{…}` after a table's title row: GitHub shows the table as text |
| `M105` | warning | a `:::` block is never closed |
| `M120` | note | field rendered as Markdown |
| `M121` | warning | raw block removed from a variable |
| `M122` | warning | image removed (not the author's value) |
| `M123` | warning | code block, `:::` or link definition removed (not the author's value) |
| `M124` | warning | reserved characters removed |
| `M130` | warning | undefined variable printed as empty |
| `M131` | warning | required template field is empty |
| `M140` | warning | counter passed its stop value |
| `M150` | warning | `--join`: rows of the main source without a match (their joined fields print empty) |
| `M151` | warning | `--join`: the joined source repeats a key (the first row is used) |
| `M152` | warning | `--join`: a column exists in two sources; `{{ col }}` uses the main one, `{{ b.col }}` the other |
| `M153` | warning | data values lost: a row with more fields than the header, or values under an empty header |
| `M154` | warning | the data header repeats a column name (the last one is used) |
| `M155` | note | a data source was renamed because a column has its name |
| `M156` | note | an option has no effect here (`--sheet` on a CSV, `--repeat` with `--data`) |
| `M157` | warning | `--set` replaces a data column of the same name in every row |
| `M158` | note | data columns renamed to names usable in `{{ }}`: `Product Name` → `product_name`, `Preço` → `preco` |
| `M159` | warning | two data columns would get the same usable name; the first keeps it |
| `M160` | note | Excel formula cells without a saved value print empty |
| `M161` | warning | no icon with that `:name:` (printed as written) |
| `M201` | warning | date pattern looks like Moment.js |
| `M202` | warning | a value is not a number, or a date moved out of the calendar (printed as it is) |
| `M203` | note | this machine's locale, from its time zone, saved in config.toml (said once) |
| `M204` | note | no locale for this machine: dates, numbers and money in English |
| `M205` | warning | the document's locale: is not a locale bobina knows (the machine's is used) |
| `M310` | error | templates cannot read files |
| `M311` | error | unsafe template operation |
| `M312` | error | a variable cannot choose a file path |
| `M313` | error | template limit exceeded |
| `M314` | error | variables cannot be used inside raw blocks |
| `M315` | error | template path outside the allowed folders |


<!-- file: docs/guides/batch-printing.md -->

# Printing a batch: one label per row

You have **one label design** and **a list of things** to label: jars in the pantry, guests at a party, products
on a shelf, kids' school notebooks. Instead of editing and printing the label once per item, you write the design
once with blanks, put the list in a table, and bobina prints one label per row.

```
  the design (with blanks)          the list (one row per label)          what prints
 ┌──────────────────────┐     ┌─────────────┬────────────┬───────┐     ┌──────────────┐
 │   {{ product }}      │     │ product     │ packed     │ shelf │     │  Brown rice  │
 │ - - - - - - - - - -  │  +  ├─────────────┼────────────┼───────┤  =  │  Packed …  A │
 │ Packed {{ packed }}  │     │ Brown rice  │ 2026-11-07 │ A     │     ├──────────────┤
 │ Shelf {{ shelf }}    │     │ Black beans │ 2026-11-07 │ A     │     │ Black beans  │
 └──────────────────────┘     │ Coffee      │ 2026-11-01 │ B     │     │  Packed …  A │
                              └─────────────┴────────────┴───────┘     ├──────────────┤
                                                                       │    Coffee    │
                                                                       └──────────────┘
```

The **column names of the table are the names of the blanks**. That is the whole idea. The files of this guide
are in [`examples/batch/`](examples/batch): run the commands from that folder.

## 1. The design, with blanks

`jar-label.bob.md` is an ordinary bobina document. Each `{{ name }}` is a blank:

```markdown
---
fields:
  product: { required: true, example: "Brown rice" }
  packed:  { help: "date the jar was filled (YYYY-MM-DD)" }
  best_before: { help: "YYYY-MM-DD; leave empty if it does not expire" }
  shelf:   { example: "A" }
---
# {{ product }} {.center}

--- {.dashed}

Packed **{{ packed }}** {.center}
{% if best_before %}

Best before **{{ best_before }}** {.center}
{% endif %}

Shelf {{ shelf }} {.center}
```

The `fields:` list at the top is optional. It documents the blanks (`bobina template show`), marks the
required ones, and lets `--ask` ask for them. `{% if best_before %}` skips that line when the value is empty.

**Try it with one label first**, filling the blanks by hand:

```sh
bobina preview jar-label.bob.md --set product="Brown rice" --set packed=2026-11-07 \
  --set best_before=2027-05-07 --set shelf=A -o one.png
```

![one label](examples/batch/one.png)

Or let bobina ask: `bobina print jar-label.bob.md --ask`.

## 2. The list, as a table

The same list in three formats. Use whichever you already have; bobina reads them all with `--data`.

**A spreadsheet** (`pantry.xlsx`, first sheet, or `--sheet Pantry`): the first filled row is the header.

| product | packed | best_before | shelf | jars |
|---|---|---|---|---|
| Brown rice | 2026-11-07 | 2027-05-07 | A | 2 |
| Black beans | 2026-11-07 | 2027-11-07 | A | 1 |
| Coffee | 2026-11-01 | 2027-02-01 | B | 1 |
| Salt | 2026-10-20 | | B | 0 |

**CSV** (`pantry.csv`), what a spreadsheet saves with "Save as CSV". Commas, semicolons, tabs or `|` all work:

```csv
product,packed,best_before,shelf,jars
Brown rice,2026-11-07,2027-05-07,A,2
Black beans,2026-11-07,2027-11-07,A,1
Coffee,2026-11-01,2027-02-01,B,1
Salt,2026-10-20,,B,0
```

**JSON** (`pantry.json`), what a program or a web service usually gives you: a list of objects, one per label,
with the blank names as keys.

```json
[
  { "product": "Brown rice",  "packed": "2026-11-07", "best_before": "2027-05-07", "shelf": "A", "jars": 2 },
  { "product": "Black beans", "packed": "2026-11-07", "best_before": "2027-11-07", "shelf": "A", "jars": 1 },
  { "product": "Coffee",      "packed": "2026-11-01", "best_before": "2027-02-01", "shelf": "B", "jars": 1 },
  { "product": "Salt",        "packed": "2026-10-20", "best_before": "",           "shelf": "B", "jars": 0 }
]
```

Columns that the design does not use (here `jars`) are simply ignored, unless you use them for copies (step 4).

## 3. Preview the whole batch, then print

```sh
bobina preview jar-label.bob.md --data pantry.csv -o all.png   # look first
bobina print   jar-label.bob.md --data pantry.csv              # confirmation screen, then p
```

![four labels, one per row](examples/batch/all.png)

Four rows, four labels, one print job. Salt has no `best_before`, so that line is not printed.

## 4. Only some rows, and copies per row

| You want | Add | With this list |
|---|---|---|
| only rows 2 to 3 | `--rows 2-3` | Black beans, Coffee |
| only shelf A | `--where shelf=A` | Brown rice, Black beans |
| everything except salt | `--where product!=salt` | the first three |
| names containing "rice" | `--where product~=rice` | Brown rice |
| as many labels as jars | `--copies-from jars` | rice ×2, beans ×1, coffee ×1, salt skipped (0) |

Filters combine. Shelf A, one label per jar:

```sh
bobina print jar-label.bob.md --data pantry.json --where shelf=A --copies-from jars
```

![shelf A, one label per jar](examples/batch/shelfA.png)

`--rows` counts data rows (1 is the first row after the header) and is applied before `--where`. Matching ignores
upper/lower case. A column name that does not exist stops with the list of columns that do.

## 5. Two sources for one label (`--join`)

Sometimes the label needs columns from two places: prices in a spreadsheet, the catalog (category, id) in a
JSON exported by another system. Name the sources and say which column matches them:

```sh
bobina print shelf-tag.bob.md --data a=prices.xlsx --join b=catalog.json --on name
```

| `prices.xlsx` (a) | | | | `catalog.json` (b) | | |
|---|---|---|---|---|---|---|
| name | price | size | category | name | category | id |
| Rice | 12.5 | 1kg | grains | rice | grocery | 101 |
| Salt | 3 | 1kg | spice | | | |

In the design, a column without a prefix works when only one source has it; the prefix picks one when both do:

```markdown
{{ name }} — {{ price }} ({{ size }})       ← name is the key; price and size only exist in a
{{ id }}                                    ← only in b
{{ a.category }}{% if b.category %} / {{ b.category }}{% endif %}   ← both have it: the prefix chooses
```

- `--data` is the **main** source: one label per row. `--join` adds the columns of the row with the same key
  (matching ignores upper/lower case). Without a name, a source is called after its file (`catalog.json` →
  `{{ catalog.id }}`).
- Different key names: `--on name=product`. Several joins: each `--on` belongs to the `--join` before it
  (`--join b=catalog.json --on name --join stock.csv --on b.id=id`).
- Rows without a match print with the joined fields empty, and one warning lists them (`M150`); guard what
  surrounds a joined field so it does not dangle: `{% if b.category %} / {{ b.category }}{% endif %}`. A key repeated
  in the joined source uses its first row (`M151`); `{{ category }}` in both sources uses the main one and says
  so (`M152`). `--where`, `--rows` and `--copies-from` work after the join, also on joined columns
  (`--where b.category=grocery`).
- Values from every source are printed literally, and only the command line chooses the files.

## Column names

A blank in the design is written like a variable: letters, digits and `_`. Headers that are not written that way
get a usable name automatically (and a note lists them): `Product Name` → `product_name`, `Preço` → `preco`,
`Data de Validade` → `data_de_validade`. The exact header always works too: `{{ row['Product Name'] }}`. If two
headers would get the same name, the first keeps it and a warning says so (`M159`).

## Good to know

- **Values are printed exactly as written.** A product called `**NEW** {{ x }}` prints those characters; data
  never becomes formatting, template code or printer commands. Only the design decides the layout.
- **Empty values**: a blank with no value prints empty (`M130`); a required one gives `M131` with the data row
  (`data row 3: required field 'product' is empty`). `--strict` stops the job instead.
- **`--set` and a column with the same name**: `--set` wins in every row (`M157`), handy to fix one field for
  the whole batch. `--where`, `--rows`, `--copies-from` and `--sheet` need `--data`; two `--data` in one part is
  an error (use `--then` to print both lists, `--join` to combine them). Both are warnings
  on the confirmation screen; nothing is blocked.
- **Spreadsheets**: formulas are not recalculated; the value Excel saved is used. `.xls`/`.ods` must be saved as
  `.xlsx` or `.csv`. Dates come out as `YYYY-MM-DD` (format them in the design with `{{ packed | date }}`).
- **Paper**: each label ends at the tear bar and bobina waits while you tear it off (`--no-step`: all at once).
  `--compact` prints one strip with ✂ lines and one feed at the end; `--then other.bob.md` adds to it.
- **Limits**: 1000 labels per job, copies included (`--copies`, `--copies-from`, `--repeat`, every `--then` part),
  and at most 100 copies of one label. Split bigger lists with `--rows`. `--copies` and `--copies-from` multiply.
- **Saved designs**: `bobina library add jar jar-label.bob.md`, then `bobina print @jar --data pantry.csv`.

## Other ideas

| Design | List |
|---|---|
| name badge (`{{ name }}`, `{{ company }}`) | the guest list exported from a form |
| shipping label (`{{ name }}`, `{{ address }}`, a QR with `{{ tracking }}`) | the day's orders as CSV |
| price tag (`{{ product }}`, `{{ price | currency('BRL') }}`, a barcode with `{{ ean }}`) | the price spreadsheet |
| school labels (`{{ child }}`, `{{ subject }}`) | one row per notebook, `--copies-from` for spares |


<!-- file: docs/guides/templates.md -->

# Ready-made templates: recipes and gallery

A template is a document with blanks that ships with bobina. You give it the values; it does the layout. Every
template below prints on a 58 mm roll with no warning.

```bash
bobina template list                          # every template and its fields
bobina template show label                    # one template: fields, required, examples
bobina template new label box.bob.md          # a starter file with every field, marked required / optional
bobina preview box.bob.md -o box.png          # look before printing
bobina print box.bob.md                       # confirmation screen, then paper
```

A document uses a template with `template: NAME` in its front matter; **the other keys are the fields**. A field
can also come from `--set NAME=VALUE`, `--ask` (asked on the terminal) or a column of `--data` (one label per row,
see [batch-printing.md](docs/guides/batch-printing.md)). `locale: pt-BR` switches the template's fixed words and the date
format to Portuguese (without it: the machine's, `bobina config get locale`). The full rules are in [FORMAT.md §8](docs/FORMAT.md).

## Recipe: a box label (`label`)

A big inverted title, lines under it and an optional Code 128 or QR code: a box, a shelf, a jar.

```markdown
---
template: label
locale: pt-BR
title: "FRÁGIL"
lines: ["Este lado para cima", "Manusear com cuidado"]
barcode: "PED-1042"
---
```

![label](spec/conformance/templates-label.png)

- `title` is required; `lines` is a list (one centred line each); `qr` instead of `barcode` for a link or a
  Pix key.
- One label per item of a list: keep the design, move the values to a CSV and print with `--data items.csv`.

## Recipe: a card (`card`)

A title between wavy rules, a message that may use Markdown (`**bold**`), a signature on the right.

```markdown
---
template: card
locale: pt-BR
title: "Feliz aniversário!"
message: "Que o seu ano seja **leve** e cheio de boas notícias."
from: "Ana e Pedro"
---
```

![card](spec/conformance/templates-card.png)

- `title` and `message` are required; without `from` there is no signature line.
- From the terminal, without a file: `bobina edit --template card` opens a draft in your editor.

## Recipe: a to-do list (`todo`)

A heading, today's date written out, one checkbox per item. An item that starts with `x ` is printed done.

```markdown
---
template: todo
locale: pt-BR
title: "Mercado"
items: ["arroz", "x feijão", "café", "pão francês"]
---
```

![todo](spec/conformance/templates-todo.png)

- `items` is required; `title` defaults to "To do" ("Tarefas" in Portuguese); `date` defaults to today, so a
  list printed on Monday says Monday.
- Leave `items` out of the file and pass `--ask`: bobina asks for the items on the terminal.

## Gallery: one template per kind of shop

Each one is a small document in [`examples/templates/`](examples/templates), printed here as it comes out of
the printer. Copy one, change the values, print.

| Shop | Template | What it has | Preview |
|---|---|---|---|
| Clothing | `clothing-tag` | brand, piece, size and colour, price, SKU as Code 128 | ![](examples/templates/clothing-tag.png) |
| Grocery | `shelf-price` | product, a huge price, price per kg or L, EAN-13 | ![](examples/templates/shelf-price.png) |
| Grocery | `sale-price` | an inverted SALE band, the old price struck through, the new price | ![](examples/templates/sale-price.png) |
| Kitchen | `food-label` | product inverted, made today, use by today + `days` (default 3), storage, who, batch | ![](examples/templates/food-label.png) |
| Jewellery | `jewelry-tag` | piece, code, metal and weight, price; short lines for a narrow strip | ![](examples/templates/jewelry-tag.png) |
| Online shop | `shipping-label` | recipient and address in large type, sender, order, tracking as Code 128 | ![](examples/templates/shipping-label.png) |
| Any counter | `pay-sign` | "Pay with …" and a big payment code for any scheme (Pix, UPI, SEPA…), the name, the amount or "any amount" | ![](examples/templates/pay-sign.png) |

- A price can be typed `24.90`, `24,90` or `R$ 1.890,00`; the template writes it in the currency of `currency`
  (default `BRL`, `R$ 24,90` in Portuguese). A price that is not a number (`consulte`) or is ambiguous
  (`1234.567`) prints as typed, with `M202`. A `days` the food label cannot count (`uma semana`) counts as 0, so
  the use-by date is today, also with `M202`: look at the warning before printing.
- `food-label` computes both dates when it prints: the same file printed tomorrow says tomorrow. Print a batch
  on the day it is made; `print --last` reprints the identical bytes, old dates included.
- Price tags for a whole shelf come from a spreadsheet: `bobina print shelf-price.bob.md --data prices.xlsx`,
  one column per field.

## Your own templates

A template is a `.bob.md` with a `fields:` front matter (FORMAT.md §8). Put it in `~/.config/bobina/templates/`
and `template: my-price` finds it; one with the same name as a built-in one wins over it. A `.bob.md` path next
to the document works too (`template: tags/price.bob.md`). The built-in ones are in
[`src/bobina/templates/`](src/bobina/templates): copy one and change its layout. `bobina template list`
shows only the built-in ones.


<!-- file: docs/SECURITY.md -->

# Security model

Status: threat model and defenses for v0.x; red teams in `tests/test_security*.py`.

## What bobina is

A local CLI. It reads a document, renders it, and — after a confirmation — sends bytes to a printer.
`bobina mcp` runs every document in `--sandbox`; a print server is planned (below).

## Trust boundaries

| Principal | Trust | Examples |
|---|---|---|
| The person at the terminal | trusted | flags, `~/.config/bobina/config.toml`, `--editor`, printer `command` |
| Document author | trusted for layout and the images it names, **not** for templates outside its folder | a `.bob.md` you wrote, or one somebody shared |
| Data | **untrusted** | `--data` CSV cells, `--set` values, future server/chat input |
| Template from elsewhere | like a document | built-ins, `~/.config/bobina/templates/`, the document folder |

## Assets

Local files (photos, notes, keys), the printer's configuration (command language, settings reachable
with vendor commands), paper and battery, counters, and the history of the last print.

## Defenses

| Threat | Defense | Test |
|---|---|---|
| Data changes structure (`# PROMO`, `{.invert}`, `**x**`, `:fragile:`) | every `{{ }}` is a placeholder, substituted as literal text after parsing (icon characters in a value are dropped) | `test_templating.py`, `test_icons.py` |
| Data evaluated as template (`{{ seq.x.take(500) }}`) | values are never re-evaluated | `test_data_is_never_evaluated_as_template` |
| Data emits printer commands | no `raw` from data (`M314`, `RAW_FENCE` in `| markdown`); C0/C1 controls stripped from all text and barcode data | `test_no_path_lets_data_emit_raw_bytes`, `test_control_characters_never_reach_the_printer` |
| Data chooses a file to print/preview | image paths with data are refused (`M312`); `| markdown` on data removes images and image fences (`M122`) | `test_data_cannot_*` |
| Data rendered as Markdown (`| markdown`) makes markup | only the author's values (front matter, fields, labels, literals) get all of Markdown; any other is a placeholder, spliced in where `| markdown` is written as text markup, never `{…}` (`M121`–`M123`). Every operation on data gives data; no bytes (`M311`) | `test_data_markup.py` |
| Shared document pulls files via `template:` | template paths must be inside the document folder or `~/.config/bobina/templates` (`M315`) | `test_template_path_outside_document_folder_is_refused` |
| Template escapes the sandbox | Jinja sandbox and an allowlist of the parsed template: `if`, `for`, `set x = …`, `with`, `{{ }}`; anything else → `M311` (`include`/`import`: `M310`); unsafe attributes, `str.format` → `M311`; globals cleared except `now`, `today`, `seq`, `range`, `namespace`, `label` | `test_sandbox_blocks` |
| Paper/CPU exhaustion | 2000 loop steps, 10 s, values and output ≤ 2 MB (`M313`), 1000 renders / 100 copies per batch, nudge above 30 cm, **confirmation before every print** | `test_sandbox_blocks`, `test_security_limits.py` |
| Spreadsheets (`--data .xlsx`) | formulas never evaluated (cached values only), file ≤ 20 MB, unpacked ≤ 200 MB (zip bomb), first 10 000 rows read; `.xls`/`.ods` refused; every value literal | `test_xlsx_values_sheet_and_no_formulas` |
| Image bombs | `Image.MAX_IMAGE_PIXELS = 40M`; base64 images and downloads ≤ 10 MB; PDF/SVG renders ≤ 8000 dots tall | `test_decompression_bomb_is_refused` |
| Image parsers as attack surface | Pillow limited to PNG/JPEG/GIF/BMP/WebP/TIFF (no EPS → no Ghostscript); PDF: one page rendered; SVG: `DOCTYPE`/`ENTITY` refused | `test_eps_is_not_opened`, `test_svg_with_entities_is_refused` |
| Shared document reads any image | `--sandbox` (MCP: always): only its folder and `image_dirs`, after symlinks (`I108`) | `test_sandbox` |
| SVG reads local files | every `href`/`url()` that is not `#fragment` or inline PNG/JPEG/GIF/WebP is removed before rendering (resvg would load absolute paths) | `test_svg_external_references_are_removed` |
| Document makes requests (tracking, SSRF into localhost/LAN/tailnet) | network images off unless the **command line** says `--allow-net` (`I103`); https only; every resolved address must be public (no loopback, private, link-local, CGNAT/tailnet, multicast; IPv4 in IPv6 checked) and the connection goes to the checked address (no rebinding); no redirects; image/PDF content types only; 10 MB / 10 s; each fetch is reported (`I104`) | `test_network_is_off_by_default`, `test_private_addresses_are_refused` |
| Malformed codes | barcode 1–250 printable ASCII; QR overflow; Pix key ≤ 77 chars, numeric amount, TLV ≤ 99 → nudge `Q109`, no crash | `test_oversized_or_invalid_codes_*` |
| Counter format strings | only one `{:spec}` allowed (`FMT_RE`), no attribute access | — |
| Font lookups | `fc-match` without a shell; the result must match the requested family | — |
| Fonts for other scripts (Thai, CJK…) | a document can make bobina download one, once: only the files pinned in `scriptfonts.py` (https at a fixed notofonts / Google Fonts commit, exact size and sha256, no redirects, 12 MB), written atomically. Reveals to GitHub that some text needs that script; `font_downloads = false` turns it off (`F305`, boxes) | `test_scriptfonts.py` |

Raw blocks written by the **author** are allowed by design (escape hatch): they always raise `P201`
in the confirmation screen and are never previewed. A shared document with a `raw` block can switch
the printer's command language on models that support it (`bobina mode esc` restores it; the MTP-II ignores it).

## Privacy

- The last print (source, bytes, preview) is kept in `~/.local/state/bobina/last/` for `print --last`.
  It can contain personal data (Pix keys, names). `bobina config set keep_last off` disables it.
- Drafts live in `~/.local/state/bobina/drafts/`.

<!-- 'Requirements before a print server or chat bot exists' left out here: see docs/SECURITY.md -->

<!-- 'Open' left out here: see docs/SECURITY.md -->


<!-- file: docs/INSTALL.md -->

# Installing bobina

bobina needs Python 3.11 or newer. Pick one way:

| You have | Run |
|---|---|
| Linux or macOS, nothing set up | `curl -LsSf https://raw.githubusercontent.com/rafaelbressan/bobina/main/get.sh \| sh` |
| uv | `uv tool install bobina` |
| Debian 12+, Ubuntu 24.04+ | the .deb (below), or `sudo apt install pipx && pipx ensurepath && pipx install bobina` |
| Homebrew (macOS) | `brew tap rafaelbressan/bobina https://github.com/rafaelbressan/bobina && brew install rafaelbressan/bobina/bobina` |
| Windows | `uv tool install bobina` or `pipx install bobina` (printer driver: `drivers/windows/`) |
| A checkout, to change bobina | `./install.sh` (editable install, plus the Bluetooth service on Linux) |

Then `bobina init` (printer, profile, locale, roll, a test strip).

## Upgrading

`bobina update` shows the upgrade command of whatever installed bobina (uv, pipx, pip, Homebrew) and asks before
running it; for the .deb and git installs it says the steps. `--check` exits 10 when a release is newer. Once a
day a command at a terminal ends with `bobina 0.1.4 is available (you have 0.1.3): uv tool upgrade bobina`, never
for agents, scripts or pipes (`bobina config set update_check off`).

## Bluetooth needs the system Python

bobina talks to Bluetooth printers through RFCOMM sockets (`socket.AF_BLUETOOTH`), which only Linux has and
only a Python built with the BlueZ headers provides. Debian's and Ubuntu's `python3` have them; the Pythons that uv
downloads and Homebrew's do not (checked on uv 0.13 and Homebrew 7). Without them a Bluetooth printer fails with
"was built without Bluetooth sockets", which says how to reinstall; file (`--path`) and command (`--command`, e.g. ssh to the host with
the printer) printers work everywhere.

- The .deb and pipx from apt use the system Python; `get.sh` picks one with Bluetooth sockets, or says there is none.
- By hand: `uv tool install --reinstall --python /usr/bin/python3 bobina` (also moves an install off uv's Python).
- Ubuntu 22.04 has Python 3.10: `sudo apt install python3.11`, then `pipx install --python python3.11 bobina`.
- Pairing and the boot service need BlueZ: `sudo apt install bluez`.

## get.sh

`get.sh` installs uv with its official installer when it is missing, then runs `uv tool install bobina`.
Running it again upgrades and keeps the extras installed before. Options go after `sh -s --`:

```bash
curl -LsSf https://raw.githubusercontent.com/rafaelbressan/bobina/main/get.sh | sh -s -- --bluetooth-service
```

| Option | What |
|---|---|
| `--bluetooth-service` | Linux: the systemd user service `bt-printer.service`: Bluetooth on and the printer paired at boot. Its files come from the git tag of the installed version, into `~/.local/share/bobina/` |
| `--extras pdf,svg,xlsx,mcp` | optional parts: PDF pages, SVG images, `.xlsx` data, `bobina mcp` (the server for agents) |
| `--version 0.2.0` | that version instead of the latest (`0.2.0rc1` for a pre-release) |
| `--python PATH` | the Python to install with |

Uninstall: `uv tool uninstall bobina`; the service: `systemctl --user disable bt-printer.service`, then delete
`~/.config/systemd/user/bt-printer.service` and `~/.local/share/bobina/`.

## Debian and Ubuntu: the .deb

Each [release](https://github.com/rafaelbressan/bobina/releases) has `bobina_X.Y.Z_amd64.deb` and `_arm64.deb`
(64-bit Raspberry Pi OS too): `sudo apt install ./bobina_X.Y.Z_arm64.deb`. It runs on the system `python3` (3.11
to 3.14) with its own copies of the dependencies, not Debian's. No apt repository (`bobina update` says the next
.deb) and no extras: for them, pipx from apt (above).

## Homebrew

This repository is the tap; install with the full name (Homebrew 7 trusts a tap only then). No extras (`pdf`,
`svg`, `xlsx`, `mcp`): for them, `get.sh --extras`. No Bluetooth sockets (above): on Linux prefer `get.sh` or the
.deb.
