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};
#[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()
}
}
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
}
}
struct EmitState {
next_bookmark_id: usize,
next_num_id: usize,
heading_slugs: HashMap<String, usize>,
numberings: Vec<Numbering>,
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(),
}
}
fn bookmark_id(&mut self) -> usize {
let id = self.next_bookmark_id;
self.next_bookmark_id += 1;
id
}
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
}
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
}
}
enum Flow {
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)
}
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());
}
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"))
}
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);
}
}
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 } => {
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);
}
}
}
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 {
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),
}
}
}
}
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())
}
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,
}
}
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())
}
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)
}
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))
}
}
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
}
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
}
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)),
}
}
}
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
}
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
}
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
}
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))
}
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)
}
fn heading_style_id(level: u8) -> &'static str {
match level {
1 => "Heading1",
2 => "Heading2",
3 => "Heading3",
4 => "Heading4",
5 => "Heading5",
_ => "Heading6",
}
}
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;
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
}
#[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"
);
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"
);
}
#[test]
fn nested_emphasis_and_link_compose() {
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");
}
#[test]
fn every_ordered_list_registers_its_numbering() {
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"
);
}
}