quilldown 1.5.0

Convert GitHub-Flavored Markdown into high-fidelity Word .docx documents.
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
//! The **emit** operation: portable [`Document`] IR → a `docx-rs` [`Docx`] builder.
//!
//! This is the compiler back-end for the IR path. It consumes the backend-neutral
//! [`crate::ir::model`] shapes and lowers them to native OOXML constructs, reusing the same
//! [`crate::styles`] primitives (page setup, numbering, spacing) as the direct renderer so the
//! two paths produce the same *kinds* of native Word objects (heading styles, `<w:hyperlink>` +
//! relationship, anchor bookmarks, list numbering, GFM tables, monospace code).
//!
//! # SHAPES vs OPERATIONS
//!
//! [`crate::ir::model`] defines the SHAPES (what a document *is*); this module defines the
//! OPERATIONS (what an emitter *does*). The operations are deliberately split into small,
//! individually testable pieces — [`emit_block`], [`emit_inlines`], [`emit_table`],
//! [`emit_list`] — so conformance can assert at three levels (see ADR-0001):
//!
//! * **node** — one shape emits the right native object (a heading emits a styled bookmarked
//!   paragraph);
//! * **composition** — nested shapes fold correctly (a link inside emphasis inside a list item);
//! * **invariant** — the non-local relational rules hold (every referenced numbering id is
//!   registered; every anchor target has a matching heading bookmark). [`EmitState`] is the
//!   "symbol table" that makes those invariants well-defined.
//!
//! Only the Core tier plus portable field-based options are emitted. Math and images reach this
//! path as first-class IR nodes but are rendered as text fallbacks; native OMML and embedded
//! image/SVG layers stay on the reference renderer's byte path.

use std::collections::HashMap;

use docx_rs::*;

use crate::ir::model::{AlertType, Align, Block, Document, Inline, List, Table as IrTable};
use crate::render::{captions, slugify};
use crate::styles;
use crate::{ConvertError, ConvertOptions, Theme};

/// Accumulated inline run style, threaded through [`emit_inlines`] as nested emphasis/strong/
/// strikethrough shapes are folded into flat styled runs.
#[derive(Clone, Copy, Default)]
struct Style {
    bold: bool,
    italic: bool,
    strike: bool,
    quote: bool,
    subscript: bool,
}

impl Style {
    fn for_depth(depth: usize) -> Self {
        Style {
            quote: depth > 0,
            ..Style::default()
        }
    }

    /// Apply the accumulated flags to a fresh run (text is added by the caller).
    fn apply(self, mut r: Run) -> Run {
        if self.bold {
            r = r.bold();
        }
        if self.italic {
            r = r.italic();
        }
        if self.strike {
            r = r.strike();
        }
        if self.quote {
            r = r.color(styles::QUOTE_TEXT_COLOR);
        }
        if self.subscript {
            r.run_property = r.run_property.vert_align(VertAlignType::SubScript);
        }
        r
    }
}

/// The emitter's mutable **symbol table**: the allocation state that makes the non-local OOXML
/// features well-defined. Bookmarks, list numbering ids, and unique heading slugs are all
/// document-global namespaces, so they cannot be decided by a single node in isolation — they
/// are exactly the state a compiler back-end threads to keep cross-references consistent.
struct EmitState {
    /// Next unused Word bookmark id (bookmarks pair a start/end by id).
    next_bookmark_id: usize,
    /// Next unused numbering id for an ordered list (each ordered list gets its own so counters
    /// restart at the list's `start`).
    next_num_id: usize,
    /// Per-base-slug occurrence counter, so repeated heading text yields `slug`, `slug-1`, ....
    heading_slugs: HashMap<String, usize>,
    /// Ordered-list numbering definitions to register on the [`Docx`] before any paragraph
    /// references them (the "declare before use" invariant).
    numberings: Vec<Numbering>,
    /// Raw caption label -> unique Word bookmark name, collected before emission so forward
    /// `[text](#label)` references can become live `REF` fields.
    caption_labels: HashMap<String, String>,
}

impl EmitState {
    fn new() -> Self {
        EmitState {
            next_bookmark_id: 1,
            next_num_id: styles::FIRST_LIST_NUM_ID,
            heading_slugs: HashMap::new(),
            numberings: Vec::new(),
            caption_labels: HashMap::new(),
        }
    }

    /// Allocate a fresh bookmark id.
    fn bookmark_id(&mut self) -> usize {
        let id = self.next_bookmark_id;
        self.next_bookmark_id += 1;
        id
    }

    /// Allocate a GitHub-style heading slug, de-duplicating repeats exactly as the direct
    /// renderer does so `#anchor` links resolve identically across the two paths.
    fn heading_slug(&mut self, text: &str) -> String {
        let base = slugify(text);
        let count = self.heading_slugs.entry(base.clone()).or_insert(0);
        let slug = if *count == 0 {
            base.clone()
        } else {
            format!("{base}-{count}")
        };
        *count += 1;
        slug
    }

    /// Allocate and register a numbering definition for one ordered list, returning its id.
    fn ordered_num_id(&mut self, level: usize, start: u32) -> usize {
        let id = self.next_num_id;
        self.next_num_id += 1;
        self.numberings
            .push(styles::ordered_numbering(id, level, start as usize));
        id
    }
}

/// One emitted top-level flow object. Boxed so the enum stays small (the two `docx-rs` builders
/// differ greatly in size).
enum Flow {
    /// Plain body paragraph, tracked separately so a following block can zero its default
    /// space-after before the explicit spacer paragraph, matching the direct renderer.
    Body(Box<Paragraph>),
    Para(Box<Paragraph>),
    Table(Box<Table>),
    Gap,
}

fn push_gap(flows: &mut Vec<Flow>) {
    match flows.last() {
        None | Some(Flow::Gap) => return,
        Some(Flow::Body(_)) => {
            if let Some(Flow::Body(p)) = flows.pop() {
                flows.push(Flow::Body(Box::new(p.line_spacing(styles::tight_after()))));
            }
        }
        _ => {}
    }
    flows.push(Flow::Gap);
}

fn collect_caption_labels(blocks: &[Block], state: &mut EmitState) {
    for block in blocks {
        let Block::Paragraph { content } = block else {
            continue;
        };
        let Some(cap) = captions::caption_of(&caption_text(content)) else {
            continue;
        };
        let Some(label) = cap.label else {
            continue;
        };
        if state.caption_labels.contains_key(&label) {
            continue;
        }
        let base = captions::bookmark_name(&label);
        let name = if !state.caption_labels.values().any(|used| used == &base) {
            base
        } else {
            (2..)
                .map(|n| format!("{base}_{n}"))
                .find(|candidate| !state.caption_labels.values().any(|used| used == candidate))
                .expect("suffix search always terminates")
        };
        state.caption_labels.insert(label, name);
    }
}

fn emit_caption(cap: &captions::Caption, state: &mut EmitState) -> Paragraph {
    let word = match cap.kind {
        captions::Kind::Figure => "Figure",
        captions::Kind::Table => "Table",
    };
    let mut p = Paragraph::new().style("Caption");
    let bookmark = cap
        .label
        .as_ref()
        .and_then(|label| state.caption_labels.get(label).cloned())
        .map(|name| (state.bookmark_id(), name));
    if let Some((id, name)) = &bookmark {
        p = p.add_bookmark_start(*id, name.clone());
    }
    p = p
        .add_run(Run::new().bold().add_text(format!("{word} ")))
        .add_run(seq_field(word));
    if let Some((id, _)) = bookmark {
        p = p.add_bookmark_end(id);
    }
    p = p.add_run(Run::new().bold().add_text(": "));
    if !cap.text.is_empty() {
        p = p.add_run(Run::new().add_text(&cap.text));
    }
    p
}

fn seq_field(kind: &str) -> Run {
    Run::new()
        .bold()
        .add_field_char(FieldCharType::Begin, true)
        .add_instr_text(InstrText::Unsupported(format!("SEQ {kind} \\* ARABIC")))
        .add_field_char(FieldCharType::Separate, false)
        .add_text("1")
        .add_field_char(FieldCharType::End, false)
}

fn ref_field(name: &str, placeholder: &str) -> Run {
    Run::new()
        .add_field_char(FieldCharType::Begin, true)
        .add_instr_text(InstrText::Unsupported(format!("REF {name} \\h")))
        .add_field_char(FieldCharType::Separate, false)
        .add_text(placeholder)
        .add_field_char(FieldCharType::End, false)
}

/// Emit a portable [`Document`] into a `docx-rs` [`Docx`] builder.
///
/// The result is a builder (not packed bytes); callers serialize it with
/// `docx.build().pack(..)`. Errors are reserved for future legalization failures — Core emission
/// is total, so this currently always returns `Ok`, but the fallible signature keeps the
/// operation symmetric with the direct renderer and forward-compatible.
///
/// Supported [`ConvertOptions`] are intentionally narrower than the direct renderer: page setup,
/// theme, `page_numbers`, `table_of_contents`, `captions`, and `highlight_code` (currently only
/// the no-highlight/plain-code shape). Images, endnotes, native math, and semantic
/// table-header-row injection remain direct-renderer/post-pack features.
pub fn emit(doc: &Document, opts: &ConvertOptions) -> Result<Docx, ConvertError> {
    let mut state = EmitState::new();
    if opts.captions {
        collect_caption_labels(&doc.blocks, &mut state);
    }
    let mut flows = Vec::new();
    emit_blocks(&doc.blocks, opts, 0, &mut state, &mut flows);
    if matches!(flows.first(), Some(Flow::Gap)) {
        flows.remove(0);
    }
    if matches!(flows.last(), Some(Flow::Gap)) {
        flows.pop();
    }

    let mut docx = styles::apply(Docx::new(), &opts.page, &opts.theme);
    if opts.page_numbers {
        docx = docx.footer(page_number_footer());
    }
    // Invariant: register every numbering *before* the paragraphs that reference it.
    for numbering in std::mem::take(&mut state.numberings) {
        docx = docx.add_numbering(numbering);
    }
    if opts.table_of_contents {
        docx = docx.add_paragraph(table_of_contents_title());
        docx = docx.add_table_of_contents(
            TableOfContents::new()
                .heading_styles_range(1, 3)
                .hyperlink()
                .dirty(),
        );
        docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
    }
    for flow in flows {
        docx = match flow {
            Flow::Body(p) => docx.add_paragraph(*p),
            Flow::Para(p) => docx.add_paragraph(*p),
            Flow::Table(t) => docx.add_table(*t),
            Flow::Gap => docx.add_paragraph(styles::block_gap_paragraph()),
        };
    }
    Ok(docx)
}

fn page_number_footer() -> Footer {
    let para = Paragraph::new()
        .align(AlignmentType::Center)
        .line_spacing(styles::tight_after())
        .add_run(Run::new().add_text("Page "))
        .add_page_num(PageNum::new())
        .add_run(Run::new().add_text(" of "))
        .add_num_pages(NumPages::new());
    Footer::new().add_paragraph(para)
}

fn table_of_contents_title() -> Paragraph {
    Paragraph::new()
        .line_spacing(styles::body_spacing())
        .add_run(Run::new().bold().size(28).add_text("Contents"))
}

/// Emit a sequence of blocks at block-quote nesting `depth`.
fn emit_blocks(
    blocks: &[Block],
    opts: &ConvertOptions,
    depth: usize,
    state: &mut EmitState,
    flows: &mut Vec<Flow>,
) {
    for block in blocks {
        emit_block(block, opts, depth, state, flows);
    }
}

/// Emit a single block (node-level operation).
fn emit_block(
    block: &Block,
    opts: &ConvertOptions,
    depth: usize,
    state: &mut EmitState,
    flows: &mut Vec<Flow>,
) {
    let theme = &opts.theme;
    match block {
        Block::Heading { level, content } => {
            // Bookmark the heading with its GitHub slug so `#slug` anchors can jump to it — this
            // is the target half of the anchor/bookmark invariant.
            let slug = state.heading_slug(&inline_text(content));
            let bid = state.bookmark_id();
            let mut p = Paragraph::new()
                .style(heading_style_id(*level))
                .keep_next(true)
                .keep_lines(true)
                .add_bookmark_start(bid, slug);
            p = emit_inlines(p, content, Style::for_depth(depth), theme, state);
            p = p.add_bookmark_end(bid);
            if depth > 0 {
                p = quote_style(p, depth);
            }
            flows.push(Flow::Para(Box::new(p)));
        }
        Block::Paragraph { content } => {
            if opts.captions && depth == 0 {
                if let Some(cap) = captions::caption_of(&caption_text(content)) {
                    flows.push(Flow::Para(Box::new(emit_caption(&cap, state))));
                    return;
                }
            }
            let mut p = Paragraph::new();
            p = emit_inlines(p, content, Style::for_depth(depth), theme, state);
            if depth > 0 {
                flows.push(Flow::Para(Box::new(quote_style(p, depth))));
            } else {
                flows.push(Flow::Body(Box::new(p)));
            }
        }
        Block::CodeBlock { code, .. } => {
            push_gap(flows);
            let mut t = emit_code_block(code, opts);
            if depth > 0 {
                t = t.indent(quote_indent(depth));
            }
            flows.push(Flow::Table(Box::new(t)));
            push_gap(flows);
        }
        Block::BlockQuote { blocks } => {
            let top_level = depth == 0;
            if top_level {
                push_gap(flows);
            }
            emit_blocks(blocks, opts, depth + 1, state, flows);
            if top_level {
                push_gap(flows);
            }
        }
        Block::Alert {
            alert_type,
            title,
            blocks,
        } => {
            push_gap(flows);
            flows.push(Flow::Table(Box::new(emit_alert(
                *alert_type,
                title.as_deref(),
                blocks,
                opts,
                state,
            ))));
            push_gap(flows);
        }
        Block::List(list) => emit_list(list, opts, depth, 0, state, flows),
        Block::Table(table) => {
            push_gap(flows);
            let mut t = emit_table(table, opts, depth, state);
            if depth > 0 {
                t = t.indent(quote_indent(depth));
            }
            flows.push(Flow::Table(Box::new(t)));
            push_gap(flows);
        }
        Block::ThematicBreak => {
            push_gap(flows);
            flows.push(Flow::Table(Box::new(horizontal_rule(
                opts.page.content_width_dxa(),
            ))));
            push_gap(flows);
        }
    }
}

/// Emit a list at markdown nesting `level` (0 = outermost). Ordered lists allocate their own
/// numbering; bullets share the globally-registered bullet numbering. Task items render a
/// checkbox glyph instead of a marker, matching the direct renderer.
fn emit_list(
    list: &List,
    opts: &ConvertOptions,
    depth: usize,
    level: usize,
    state: &mut EmitState,
    flows: &mut Vec<Flow>,
) {
    let level = level.min(8);
    let num_id = if list.ordered {
        state.ordered_num_id(level, list.start)
    } else {
        styles::BULLET_NUM_ID
    };
    let theme = &opts.theme;
    let continuation_indent = styles::LIST_INDENT_STEP_DXA * (level as i32 + 1);

    for item in &list.items {
        // Only the first paragraph of an item carries the marker; later blocks are continuation
        // text (indented, unmarked) so the item is numbered once, not once per paragraph.
        let mut marker_used = false;
        for block in &item.blocks {
            match block {
                Block::Paragraph { content } => {
                    let mut p = if marker_used {
                        Paragraph::new().line_spacing(styles::tight_after()).indent(
                            Some(continuation_indent),
                            None,
                            None,
                            None,
                        )
                    } else if let Some(checked) = item.task {
                        let glyph = if checked {
                            styles::TASK_CHECKED
                        } else {
                            styles::TASK_UNCHECKED
                        };
                        Paragraph::new()
                            .line_spacing(styles::tight_after())
                            .indent(
                                Some(continuation_indent),
                                Some(SpecialIndentType::Hanging(styles::LIST_HANGING_DXA)),
                                None,
                                None,
                            )
                            .add_run(Run::new().add_text(glyph).add_tab())
                    } else {
                        Paragraph::new()
                            .line_spacing(styles::tight_after())
                            .numbering(NumberingId::new(num_id), IndentLevel::new(level))
                    };
                    marker_used = true;
                    p = emit_inlines(p, content, Style::for_depth(depth), theme, state);
                    if depth > 0 {
                        p = quote_border(p);
                    }
                    flows.push(Flow::Para(Box::new(p)));
                }
                Block::List(sub) => emit_list(sub, opts, depth, level + 1, state, flows),
                other => emit_block(other, opts, depth, state, flows),
            }
        }
    }
}

/// Emit a fenced/indented code block as a shaded 1x1 table of monospace lines. This mirrors the
/// direct renderer's structure (native cell shading around monospace paragraphs); the
/// experimental path deliberately omits syntax highlighting, which is Enhanced tier.
fn emit_code_block(code: &str, opts: &ConvertOptions) -> Table {
    let theme = &opts.theme;
    let mut cell = TableCell::new().shading(Shading::new().fill(theme.code_fill));
    let trimmed = code.strip_suffix('\n').unwrap_or(code);
    for line in trimmed.split('\n') {
        cell = cell.add_paragraph(
            Paragraph::new()
                .line_spacing(styles::code_spacing())
                .add_run(mono_run(line, theme.mono_font)),
        );
    }
    Table::new(vec![TableRow::new(vec![cell])])
        .width(opts.page.content_width_dxa(), WidthType::Dxa)
        .margins(styles::code_cell_margins())
}

/// Emit a GitHub alert/callout as a shaded single-cell table with a left accent border.
fn emit_alert(
    alert_type: AlertType,
    title: Option<&str>,
    blocks: &[Block],
    opts: &ConvertOptions,
    state: &mut EmitState,
) -> Table {
    let (accent, fill) = alert_palette(alert_type);
    let label = title.unwrap_or_else(|| alert_type.default_title());
    let mut cell = TableCell::new()
        .shading(Shading::new().fill(fill))
        .add_paragraph(
            Paragraph::new().add_run(Run::new().bold().color(accent).add_text(label.to_string())),
        );
    let mut inner_flows = Vec::new();
    emit_blocks(blocks, opts, 0, state, &mut inner_flows);
    if matches!(inner_flows.first(), Some(Flow::Gap)) {
        inner_flows.remove(0);
    }
    if matches!(inner_flows.last(), Some(Flow::Gap)) {
        inner_flows.pop();
    }
    for flow in inner_flows {
        cell = match flow {
            Flow::Body(p) | Flow::Para(p) => cell.add_paragraph(*p),
            Flow::Table(t) => cell.add_table(*t),
            Flow::Gap => cell.add_paragraph(styles::block_gap_paragraph()),
        };
    }

    use TableBorderPosition::*;
    let left = TableBorder::new(Left)
        .border_type(BorderType::Single)
        .size(styles::ALERT_BORDER_SIZE)
        .color(accent);
    Table::new(vec![TableRow::new(vec![cell])])
        .width(opts.page.content_width_dxa(), WidthType::Dxa)
        .margins(styles::table_cell_margins())
        .set_borders(TableBorders::with_empty().set(left))
}

fn alert_palette(alert_type: AlertType) -> (&'static str, &'static str) {
    match alert_type {
        AlertType::Note => styles::ALERT_NOTE,
        AlertType::Tip => styles::ALERT_TIP,
        AlertType::Important => styles::ALERT_IMPORTANT,
        AlertType::Warning => styles::ALERT_WARNING,
        AlertType::Caution => styles::ALERT_CAUTION,
    }
}

/// Emit a GFM table: a bold, shaded header row plus body rows, with per-column alignment.
fn emit_table(table: &IrTable, opts: &ConvertOptions, depth: usize, state: &EmitState) -> Table {
    let theme = &opts.theme;
    let mut rows = Vec::new();
    if !table.head.is_empty() {
        rows.push(emit_table_row(
            &table.head,
            &table.align,
            true,
            theme,
            depth,
            state,
        ));
    }
    for row in &table.rows {
        rows.push(emit_table_row(
            row,
            &table.align,
            false,
            theme,
            depth,
            state,
        ));
    }
    Table::new(rows)
        .width(opts.page.content_width_dxa(), WidthType::Dxa)
        .set_borders(table_borders())
        .margins(styles::table_cell_margins())
}

/// Emit one table row. Header cells are bold and shaded; body cells inherit body style. GFM
/// cells are inline-only, so each cell is a single aligned paragraph of styled runs.
fn emit_table_row(
    cells: &[Vec<Inline>],
    align: &[Align],
    is_header: bool,
    theme: &Theme,
    depth: usize,
    state: &EmitState,
) -> TableRow {
    let mut tcs = Vec::new();
    for (col, cell) in cells.iter().enumerate() {
        let mut para = Paragraph::new().line_spacing(styles::tight_after());
        if let Some(a) = align.get(col).and_then(align_to_docx) {
            para = para.align(a);
        }
        let style = Style {
            bold: is_header,
            ..Style::for_depth(depth)
        };
        para = emit_inlines(para, cell, style, theme, state);
        let mut tc = TableCell::new().add_paragraph(para);
        if is_header {
            tc = tc.shading(Shading::new().fill(styles::TABLE_HEADER_FILL));
        }
        tcs.push(tc);
    }
    TableRow::new(tcs)
}

/// Emit a flat run of inline content into `p`, recursively folding style-bearing shapes into the
/// accumulated [`Style`] (composition-level operation). Links become native hyperlinks.
fn emit_inlines(
    mut p: Paragraph,
    content: &[Inline],
    style: Style,
    theme: &Theme,
    state: &EmitState,
) -> Paragraph {
    for inline in content {
        p = match inline {
            Inline::Text(t) => p.add_run(style.apply(Run::new()).add_text(t)),
            Inline::Strong(c) => emit_inlines(
                p,
                c,
                Style {
                    bold: true,
                    ..style
                },
                theme,
                state,
            ),
            Inline::Emphasis(c) => emit_inlines(
                p,
                c,
                Style {
                    italic: true,
                    ..style
                },
                theme,
                state,
            ),
            Inline::Strikethrough(c) => emit_inlines(
                p,
                c,
                Style {
                    strike: true,
                    ..style
                },
                theme,
                state,
            ),
            Inline::Subscript(c) => emit_inlines(
                p,
                c,
                Style {
                    subscript: true,
                    ..style
                },
                theme,
                state,
            ),
            Inline::Code(c) => p.add_run(mono_run(c, theme.mono_font)),
            Inline::Link { href, content } => {
                if let Some(label) = href.strip_prefix('#') {
                    if let Some(name) = state.caption_labels.get(label) {
                        let placeholder = caption_text(content);
                        let shown = if placeholder.is_empty() {
                            label
                        } else {
                            placeholder.as_str()
                        };
                        p.add_run(ref_field(name, shown))
                    } else {
                        p.add_hyperlink(build_link(href, content, style, theme))
                    }
                } else {
                    p.add_hyperlink(build_link(href, content, style, theme))
                }
            }
            // The Core emit path has no OMML/image embedding (that lives on the reference
            // engine's byte path); render the math source and image alt as plain runs so the
            // IR path stays lossless-to-text while carrying the structured node.
            Inline::Math { latex, .. } => p.add_run(
                Style {
                    quote: false,
                    ..style
                }
                .apply(Run::new())
                .add_text(latex),
            ),
            Inline::Image { alt, .. } => p.add_run(
                Style {
                    quote: false,
                    ..style
                }
                .apply(Run::new())
                .add_text(alt),
            ),
            Inline::FootnoteReference { label } => p.add_run(
                Style {
                    quote: false,
                    ..style
                }
                .apply(Run::new())
                .add_text(format!("[^{label}]")),
            ),
            Inline::SoftBreak => p.add_run(style.apply(Run::new()).add_text(" ")),
            Inline::HardBreak => p.add_run(Run::new().add_break(BreakType::TextWrapping)),
        };
    }
    p
}

/// Build a native hyperlink. `#`-prefixed hrefs are in-document anchors (to a heading bookmark);
/// everything else is external (docx-rs auto-registers the external relationship). Inner content
/// is flattened to blue, underlined runs since Word hyperlinks cannot nest.
fn build_link(href: &str, content: &[Inline], style: Style, theme: &Theme) -> Hyperlink {
    let mut link = if let Some(anchor) = href.strip_prefix('#') {
        Hyperlink::new(anchor, HyperlinkType::Anchor)
    } else {
        Hyperlink::new(href, HyperlinkType::External)
    };
    let mut runs = Vec::new();
    collect_runs(content, style, theme, &mut runs);
    for r in runs {
        link = link.add_run(r.color(theme.link_color).underline("single"));
    }
    link
}

/// Flatten inline content into styled runs (no hyperlinks). Used for hyperlink children, where a
/// nested link's text is spliced in as plain runs.
fn collect_runs(content: &[Inline], style: Style, theme: &Theme, out: &mut Vec<Run>) {
    for inline in content {
        match inline {
            Inline::Text(t) => out.push(style.apply(Run::new()).add_text(t)),
            Inline::Strong(c) => collect_runs(
                c,
                Style {
                    bold: true,
                    ..style
                },
                theme,
                out,
            ),
            Inline::Emphasis(c) => collect_runs(
                c,
                Style {
                    italic: true,
                    ..style
                },
                theme,
                out,
            ),
            Inline::Strikethrough(c) => collect_runs(
                c,
                Style {
                    strike: true,
                    ..style
                },
                theme,
                out,
            ),
            Inline::Subscript(c) => collect_runs(
                c,
                Style {
                    subscript: true,
                    ..style
                },
                theme,
                out,
            ),
            Inline::Code(c) => out.push(mono_run(c, theme.mono_font)),
            Inline::Link { content, .. } => collect_runs(content, style, theme, out),
            Inline::Math { latex, .. } => out.push(
                Style {
                    quote: false,
                    ..style
                }
                .apply(Run::new())
                .add_text(latex),
            ),
            Inline::Image { alt, .. } => out.push(
                Style {
                    quote: false,
                    ..style
                }
                .apply(Run::new())
                .add_text(alt),
            ),
            Inline::FootnoteReference { label } => out.push(
                Style {
                    quote: false,
                    ..style
                }
                .apply(Run::new())
                .add_text(format!("[^{label}]")),
            ),
            Inline::SoftBreak => out.push(style.apply(Run::new()).add_text(" ")),
            Inline::HardBreak => out.push(Run::new().add_break(BreakType::TextWrapping)),
        }
    }
}

/// Concatenate the visible text of an inline run (used to derive a heading's slug).
fn inline_text(content: &[Inline]) -> String {
    let mut s = String::new();
    for inline in content {
        match inline {
            Inline::Text(t) | Inline::Code(t) => s.push_str(t),
            Inline::Strong(c)
            | Inline::Emphasis(c)
            | Inline::Strikethrough(c)
            | Inline::Subscript(c) => s.push_str(&inline_text(c)),
            Inline::Link { content, .. } => s.push_str(&inline_text(content)),
            Inline::Math { latex, .. } => s.push_str(latex),
            Inline::Image { alt, .. } => s.push_str(alt),
            Inline::FootnoteReference { label } => {
                s.push_str("[^");
                s.push_str(label);
                s.push(']');
            }
            Inline::SoftBreak => s.push(' '),
            Inline::HardBreak => {}
        }
    }
    s
}

/// Text extraction for caption detection and caption REF placeholders. This deliberately mirrors
/// the direct renderer's `text_of` helper: literal text descendants and image alt text
/// contribute. Code, math, footnote references, and explicit breaks do not.
fn caption_text(content: &[Inline]) -> String {
    let mut s = String::new();
    for inline in content {
        match inline {
            Inline::Text(t) => s.push_str(t),
            Inline::Strong(c)
            | Inline::Emphasis(c)
            | Inline::Strikethrough(c)
            | Inline::Subscript(c) => s.push_str(&caption_text(c)),
            Inline::Link { content, .. } => s.push_str(&caption_text(content)),
            Inline::Image { alt, .. } => s.push_str(alt),
            Inline::Code(_)
            | Inline::Math { .. }
            | Inline::FootnoteReference { .. }
            | Inline::SoftBreak
            | Inline::HardBreak => {}
        }
    }
    s
}

/// A monospace run for inline code and code-block lines (mirrors the direct renderer).
fn mono_run(text: &str, mono_font: &str) -> Run {
    Run::new()
        .fonts(RunFonts::new().ascii(mono_font).hi_ansi(mono_font))
        .size(styles::CODE_SIZE)
        .add_text(text)
}

fn quote_style(p: Paragraph, depth: usize) -> Paragraph {
    quote_border(p.indent(Some(quote_indent(depth)), None, None, None))
}

fn quote_border(mut p: Paragraph) -> Paragraph {
    let border = ParagraphBorder::new(ParagraphBorderPosition::Left)
        .size(styles::QUOTE_BORDER_SIZE)
        .space(styles::QUOTE_BORDER_SPACE)
        .color(styles::QUOTE_BORDER_COLOR);
    p.property = p
        .property
        .set_borders(ParagraphBorders::with_empty().set(border));
    p
}

fn quote_indent(depth: usize) -> i32 {
    styles::QUOTE_INDENT_DXA * depth as i32
}

/// Light single-line borders on every edge and gridline, matching the direct renderer's tables.
fn table_borders() -> TableBorders {
    use TableBorderPosition::*;
    let border = |p| {
        TableBorder::new(p)
            .border_type(BorderType::Single)
            .size(2)
            .color(styles::TABLE_BORDER_COLOR)
    };
    TableBorders::new()
        .set(border(Top))
        .set(border(Left))
        .set(border(Bottom))
        .set(border(Right))
        .set(border(InsideH))
        .set(border(InsideV))
}

/// A full-width horizontal rule: a borderless 1x1 table whose only visible edge is a thin bottom
/// border (the same trick the direct renderer uses, since docx-rs has no paragraph-border API).
fn horizontal_rule(content_width_dxa: usize) -> Table {
    use TableBorderPosition::*;
    let bottom = TableBorder::new(Bottom)
        .border_type(BorderType::Single)
        .size(4)
        .color(styles::TABLE_BORDER_COLOR);
    let borders = TableBorders::with_empty().set(bottom);
    let cell = TableCell::new().add_paragraph(Paragraph::new());
    Table::new(vec![TableRow::new(vec![cell])])
        .width(content_width_dxa, WidthType::Dxa)
        .set_borders(borders)
}

/// Map a heading level (1–6) to its Word style id, clamping deeper levels to `Heading6`.
fn heading_style_id(level: u8) -> &'static str {
    match level {
        1 => "Heading1",
        2 => "Heading2",
        3 => "Heading3",
        4 => "Heading4",
        5 => "Heading5",
        _ => "Heading6",
    }
}

/// Map an IR column alignment to a Word paragraph alignment. `None` keeps the default left flow
/// without emitting a redundant `<w:jc>`.
fn align_to_docx(a: &Align) -> Option<AlignmentType> {
    match a {
        Align::Left => Some(AlignmentType::Left),
        Align::Center => Some(AlignmentType::Center),
        Align::Right => Some(AlignmentType::Right),
        Align::None => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::lower::lower;
    use std::io::Cursor;

    /// Pack an emitted document to `.docx` bytes and return `word/document.xml`.
    fn document_xml(doc: &Document) -> String {
        let docx = emit(doc, &ConvertOptions::default()).expect("emit should succeed");
        let mut buf = Cursor::new(Vec::new());
        docx.build().pack(&mut buf).expect("pack should succeed");
        let mut archive = zip::ZipArchive::new(Cursor::new(buf.into_inner())).expect("valid zip");
        let mut s = String::new();
        std::io::Read::read_to_string(
            &mut archive.by_name("word/document.xml").expect("document.xml"),
            &mut s,
        )
        .expect("utf8");
        s
    }

    // --- NODE-level operations: one shape emits the right native object ------------------------

    #[test]
    fn heading_emits_style_and_bookmark() {
        let xml = document_xml(&lower("# Hello World\n"));
        assert!(
            xml.contains("Heading1"),
            "heading must use the Heading1 style"
        );
        assert!(
            xml.contains("w:bookmarkStart") && xml.contains("hello-world"),
            "heading must be bookmarked with its GitHub slug"
        );
    }

    #[test]
    fn external_link_emits_native_hyperlink() {
        let doc = lower("[docs](https://example.com)\n");
        let xml = document_xml(&doc);
        assert!(
            xml.contains("w:hyperlink"),
            "link must be a native hyperlink"
        );
        // docx-rs materializes the external target as a relationship id on the hyperlink.
        assert!(
            xml.contains("r:id"),
            "external hyperlink must reference a relationship"
        );
    }

    #[test]
    fn anchor_link_emits_bookmark_reference() {
        let doc = lower("# Title\n\n[jump](#title)\n");
        let xml = document_xml(&doc);
        assert!(
            xml.contains("w:anchor=\"title\""),
            "in-document link must target the heading anchor"
        );
    }

    #[test]
    fn ordered_list_emits_numbering() {
        let doc = lower("1. one\n2. two\n");
        let xml = document_xml(&doc);
        assert!(
            xml.contains("w:numPr"),
            "ordered list items must carry numbering"
        );
    }

    // --- COMPOSITION-level operations: nested shapes fold correctly ----------------------------

    #[test]
    fn nested_emphasis_and_link_compose() {
        // A link inside strong inside a paragraph: the hyperlink survives and its text is bold.
        let doc = lower("A **bold [link](https://ex.com)** here.\n");
        let xml = document_xml(&doc);
        assert!(
            xml.contains("w:hyperlink"),
            "nested link must still be a hyperlink"
        );
        assert!(xml.contains("<w:b "), "text inside strong must be bold");
    }

    #[test]
    fn table_emits_rows_and_header_shading() {
        let doc = lower("| a | b |\n|:--|--:|\n| 1 | 2 |\n");
        let xml = document_xml(&doc);
        assert!(xml.contains("w:tbl"), "table must be a native table");
        assert!(
            xml.contains(styles::TABLE_HEADER_FILL),
            "header row must be shaded"
        );
        assert!(
            xml.contains("w:jc") && xml.contains("right"),
            "column alignment must land"
        );
    }

    #[test]
    fn code_block_emits_monospace() {
        let doc = lower("```\nlet x = 1;\n```\n");
        let xml = document_xml(&doc);
        assert!(xml.contains("let x = 1;"), "code text must be preserved");
    }

    // --- INVARIANT-level operations: cross-references are internally consistent -----------------

    #[test]
    fn every_ordered_list_registers_its_numbering() {
        // Two ordered lists must each register a distinct numbering; the emit succeeds and both
        // sets of items reference a defined numbering id (docx-rs panics on an undefined ref).
        let doc = lower("1. a\n2. b\n\ntext\n\n1. c\n2. d\n");
        let xml = document_xml(&doc);
        let num_refs = xml.matches("w:numId").count();
        assert!(
            num_refs >= 2,
            "each ordered list must reference its numbering"
        );
    }
}