docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# docx-templating

[![CI](https://github.com/sabryio/docx-templating/actions/workflows/ci.yml/badge.svg)](https://github.com/sabryio/docx-templating/actions/workflows/ci.yml)

A Rust library for generating Microsoft Word documents (`.docx`) from templates with variable placeholders, conditional sections, and loops.

## Status: Stable

**Current Version:** 1.0.0 (all phases complete)

The public API is frozen for 1.x. New features are additive and breaking changes wait for 2.0. The minimum supported Rust version is 1.89.

### Implementation Progress

- ✅ **Phase 0:** Engineering Baseline
- ✅ **Phase 1:** Package Foundation (ZIP/OPC handling)
- ✅ **Phase 2:** Text Projection (placeholders split across runs)
- ✅ **Phase 3:** Template Syntax Parser
- ✅ **Phase 4:** Context and Data Lookup
- ✅ **Phase 5:** Inline Variable Replacement
- ✅ **Phase 6:** Conditionals
- ✅ **Phase 7:** Paragraph Loops
- ✅ **Phase 8:** Table Loops and Nested Blocks
- ✅ **Phase 9:** Headers, Footers, Footnotes and Endnotes
- ✅ **Phase 10:** Hardening and Performance
- ✅ **Pipeline rewrite:** lossless document tree, resolved plan tree, pure domain

Every phase of the roadmap is now implemented. The main document is always rendered. Headers, footers, footnotes and endnotes are rendered when `TemplateOptions` asks for them; otherwise those parts are copied through unchanged.

## Features

- **Variable substitution:** `{{user.name}}`, `{{items.0}}`, `{{item}}` and `{{.}}` (current item in a loop)
- **Filters:** `{{name | upper}}`, `{{nickname | default: "friend"}}`, `{{items | len}}`, `{{total | round: 2}}`, `{{created_at | date: "%Y-%m-%d"}}`, chains such as `{{name | trim | upper}}`, and custom filters on `TemplateOptions`
- **Conditionals:** `{% if condition %} ... {% elif condition %} ... {% else %} ... {% endif %}`
- **Arithmetic:** `{{price * quantity}}`, `{{subtotal - discount}}`, `{{(price + tax) * quantity | fixed: 2}}`
- **Loops:** `{% for item in items %} ... {% endfor %}` for paragraphs and table rows, with `{{@index}}`, `{{@first}}` and `{{@last}}`
- **Table-row loops:** loop markers inside a `<w:tr>` duplicate the entire row per element
- **Multi-paragraph/row blocks:** tag lines on their own paragraphs or rows are deleted cleanly with no empty lines or rows left behind
- **Conditional rows:** `{% if %}` aligned with a table row removes the row when false
- **Nested blocks:** conditionals inside loop body cells, loops inside conditionals
- **Line break policy:** control how `\n` in a value is rendered — `InsertWordBreak` (default, emits `<w:br/>`) or `SplitParagraph` (produces separate `<w:p>` elements inheriting original formatting)
- **Whitespace preservation:** `preserve_whitespace` option (default `true`) controls whether `xml:space="preserve"` is added to replacement `<w:t>` elements with leading/trailing spaces; set to `false` to let Word normalise edge whitespace itself
- **Safe XML escaping:** All user text automatically escaped
- **Decompression-bomb protection:** ZIP entries with declared uncompressed size > 100 MiB are rejected before decompression begins (`PackageError::EntrySizeExceeded`)
- **Actionable error context:** `RenderError` variants include the DOCX part name (e.g. `word/document.xml`) so errors pinpoint exactly where template evaluation failed
- **Raw-copy passthrough:** unchanged ZIP parts are copied verbatim without decompress/recompress when the source exposes its raw archive bytes — transparent to all callers
- **Split placeholder handling:** Works even when a placeholder spans multiple XML runs
- **Flexible context:** `render` accepts a `Context`, a `serde_json::Value`, or a borrowed `serde::Serialize` value, so a caller can pass their own struct
- **One shot rendering:** `docx_templating::render("template.docx", &data)` loads and renders in a single call
- **Byte in, byte out:** `Template::from_bytes` accepts a slice or a `Vec`, and `RenderedDocument` implements `AsRef<[u8]>` and `Into<Vec<u8>>`
- **Thread safe:** a loaded `Template` is `Send` and `Sync`, so one `Arc<Template>` can render on several threads
- **Streaming output:** `Template::render_to_writer` writes the package to any `Write + Seek` sink, and `render` returns the bytes
- **Compiler style errors:** `diagnose` and `Template::diagnostic` point a caret at the paragraph that failed, with a help line
- **Multi-part templates:** placeholders, conditionals and loops work in headers, footers, footnotes and endnotes when the matching option is on

## Installation

```bash
cargo add docx-templating
```

## Usage

```rust
use docx_templating::Template;
use serde_json::json;

let output = Template::from_path("template.docx")?
    .render(json!({
        "user": { "name": "Ada Lovelace" },
        "items": [
            { "sku": "KB-01", "qty": 1 },
            { "sku": "MS-02", "qty": 2 }
        ]
    }))?;

output.write_to_file("output.docx")?;
```

### Variables

```
Hello {{user.name}}!
Invoice #{{invoice.number}}
First tag: {{tags.0}}
```

### Filters

A filter changes a value before it is inserted. Write it after a pipe, and chain
filters left to right. A filter can take one argument after a colon.

```
{{user.name | upper}}
{{nickname | default: "friend"}}
{{items | len}}
{{tags | join: ", "}}
{{user.name | trim | upper}}
```

The built in filters are:

| Filter | Effect |
| --- | --- |
| `upper` | Upper case a string or scalar |
| `lower` | Lower case a string or scalar |
| `trim` | Remove leading and trailing whitespace |
| `default: "text"` | Replace a missing or null value |
| `len` | Length of a string, array or object |
| `join: ", "` | Join an array into text, comma and space by default |
| `round: 2` | Round to a number of decimal places, half away from zero |
| `fixed: 2` | Format with exactly that many decimal places as text |
| `thousands` | Group the integer digits in threes, comma by default |
| `percent: 1` | Multiply by 100 and append `%`, with one decimal |
| `date: "%Y-%m-%d"` | Format a date with a `strftime` pattern |
| `timezone: "Europe/Paris"` | Convert an instant to a named time zone |

#### Numbers

The number filters accept JSON numbers and numeric strings:

```
{{total | round: 2}}             -> 1234.57
{{total | fixed: 2}}             -> 1234.57
{{total | thousands}}            -> 1,234.57
{{rate | percent: 1}}            -> 12.3%
{{total | round: 2 | thousands}} -> 1,234.57
```

`round` rounds half away from zero. `fixed` and `percent` return text with the
requested number of decimal places. `thousands` takes an optional separator,
as in `{{total | thousands: " "}}`. It does not round, so chain `round` before
`thousands` when the output should be rounded.

#### Dates and time zones

The `dates` feature adds `date` and `timezone`. It is on by default.

```
{{created_at | date: "%Y-%m-%d"}}
{{created_at | date: "%d %B %Y at %H:%M"}}
{{created_at | timezone: "Europe/Paris" | date: "%H:%M"}}
```

`date` accepts an ISO 8601 date or date and time, an instant with an offset,
or a number of epoch seconds. It uses `strftime` patterns such as `%Y`, `%m`,
`%d`, `%H`, `%M`, `%S`, `%B` and `%A`. A value without an offset is formatted
as written, a value with an offset is formatted in that offset, and epoch
seconds are read in UTC.

`timezone` converts an instant to a named IANA zone and returns an ISO 8601
value that `date` can format. The name may be any IANA zone such as
`America/New_York`, or `local` for the system zone. A value with an offset is
converted to the target zone. A value without an offset keeps its clock time
and takes the target zone, so a local appointment reads the same before and
after.

Turn the date filters off to drop the dependency:

```toml
docx-templating = { version = "1.0.0", default-features = false }
```

Filters also work in conditions and loop iterables:

```
{% if items | len %}We have items.{% endif %}
{% for tag in tags | default: "none" %}{{tag | upper}}{% endfor %}
```

A missing path becomes null, so `default` can supply a fallback. Without a
filter, a missing path still follows the missing value policy.

Register or replace a filter on the options. The closure receives the current
value and the optional argument:

```rust
use docx_templating::{FilterError, Template, TemplateOptions};
use serde_json::Value;

let options = TemplateOptions::default().filter("shout", |value, _| {
    let text = value
        .as_str()
        .ok_or_else(|| FilterError::new("value is not a string"))?;
    Ok(Value::String(format!("{}!", text.to_uppercase())))
});

let output = Template::from_path("template.docx")?
    .with_options(options)
    .render(&data)?;
```

An unknown filter reports `RenderError::UnknownFilter`, and a filter that rejects
its value reports `RenderError::FilterFailed` with the reason. Both name the
filter and the DOCX part.

### Conditionals

Block tags are removed from the output; only the chosen branch content remains.

**Inline** (tag and content in the same paragraph):

```
{% if user.active %}Welcome back, {{user.name}}!{% endif %}
{% if user.vip %}VIP benefits apply.{% else %}Standard access.{% endif %}
{% if not user.active %}Your account is inactive.{% endif %}
```

**Multi-paragraph** (each tag on its own line, as Word naturally produces):

```
{% if user.active %}

Welcome back, {{user.name}}!

{% endif %}
```

When the condition is true, the tag paragraphs are removed and the body paragraph is kept with variables substituted. When false, all paragraphs in the block are removed - no empty lines are left behind.

#### Else if chains

`{% elif %}` adds more branches, tried in order until one is true. When none
match, the `{% else %}` branch runs, if there is one:

```
{% if status == "open" %}Open
{% elif status == "pending" %}Pending
{% elif status == "closed" %}Closed
{% else %}Unknown{% endif %}
```

```
{% if total > 100 %}


Large order

{% elif total > 10 %}

Medium order

{% else %}

Small order

{% endif %}
```

The same rules as `if` apply: inline chains live in one paragraph, chains that
span paragraphs or table rows remove every unused tag and branch, and every
condition can combine comparisons, boolean logic and arithmetic. Conditions are
evaluated from top to bottom and evaluation stops at the first true one, so a
later branch that would fail on its own never runs. An `{% elif %}` without an
open `if`, or an `{% elif %}` after `{% else %}`, is rejected when the template
loads.

#### Comparisons and boolean logic

A condition can compare values and combine the results:

```
{% if total > 100 %}Approval required.{% endif %}
{% if status == "paid" %}Receipt attached.{% endif %}
{% if status != "cancelled" %}Active order.{% endif %}
{% if quantity <= 0 %}Out of stock.{% endif %}
{% if active and verified %}Account ready.{% endif %}
{% if draft or revised %}Needs review.{% endif %}
{% if not (draft or revised) %}Final.{% endif %}
```

The operands can be paths, literals, filtered values or parenthesized expressions, so `{% if items | len > 0 %}` and `{% if (total > limit and paid) or approved %}` both work. Equality compares any two values and treats `10` and `10.0` as equal. Ordering works for two numbers or two strings; mixing them reports `RenderError::InvalidComparison` with both types. `not` binds tighter than `and`, and `and` binds tighter than `or`. `and` and `or` short circuit, so the side that cannot change the result is not evaluated.

Comparisons belong in a condition. Using one as text or as a loop iterable reports `RenderError::ExpressionNotSupported` with a hint.

#### Arithmetic

Placeholders and conditions can do arithmetic with `+`, `-`, `*`, `/` and `%`:

```
{{price * quantity}}
{{subtotal - discount}}
{{(price + tax) * quantity | fixed: 2}}
{% if price * quantity > 100 %}Approval required.{% endif %}
```

`*`, `/` and `%` bind tighter than `+` and `-`, and parentheses override
either. A leading minus negates a value, as in `{{-balance}}`. Integer results
stay integers and keep full precision, so `{{2 * 3}}` writes `6` and
`{{10 / 4}}` writes `2.5`.

Arithmetic works on numbers only. A string, boolean, array, object or missing
value reports `RenderError::ArithmeticType`, and division or remainder by zero
reports `RenderError::DivisionByZero`.

A filter after an arithmetic expression applies to the whole result, so
`{{price * quantity | fixed: 2}}` formats the product. To format one operand,
group it first: `{{(price | round: 2) * quantity}}`.

### Loops

#### Paragraph loops

Iterate over an array. Tag paragraphs are removed; the body paragraph is duplicated once per element.

**Object array:**

```
{% for item in items %}

{{item.name}} — qty {{item.qty}}

{% endfor %}
```

**Primitive array** (the loop variable and `{{.}}` both refer to the element):

```
{% for tag in tags %}

{{.}}

{% endfor %}
```

An empty or missing array removes all loop paragraphs without error. A non-array value returns `RenderError::ExpectedIterable`.

#### Table-row loops

Place `{% for %}` and `{% endfor %}` inside a table to duplicate rows instead of paragraphs.

**Multi-row range** — each marker in its own row, body rows between them:

```
| {% for item in items %} |         |
| {{item.sku}}            | {{item.qty}} |
| {% endfor %}            |         |
```

Renders to one data row per element; tag rows are removed.

**Same-row** — all markers inside a single row:

```
| {% for item in items %} {{item.sku}} {% endfor %} |
```

The whole row is cloned once per element; tag text is stripped from each copy.

**Conditional rows** — `{% if %}` whose block aligns with a complete row removes or keeps that row:

```
| {% if item.active %} |
| {{item.name}}        |
| {% endif %}          |
```

#### Loop metadata

Three values describe the current iteration. They work in text, in filters and in conditions.

| Tag | Value |
|---|---|
| `{{@index}}` | Zero based position of the item |
| `{{@first}}` | `true` on the first item |
| `{{@last}}` | `true` on the last item |

```
{% for item in items %}
{{@index + 1}}. {{item.name}}{% if not @last %},{% endif %}
{% endfor %}
```

Details:

- `@index` is zero based, so add one for the numbering people expect.
- In nested loops `@index` refers to the innermost loop. The outer index cannot be read.
- Outside a loop a metadata tag reports `RenderError::MetaOutsideLoop` with the name.
- An unknown name such as `@count` reports a render error that names it.

#### The current item

`{{.}}` always means the current item, whatever the loop variable is called. The loop variable works too, so with `{"tags": ["a", "b"]}` both forms render the same text:

```
{% for tag in tags %}
{{tag}} and {{.}}
{% endfor %}
```

Use `{{.}}` for a primitive array, because it survives renaming the loop variable and matches the Mustache and Docxtemplater form. Use the name when the item is an object, since `{{item.name}}` reaches a field and `{{.}}` cannot. Rendering an object directly reports `RenderError::CannotConvertToText` with the value type `object`.

### Missing Value Policy

Control what happens when a variable path is not found in the context:

```rust
use docx_templating::{Template, TemplateOptions, MissingValuePolicy};

let template = Template::from_path("template.docx")?
    .with_options(
        TemplateOptions::default()
            .missing_value_policy(MissingValuePolicy::Empty)
            // also: MissingValuePolicy::Error (default), MissingValuePolicy::KeepPlaceholder
    );
```

### Line Break Policy

Control how `\n` (or `\r\n`) characters in a resolved variable value are rendered. DOCX ignores literal newlines inside `<w:t>` elements, so the library converts them:

```rust
use docx_templating::{Template, TemplateOptions, LineBreakPolicy};

// InsertWordBreak (default): emits <w:br w:type="textWrapping"/> between segments,
// keeping everything in the same paragraph.
let template = Template::from_path("template.docx")?
    .with_options(
        TemplateOptions::default()
            .line_break_policy(LineBreakPolicy::InsertWordBreak)
    );

// SplitParagraph: splits the containing <w:p> into N separate paragraphs,
// each inheriting the original paragraph and run formatting.
let template = Template::from_path("template.docx")?
    .with_options(
        TemplateOptions::default()
            .line_break_policy(LineBreakPolicy::SplitParagraph)
    );
```

Both policies can be combined with `MissingValuePolicy`:

```rust
use docx_templating::{TemplateOptions, MissingValuePolicy, LineBreakPolicy};

let options = TemplateOptions::default()
    .missing_value_policy(MissingValuePolicy::Empty)
    .line_break_policy(LineBreakPolicy::SplitParagraph);
```

### Whitespace Preservation

By default the library emits `xml:space="preserve"` on any `<w:t>` element whose replacement value has leading or trailing spaces, preventing Word from silently stripping them. Set `preserve_whitespace(false)` to suppress this attribute and let Word apply its own normalisation:

```rust
use docx_templating::{Template, TemplateOptions};

// Default: preserve edge whitespace in replacement values
let template = Template::from_path("template.docx")?
    .with_options(TemplateOptions::default()); // preserve_whitespace defaults to true

// Opt out: let Word normalise whitespace
let template = Template::from_path("template.docx")?
    .with_options(
        TemplateOptions::default()
            .preserve_whitespace(false)
    );
```

### Headers, Footers and Notes

The main document is always templated. Headers, footers, footnotes and endnotes are copied through unchanged until an option turns them on:

```rust
use docx_templating::{Template, TemplateOptions};

// Template headers and footers as well as the body
let template = Template::from_path("template.docx")?
    .with_options(TemplateOptions::default().headers_and_footers(true));

// Template footnote and endnote parts
let template = Template::from_path("template.docx")?
    .with_options(TemplateOptions::default().footnotes(true));
```

Both options can be combined. Every enabled part takes the same syntax as the body, including loops, conditionals and split placeholders:

```rust
let template = Template::from_path("template.docx")?
    .with_options(
        TemplateOptions::default()
            .headers_and_footers(true)
            .footnotes(true)
    );
```

A part that stays disabled is never parsed, so a placeholder looking sequence in it cannot fail the load or the render. An error inside an enabled part names that part, for example `word/header1.xml`, and `Template::diagnostic` points at the paragraph in it.

### Error Diagnostics

An error can be printed as a compiler style message with a caret under the template text that caused it:

```rust
use docx_templating::{Template, diagnose};

let bytes = std::fs::read("broken.docx")?;

if let Err(error) = Template::from_bytes(bytes.clone()) {
    eprintln!("{}", diagnose(&bytes, &error));
}
```

```
error: unclosed block in word/document.xml at 6..29
  --> word/document.xml:2:1
  |
2 | {% for item in items %}
  | ^^^^^^^^^^^^^^^^^^^^^^^ this block is never closed
  |
  = help: add the matching closing tag before the enclosing block ends
```

A template that loaded but failed to render is diagnosed with `Template::diagnostic`, which adds a help line naming the next step, such as the path that the context is missing.

## How It Works

A render runs four steps:

1. **Load** - read the ZIP package, validate the required parts, and read `word/document.xml`.
2. **Bind** - parse the part into a lossless tree, project runs into logical text, and bind template tags to positions. Unsupported placements fail here with `BindingError`.
3. **Evaluate** - resolve every tag against the context into a plan. Each loop iteration carries its own nested plan, already evaluated.
4. **Apply and write** - apply the plan to a copy of the tree, serialize the part, and write the package. Every other part is copied verbatim.

### Capabilities

- **Lossless tree:** markup the model does not type passes through byte for byte, so an untouched document round trips exactly.
- **Split placeholders:** `{{user.` and `name}}` in separate runs are stitched into one logical string.
- **Block placement:** inline ranges, whole paragraphs, and table rows are supported. Anything else fails with a typed error instead of producing broken XML.
- **Policies:** missing values (`Error`, `Empty`, `KeepPlaceholder`), line breaks (`InsertWordBreak`, `SplitParagraph`), and whitespace preservation.
- **Safe output:** all inserted text is escaped, and ZIP entry names are validated against path traversal.
- **Bounded reads:** a ZIP entry whose declared uncompressed size exceeds 100 MiB is rejected with `PackageError::EntrySizeExceeded`.

## Performance

Rendering is linear in the number of tags and blocks. There is no per tag or per iteration scan of the rest of the document, so a document with 10,000 placeholders costs about 10,000 times one tag.

Indicative timings from `benches/pipeline.rs`. Each row is one `cargo bench` iteration, and the render rows include writing the output package:

| Workload | Time | Throughput |
|---|---|---|
| Load, 10,000 placeholders | 50 ms | about 200k tags/s |
| Load, 10,000 paragraphs without tags | 32 ms | about 310k blocks/s |
| Render, 10,000 placeholders | 44 ms | about 230k tags/s |
| Render, 10,000 paragraphs without tags | 16 ms | about 625k blocks/s |
| Paragraph loop, 1,000 items | 9 ms | about 110k items/s |
| Table row loop, 1,000 items | 17 ms | about 60k items/s |

A tag costs roughly 4 microseconds end to end, and a table row loop costs about 17 microseconds per row because each row is cloned and stripped of its tags.

These numbers come from an Intel Core i5-10500H running Windows 11 with rustc 1.99.1, best of several runs while an editor and a language server were also running. Measurements on that kind of shared laptop move by tens of percent between runs, so treat the table as an order of magnitude and run the suite on an idle machine for your own baseline:

```bash
cargo bench
```

The suites assert that they rendered the expected number of blocks before they time anything, so a broken fixture fails the run instead of reporting a fast number. `tests/stress.rs` adds a correctness gate for the same shapes: 5,000 blocks, 50 nested loops, and a byte identical round trip of an untouched document.

## Architecture

The crate is one library with a pure core:

1. **Domain** - the lossless document tree, template binding, placement rules, the resolved plan, and the evaluator. It never touches XML, ZIP, or the filesystem.
2. **Adapters** - parse WordprocessingML into the tree and serialize it back, and read and write the DOCX package.
3. **Public API** - `Template`, `Context`, `IntoContext`, `RenderedDocument`, options, and errors.

`tests/architecture.rs` fails the build if the domain reaches for an adapter, `quick_xml`, `zip`, the filesystem, or IO.

### Module Structure

```
src/
├── lib.rs                 # Public re-exports and crate docs
├── error.rs               # Error, XmlError
├── options.rs             # TemplateOptions, MissingValuePolicy, LineBreakPolicy
├── rendered.rs            # RenderedDocument
├── template.rs            # Template<S>, constructors, render, free render()
├── context.rs             # Context, IntoContext
├── domain/                # Pure model, no IO
│   ├── document/          # Lossless tree, roles, text projection
│   ├── template/          # Template syntax model
│   ├── binding/           # Bind tags to positions, placement errors
│   ├── placement/         # Classify block placement
│   ├── plan/              # Plan, Edit, overlap check, apply
│   └── engine/            # Evaluate a bound template into a plan
├── adapters/              # Format and storage adapters
│   ├── docx/              # Parse and serialize WordprocessingML
│   └── package/           # Package adapter
├── syntax/                # Template syntax parser (crate private)
│   ├── ast.rs
│   ├── span.rs
│   └── parser.rs
├── package/               # ZIP/OPC handling
│   ├── source.rs          # PackageSource trait
│   ├── writer.rs          # PackageWriter trait
│   ├── zip_source.rs      # ZipPackageSource
│   ├── zip_writer.rs      # ZipPackageWriter
│   ├── memory_source.rs   # InMemoryPackageSource
│   └── validation.rs      # Path traversal guards
├── docx/                  # Part names and structural validation
│   ├── parts.rs
│   └── validate.rs
└── api/                   # Public surface marker
```

## Development

### Prerequisites

Rust 1.89 or later. The crate uses the 2024 edition.

### Building

```bash
cargo build
```

### Running Tests

```bash
cargo test --all-features
```

### Benchmarks

```bash
cargo bench
```

Criterion writes its report to `target/criterion`. The suite has three groups: `load` for parsing and binding, `render` for evaluation plus the package write, and `loop` for paragraph and table row duplication. The current numbers are in [Performance](#performance).

### Repository Tasks

Two generators write the files that the tests and the examples read. They live in the private `xtask` package, which is not published, so the crate that reaches crates.io has no binaries:

```bash
cargo xtask gen-fixtures   # writes tests/fixtures/
cargo xtask gen-examples   # writes examples/input/
```

Both write relative to the working directory, so run them from the repository root. The generated files are committed, so a fresh clone does not need to run either one.

### Quality Checks

```bash
cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo doc --no-deps
```

## Documentation

- **[SPECIFICATION.md](SPECIFICATION.md)** — Complete product specification with user stories and business rules
- **[CHANGELOG.md](CHANGELOG.md)** — Version history

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.