@litfamily/litclaude 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +14 -8
  3. package/README_ko-KR.md +13 -8
  4. package/docs/assets/readme/badge-version.svg +1 -1
  5. package/docs/hooks.md +3 -2
  6. package/package.json +1 -1
  7. package/plugins/litclaude/.claude-plugin/plugin.json +1 -1
  8. package/plugins/litclaude/bin/litclaude-hook.js +4 -4
  9. package/plugins/litclaude/bin/litclaude-mcp.js +1 -1
  10. package/plugins/litclaude/lib/canonical-skill-resources.mjs +91 -31
  11. package/plugins/litclaude/skills/frontend-ui-ux/ATTRIBUTION.md +3 -6
  12. package/plugins/litclaude/skills/lit-docx/SKILL.md +50 -19
  13. package/plugins/litclaude/skills/lit-docx/references/components.md +207 -0
  14. package/plugins/litclaude/skills/lit-docx/references/direction-step.md +277 -0
  15. package/plugins/litclaude/skills/lit-docx/references/examples/01-report-ko.md +166 -0
  16. package/plugins/litclaude/skills/lit-docx/references/examples/02-brief-ko.md +105 -0
  17. package/plugins/litclaude/skills/lit-docx/references/examples/03-manual-ko.md +164 -0
  18. package/plugins/litclaude/skills/lit-docx/references/examples/04-proposal-ko.md +138 -0
  19. package/plugins/litclaude/skills/lit-docx/references/examples/05-memo-en.md +55 -0
  20. package/plugins/litclaude/skills/lit-docx/references/examples/06-journal-en.md +130 -0
  21. package/plugins/litclaude/skills/lit-docx/references/examples/07-report-en.md +123 -0
  22. package/plugins/litclaude/skills/lit-docx/references/examples/08-proposal-en.md +123 -0
  23. package/plugins/litclaude/skills/lit-docx/references/examples/09-memo-ko.md +45 -0
  24. package/plugins/litclaude/skills/lit-docx/references/page-composition.md +221 -0
  25. package/plugins/litclaude/skills/lit-docx/references/tonalities/brief.md +143 -0
  26. package/plugins/litclaude/skills/lit-docx/references/tonalities/journal.md +142 -0
  27. package/plugins/litclaude/skills/lit-docx/references/tonalities/manual.md +148 -0
  28. package/plugins/litclaude/skills/lit-docx/references/tonalities/memo.md +137 -0
  29. package/plugins/litclaude/skills/lit-docx/references/tonalities/proposal.md +140 -0
  30. package/plugins/litclaude/skills/lit-docx/references/tonalities/report.md +156 -0
  31. package/plugins/litclaude/skills/lit-docx/scripts/convert_md_to_docx.py +274 -73
  32. package/plugins/litclaude/skills/lit-docx/scripts/docx_design.py +2449 -0
  33. package/plugins/litclaude/skills/lit-docx/scripts/docx_layout.py +959 -0
  34. package/plugins/litclaude/skills/lit-docx/scripts/qa_docx.py +66 -9
  35. package/plugins/litclaude/skills/lit-docx/scripts/slop_lint.py +18 -6
  36. package/plugins/litclaude/skills/lit-docx/templates/tonalities/brief.yaml +28 -0
  37. package/plugins/litclaude/skills/lit-docx/templates/tonalities/journal.yaml +25 -0
  38. package/plugins/litclaude/skills/lit-docx/templates/tonalities/manual.yaml +26 -0
  39. package/plugins/litclaude/skills/lit-docx/templates/tonalities/memo.yaml +26 -0
  40. package/plugins/litclaude/skills/lit-docx/templates/tonalities/proposal.yaml +26 -0
  41. package/plugins/litclaude/skills/lit-docx/templates/tonalities/report.yaml +26 -0
  42. package/plugins/litclaude/skills/lit-pptx/SKILL.md +105 -48
  43. package/plugins/litclaude/skills/lit-pptx/references/agents/analyst.md +1 -1
  44. package/plugins/litclaude/skills/lit-pptx/references/agents/thesis.md +1 -1
  45. package/plugins/litclaude/skills/lit-pptx/references/anti-slop-checklist.md +59 -30
  46. package/plugins/litclaude/skills/lit-pptx/references/authoring-guide.md +119 -42
  47. package/plugins/litclaude/skills/lit-pptx/references/consensus-protocol.md +1 -1
  48. package/plugins/litclaude/skills/lit-pptx/references/data-display-cookbook.md +13 -6
  49. package/plugins/litclaude/skills/lit-pptx/references/density-and-fill.md +164 -0
  50. package/plugins/litclaude/skills/lit-pptx/references/design-system-azure.md +7 -4
  51. package/plugins/litclaude/skills/lit-pptx/references/direction-step.md +186 -0
  52. package/plugins/litclaude/skills/lit-pptx/references/examples/01-pitch-signal-ko.md +210 -0
  53. package/plugins/litclaude/skills/lit-pptx/references/examples/02-pitch-studio-ko.md +147 -0
  54. package/plugins/litclaude/skills/lit-pptx/references/examples/03-business-review-ledger-ko.md +199 -0
  55. package/plugins/litclaude/skills/lit-pptx/references/examples/04-business-review-night-en.md +203 -0
  56. package/plugins/litclaude/skills/lit-pptx/references/examples/05-research-talk-paper-en.md +179 -0
  57. package/plugins/litclaude/skills/lit-pptx/references/examples/06-lecture-chalk-ko.md +199 -0
  58. package/plugins/litclaude/skills/lit-pptx/references/examples/07-data-review-night-en.md +194 -0
  59. package/plugins/litclaude/skills/lit-pptx/references/examples/08-image-led-atlas-ko.md +175 -0
  60. package/plugins/litclaude/skills/lit-pptx/references/examples/09-briefing-gazette-ko.md +204 -0
  61. package/plugins/litclaude/skills/lit-pptx/references/examples/10-status-update-ledger-ko.md +179 -0
  62. package/plugins/litclaude/skills/lit-pptx/references/examples/11-portfolio-studio-en.md +164 -0
  63. package/plugins/litclaude/skills/lit-pptx/references/examples/12-research-tutorial-chalk-en.md +174 -0
  64. package/plugins/litclaude/skills/lit-pptx/references/interview-protocol.md +1 -1
  65. package/plugins/litclaude/skills/lit-pptx/references/layout-families.md +198 -0
  66. package/plugins/litclaude/skills/lit-pptx/references/stages/autopilot.md +1 -1
  67. package/plugins/litclaude/skills/lit-pptx/references/stages/interview.md +2 -2
  68. package/plugins/litclaude/skills/lit-pptx/references/stages/plan.md +1 -1
  69. package/plugins/litclaude/skills/lit-pptx/references/title-treatments.md +109 -0
  70. package/plugins/litclaude/skills/lit-pptx/references/tonalities/atlas.md +139 -0
  71. package/plugins/litclaude/skills/lit-pptx/references/tonalities/chalk.md +148 -0
  72. package/plugins/litclaude/skills/lit-pptx/references/tonalities/gazette.md +149 -0
  73. package/plugins/litclaude/skills/lit-pptx/references/tonalities/ledger.md +149 -0
  74. package/plugins/litclaude/skills/lit-pptx/references/tonalities/night.md +147 -0
  75. package/plugins/litclaude/skills/lit-pptx/references/tonalities/paper.md +151 -0
  76. package/plugins/litclaude/skills/lit-pptx/references/tonalities/signal.md +150 -0
  77. package/plugins/litclaude/skills/lit-pptx/references/tonalities/studio.md +132 -0
  78. package/plugins/litclaude/skills/lit-pptx/scripts/compile-deck.js +64 -16
  79. package/plugins/litclaude/skills/lit-pptx/scripts/craft_extras.py +664 -3
  80. package/plugins/litclaude/skills/lit-pptx/scripts/deck_craft.py +48 -6
  81. package/plugins/litclaude/skills/lit-pptx/scripts/lib/grid-resolver.js +521 -0
  82. package/plugins/litclaude/skills/lit-pptx/scripts/lib/layout-resolver.js +362 -11
  83. package/plugins/litclaude/skills/lit-pptx/scripts/lib/markdown-loader.js +6 -4
  84. package/plugins/litclaude/skills/lit-pptx/scripts/lib/render-adapter-pptx.js +211 -65
  85. package/plugins/litclaude/skills/lit-pptx/scripts/lib/render-pack.js +3559 -0
  86. package/plugins/litclaude/skills/lit-pptx/scripts/lib/slide-ast.js +10 -6
  87. package/plugins/litclaude/skills/lit-pptx/scripts/lib/template-registry.js +286 -1
  88. package/plugins/litclaude/skills/lit-pptx/scripts/qa_deck.py +39 -10
  89. package/plugins/litclaude/skills/lit-pptx/scripts/validate_pptx.py +22 -7
  90. package/plugins/litclaude/skills/lit-pptx/templates/enrolled/AZURE-A2Z/layout-mapping.yaml +1 -1
  91. package/plugins/litclaude/skills/lit-pptx/templates/enrolled/AZURE-A2Z/template.yaml +4 -1
  92. package/plugins/litclaude/skills/lit-pptx/templates/enrolled/AZURE-PRO/layout-mapping.yaml +1 -1
  93. package/plugins/litclaude/skills/lit-pptx/templates/enrolled/AZURE-PRO/template.yaml +4 -1
  94. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/atlas/pack.yaml +92 -0
  95. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/chalk/pack.yaml +97 -0
  96. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/gazette/pack.yaml +93 -0
  97. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/ledger/pack.yaml +94 -0
  98. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/night/pack.yaml +93 -0
  99. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/paper/pack.yaml +98 -0
  100. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/signal/pack.yaml +94 -0
  101. package/plugins/litclaude/skills/lit-pptx/templates/tonalities/studio/pack.yaml +92 -0
@@ -0,0 +1,2449 @@
1
+ """Design directions (tonalities) and page components for convert_md_to_docx.py.
2
+
3
+ A tonality is a data file, templates/tonalities/<name>.yaml, merged over the korean-generic
4
+ `design:` tree of templates/registry.yaml; its two dials (density, variance) then set the page
5
+ margins, leading and body size. The converter reads the pack; nothing here forks per look.
6
+
7
+ The six tonalities differ in structure, not colour (docx-spec Amendments 4, "restraint"): what
8
+ stands on page 1 (a title block, a cover page, a memo block, a document-control block), how the
9
+ summary is set, how headings are numbered, which components a document may use and what the running
10
+ head carries. Every pack sets body and headings in near-black ink, booktabs tables without fills,
11
+ a quiet 1.2x type scale on an A4 page with 25 mm sides, and at most one accent colour on at most
12
+ two element kinds.
13
+
14
+ The Markdown dialect adds fenced directives (::: cover, callout, sidebar, pullquote, keyfigures,
15
+ columns; <!-- column-break --> inside columns) and a {style=...} attribute on table captions. The
16
+ pre-pass splits them out before Markdown sees the text, so no fence ever reaches the page. A
17
+ directive the tonality does not use, or one past the component budget, keeps its content as
18
+ ordinary text; a pull quote that repeats a sentence of the body is left out.
19
+
20
+ The plain profile (no tonality, no publisher) runs through the same builders with neutral tokens:
21
+ A4, Pretendard, booktabs tables, the notice in every header.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import copy
26
+ import datetime as _dt
27
+ import math
28
+ import re
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+
32
+ import yaml
33
+ from docx.enum.section import WD_SECTION
34
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK, WD_TAB_ALIGNMENT, WD_TAB_LEADER
35
+ from docx.oxml import OxmlElement
36
+ from docx.oxml.ns import qn
37
+ from docx.shared import Emu, Mm, Pt, RGBColor
38
+ from docx.table import Table
39
+ from docx.text.paragraph import Paragraph
40
+
41
+ SKILL_ROOT = Path(__file__).resolve().parent.parent
42
+ TONALITIES = ("Report", "Brief", "Manual", "Proposal", "Memo", "Journal")
43
+ NUMBERING = ("none", "decimal", "roman-ko")
44
+ TITLE_BLOCKS = ("masthead", "cover", "memo", "manual")
45
+ RUNNING_ITEMS = ("title", "folio", "section")
46
+ TABLE_STYLES = ("booktabs", "banded", "light-grid", "header-fill") # caption attributes; every tonality draws booktabs
47
+ COVERS = ("typographic", "band", "split", "masthead") # ::: cover variant= values the source may name
48
+ KINDS = ("callout", "sidebar", "pullquote", "keyfigures", "columns")
49
+ CALLOUT_KINDS = ("note", "key", "warning")
50
+ CALLOUT_PRIORITY = {"key": 0, "warning": 1, "note": 2}
51
+ NOTICE = ("A21B12", "FDECEA") # the plain and publisher profiles' example-data tag: ink on fill
52
+ LABELS = {
53
+ "ko": {"note": "참고", "key": "핵심", "warning": "주의", "abstract": "초록", "keywords": "주요어", "contents": "목차",
54
+ "memo": "메모", "to": "받는 사람", "from": "보내는 사람", "date": "날짜", "subject": "제목", "unit": "단위",
55
+ "doc": "문서", "owner": "작성 부서", "org": "기관", "issued": "시행일"},
56
+ "en": {"note": "Note", "key": "Key point", "warning": "Warning", "abstract": "Abstract", "keywords": "Keywords", "contents": "Contents",
57
+ "memo": "Memo", "to": "To", "from": "From", "date": "Date", "subject": "Subject", "unit": "Unit",
58
+ "doc": "Document", "owner": "Owner", "org": "Organisation", "issued": "Issued"},
59
+ }
60
+ PACK_KEYS = {"schema_version", "tonality", "summary", "dials", "docx", "design"}
61
+ DESIGN_KEYS = {"ramp", "numbering", "h1_rule", "title_block", "contents", "summary_form", "conclusion_first", "running_head", "justify",
62
+ "palette", "accent_on", "page_geometry", "components", "figure_style", "spacing"}
63
+ ACCENT_PLACES = ("title_rule", "callout_rule", "sidebar_rule")
64
+ DIRECTIVE_KEYS = {
65
+ "cover": {"variant", "image", "kicker"},
66
+ "callout": {"kind", "title"},
67
+ "sidebar": {"title", "width", "float"},
68
+ "pullquote": {"cite"},
69
+ "keyfigures": {"cols"},
70
+ "columns": {"gap", "rule"},
71
+ }
72
+ SOURCE_LINE = re.compile(r"^(출처|자료|주|Source|Sources|Note|Notes)\s*[::]")
73
+ CAPTION_ATTR = re.compile(r"^((?:표|Table)[ \t]*\d+\..*?)[ \t]*\{style=([a-z-]+)\}[ \t]*$", re.M)
74
+ TABLE_CAPTION = re.compile(r"^(?:표|Table)\s*\d+[.:]|^<표\s*\d+>")
75
+ FIGURE_LABEL = re.compile(r"^((?:Figure|Fig\.|그림|도)\s*\d+[.:])\s*")
76
+ TOTALS = re.compile(r"^(합계|총계|소계|계|total|sum)(?![\w])", re.I)
77
+ ISO_DATE = re.compile(r"(?<![\d-])((?:19|20)\d{2})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?![\d-])")
78
+ BACK_MATTER = re.compile(r"^(references|bibliography|acknowledg(e)?ments?|참고\s*문헌|감사의\s*글)$", re.I)
79
+ ROMAN = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ"
80
+ # A single line in em, measured on rendered pages (Word 1.55 / LibreOffice 1.51 for Pretendard; the mean is used).
81
+ SINGLE_EM = {"Pretendard": 1.53, "Times New Roman": 1.15}
82
+ GANADA = "가나다라마바사아자차카타파하"
83
+ CIRCLED = "①②③④⑤"
84
+ MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
85
+
86
+
87
+ class DesignError(ValueError):
88
+ """A pack, dial or directive the engine cannot honour; the message names what is allowed."""
89
+
90
+
91
+ # ── Packs and dials ──────────────────────────────────────────────────────────
92
+
93
+ def _merge(base: dict, over: dict) -> dict:
94
+ out = copy.deepcopy(base)
95
+ for key, value in (over or {}).items():
96
+ out[key] = _merge(out[key], value) if isinstance(value, dict) and isinstance(out.get(key), dict) else copy.deepcopy(value)
97
+ return out
98
+
99
+
100
+ def _half(x: float) -> float:
101
+ return math.floor(x * 2 + 0.5) / 2
102
+
103
+
104
+ # Margins (top, bottom, left, right) in mm by density: sides never under 25 mm (a text block of at most
105
+ # 160 mm on A4) and the bottom never under the top (docx-spec Amendments 4, A4.3).
106
+ MARGINS = [(2, (30, 32, 30, 30)), (4, (28, 30, 28, 28)), (6, (27, 29, 27, 27)), (8, (26, 28, 26, 26)), (9, (25, 27, 25, 25)), (10, (24, 26, 25, 25))]
107
+
108
+
109
+ @dataclass
110
+ class Tonality:
111
+ name: str
112
+ dials: dict
113
+ design: dict
114
+ docx: dict
115
+ locale: str = "ko"
116
+ neutral: bool = False
117
+ palette: dict = field(default_factory=dict)
118
+
119
+ # Derived tokens; the converter reads these and never a number of its own.
120
+ @property
121
+ def density(self) -> int:
122
+ return self.dials["density"]
123
+
124
+ @property
125
+ def variance(self) -> int:
126
+ return self.dials["variance"]
127
+
128
+ @property
129
+ def margins_mm(self) -> tuple:
130
+ return next(m for d, m in MARGINS if self.density <= d)
131
+
132
+ @property
133
+ def body_pt(self) -> float:
134
+ font = self.docx.get("font", {})
135
+ b = float(font.get("body_pt_en" if self.locale == "en" else "body_pt_ko", 10.5))
136
+ b += 0.5 if self.density <= 3 else 0
137
+ return max(10.5, b) # the readable floor: body text never under 10.5 pt
138
+
139
+ @property
140
+ def tight(self) -> bool:
141
+ """A pack that keeps short documents on one page (Memo): the low end of the A4.3 pitches, tighter heading space."""
142
+ return self.design.get("spacing") == "tight"
143
+
144
+ @property
145
+ def pitch(self) -> float:
146
+ """Body line pitch over the body size (A4.3): Hangul 175-185 %, Latin 130-140 %; a tight pack 165 % / 120 %
147
+ (the low ends of A4.3)."""
148
+ en = self.locale == "en"
149
+ if self.tight:
150
+ return 1.2 if en else 1.65
151
+ return (1.4 if en else 1.85) if self.density <= 4 else (1.37 if en else 1.8) if self.density <= 7 else (1.33 if en else 1.75)
152
+
153
+ def line(self, pitch: float, face: str | None = None) -> float:
154
+ """The Word "multiple" that sets a line pitch of `pitch` times the size in the given face (the body face
155
+ when omitted). A single line is not 1.0 em: measured on rendered pages, Pretendard's is 1.55 em in Word
156
+ and 1.51 em in LibreOffice (task-12b/leading-calibration.txt), Times New Roman's about 1.15 em."""
157
+ face = face or self.fonts["latin" if self.locale == "en" else "hangul"]
158
+ return round(pitch / SINGLE_EM.get(face, SINGLE_EM["Pretendard"]), 3)
159
+
160
+ @property
161
+ def leading(self) -> float:
162
+ """Body line spacing as a Word multiple (the pitch over the face's single line)."""
163
+ return self.line(self.pitch)
164
+
165
+ @property
166
+ def unit(self) -> float:
167
+ return self.body_pt * self.pitch
168
+
169
+ @property
170
+ def sizes(self) -> dict:
171
+ b, ramp = self.body_pt, self.design.get("ramp") or {}
172
+ return {"h1": _half(b * float(ramp.get("h1", 1.4))), "h2": _half(b * float(ramp.get("h2", 1.2))), "h3": b, "h4": b,
173
+ "title": _half(b * float(ramp.get("title", 2.5)))}
174
+
175
+ @property
176
+ def table_pt(self) -> float:
177
+ return max(9.0, _half(self.body_pt * 0.92))
178
+
179
+ @property
180
+ def note_pt(self) -> float:
181
+ return max(8.5, self.table_pt - 0.5)
182
+
183
+ @property
184
+ def furniture_pt(self) -> float:
185
+ return max(8.5, _half(self.body_pt * 0.82))
186
+
187
+ @property
188
+ def keyfigure_pt(self) -> float:
189
+ # A key figure is one modest step above the body, never a display number.
190
+ return self.sizes["h2"]
191
+
192
+ @property
193
+ def numbering(self) -> str:
194
+ n = self.design.get("numbering") or "none"
195
+ if isinstance(n, dict):
196
+ n = n.get(self.locale) or n.get("default") or "none"
197
+ return n
198
+
199
+ @property
200
+ def title_block(self) -> str:
201
+ return self.design.get("title_block") or "masthead"
202
+
203
+ @property
204
+ def running_head(self) -> dict:
205
+ return self.design.get("running_head") or {}
206
+
207
+ @property
208
+ def columns(self) -> int:
209
+ return int((self.design.get("page_geometry") or {}).get("columns", 1) or 1)
210
+
211
+ @property
212
+ def column_gap_mm(self) -> float:
213
+ return float((self.design.get("page_geometry") or {}).get("column_gap_cm", 0.6)) * 10
214
+
215
+ @property
216
+ def components(self) -> dict:
217
+ return self.design.get("components") or {}
218
+
219
+ @property
220
+ def allowed_kinds(self) -> list:
221
+ return list(self.components.get("allowed") or [])
222
+
223
+ @property
224
+ def justify(self) -> bool:
225
+ j = self.design.get("justify", "ko")
226
+ return j == "all" or (j == "ko" and self.locale != "en")
227
+
228
+ @property
229
+ def fonts(self) -> dict:
230
+ f = self.docx.get("font", {})
231
+ return {"latin": f.get("latin", "Pretendard"), "hangul": f.get("hangul", "Pretendard"), "heading": f.get("heading", "Pretendard")}
232
+
233
+ def colour(self, role: str) -> str:
234
+ return self.palette[role]
235
+
236
+ def accent_for(self, place: str) -> str:
237
+ """The accent on the places the pack names (at most two element kinds), ink everywhere else."""
238
+ return self.palette["accent"] if place in (self.design.get("accent_on") or []) else self.palette["ink"]
239
+
240
+
241
+ def _registry_base(registry: Path | None = None) -> dict:
242
+ path = registry or SKILL_ROOT / "templates" / "registry.yaml"
243
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
244
+ return copy.deepcopy(data["publishers"]["korean-generic"]["design"])
245
+
246
+
247
+ def _check(value, allowed, what):
248
+ if value not in allowed:
249
+ raise DesignError(f"{what} {value!r} is not one of: {', '.join(allowed)}")
250
+
251
+
252
+ def load_tonality(name: str, density: int | None = None, variance: int | None = None, locale: str = "ko", registry: Path | None = None) -> Tonality:
253
+ """Load a pack by name (any case), merge it over the korean-generic design tree and apply the dials."""
254
+ match = next((t for t in TONALITIES if t.lower() == str(name).strip().lower()), None)
255
+ if not match:
256
+ raise DesignError(f"unknown tonality {name!r}; the tonalities are {', '.join(sorted(TONALITIES))}")
257
+ pack = yaml.safe_load((SKILL_ROOT / "templates" / "tonalities" / f"{match.lower()}.yaml").read_text(encoding="utf-8"))
258
+ unknown = set(pack) - PACK_KEYS
259
+ if unknown:
260
+ raise DesignError(f"{match}: unknown pack keys {sorted(unknown)}; allowed {sorted(PACK_KEYS)}")
261
+ unknown = set(pack.get("design") or {}) - DESIGN_KEYS
262
+ if unknown:
263
+ raise DesignError(f"{match}: unknown design keys {sorted(unknown)}; allowed {sorted(DESIGN_KEYS)}")
264
+ dials = dict(pack.get("dials") or {})
265
+ for key, value in (("density", density), ("variance", variance)):
266
+ if value is not None:
267
+ dials[key] = value
268
+ if not isinstance(dials.get(key), int) or not 1 <= dials[key] <= 10:
269
+ raise DesignError(f"{match}: dial {key} must be an integer from 1 to 10, got {dials.get(key)!r}")
270
+ design = _merge(_registry_base(registry), pack.get("design") or {})
271
+ numbering = design.get("numbering") or "none"
272
+ for value in (numbering.values() if isinstance(numbering, dict) else [numbering]):
273
+ _check(value, NUMBERING, f"{match} numbering")
274
+ _check(design.get("title_block", "masthead"), TITLE_BLOCKS, f"{match} title_block")
275
+ _check(design.get("h1_rule", "none"), ("none", "above"), f"{match} h1_rule")
276
+ _check(design.get("spacing", "normal"), ("normal", "tight"), f"{match} spacing")
277
+ for where, items in (design.get("running_head") or {}).items():
278
+ _check(where, ("header", "footer", "folio_align"), f"{match} running_head key")
279
+ if where != "folio_align":
280
+ for item in items:
281
+ _check(item, RUNNING_ITEMS, f"{match} running_head.{where}")
282
+ for place in design.get("accent_on") or []:
283
+ _check(place, ACCENT_PLACES, f"{match} accent_on")
284
+ if len(design.get("accent_on") or []) > 2:
285
+ raise DesignError(f"{match}: the accent marks at most two element kinds, got {design['accent_on']}")
286
+ for kind in (design.get("components") or {}).get("allowed") or []:
287
+ _check(kind, KINDS, f"{match} components.allowed")
288
+ if "pullquote" in ((design.get("components") or {}).get("allowed") or []):
289
+ raise DesignError(f"{match}: pull quotes are off in every tonality")
290
+ pal = design.get("palette") or {}
291
+ palette = {"ink": str(pal.get("ink", "1A1A1A")).lstrip("#").upper(), "ink_muted": str(pal.get("ink_muted", "555555")).lstrip("#").upper(),
292
+ "line": str(pal.get("line", "8C8C8C")).lstrip("#").upper()}
293
+ palette["accent"] = str(pal["accent"]).lstrip("#").upper() if pal.get("accent") else palette["ink"]
294
+ return Tonality(match, dials, design, dict(pack.get("docx") or {}), locale, False, palette)
295
+
296
+
297
+ def neutral_tonality(locale: str = "ko") -> Tonality:
298
+ """The plain profile's tokens: ink and line only, booktabs tables, plain headings, notice-only header."""
299
+ design = _registry_base()
300
+ design.update({
301
+ "ramp": {"h1": 1.4, "h2": 1.2, "title": 2.1},
302
+ "numbering": "none",
303
+ "title_block": "masthead",
304
+ "figure_style": {"max_height_ratio": 0.45},
305
+ "page_geometry": {"columns": 1, "column_gap_cm": 0.6},
306
+ "components": {"allowed": [k for k in KINDS if k != "pullquote"], "keyfigures": {"per_row": 3}, "sidebar": {"default_width": "third", "float": "right"}},
307
+ "justify": "none",
308
+ })
309
+ palette = {"ink": "1A1A1A", "ink_muted": "555555", "line": "8C8C8C", "accent": "1A1A1A"}
310
+ docx_cfg = {"font": {"latin": "Pretendard", "hangul": "Pretendard", "heading": "Pretendard", "body_pt_ko": 10.5, "body_pt_en": 10.5}}
311
+ return Tonality("plain", {"density": 7, "variance": 10}, design, docx_cfg, locale, True, palette)
312
+
313
+
314
+ def format_date(value, lang: str) -> str:
315
+ """A frontmatter or body date as a reader writes it: 2026. 10. 1. in Korean, 1 October 2026 in English
316
+ (docx-spec Amendments 4, A4.10: no ISO dates in Korean text)."""
317
+ if isinstance(value, (_dt.date, _dt.datetime)):
318
+ y, m, d = value.year, value.month, value.day
319
+ else:
320
+ found = ISO_DATE.fullmatch(str(value).strip())
321
+ if not found:
322
+ return str(value)
323
+ y, m, d = (int(x) for x in found.groups())
324
+ return f"{y}. {m}. {d}." if lang != "en" else f"{d} {MONTHS[m - 1]} {y}"
325
+
326
+
327
+ def korean_dates(text: str) -> str:
328
+ """ISO dates in Korean Markdown, written the Korean way; a date that opens a line escapes its first full stop,
329
+ or Markdown would read "2026. 6. 30." as a numbered list."""
330
+ def korean(m):
331
+ escape = "\\" if m.start() == 0 or text[m.start() - 1] == "\n" else ""
332
+ return f"{int(m.group(1))}{escape}. {int(m.group(2))}. {int(m.group(3))}."
333
+ return ISO_DATE.sub(korean, text)
334
+
335
+
336
+ # ── Directive pre-pass ──────────────────────────────────────────────────────
337
+
338
+ @dataclass
339
+ class Directive:
340
+ name: str
341
+ args: list
342
+ attrs: dict
343
+ body: str
344
+ line: int
345
+
346
+
347
+ _OPEN = re.compile(r"^(:{3,})[ \t]+([A-Za-z]+)(.*)$")
348
+ _ARG = re.compile(r'\s*([a-z_]+)=("(?:[^"\\]|\\")*"|[A-Za-z0-9_.%-]+)|\s*([A-Za-z0-9_.%-]+)')
349
+ COLUMN_BREAK = re.compile(r"^\s*<!--\s*column-break\s*-->\s*$", re.M)
350
+
351
+
352
+ def _parse_args(name: str, rest: str, line: int) -> tuple[list, dict]:
353
+ args, attrs, pos = [], {}, 0
354
+ rest = rest.rstrip()
355
+ while pos < len(rest):
356
+ m = _ARG.match(rest, pos)
357
+ if not m or m.end() == pos:
358
+ raise DesignError(f"line {line}: cannot read the attributes of ::: {name}: {rest[pos:]!r}")
359
+ if m.group(1):
360
+ key, value = m.group(1), m.group(2)
361
+ if key in attrs:
362
+ raise DesignError(f"line {line}: ::: {name} repeats {key}=")
363
+ if key not in DIRECTIVE_KEYS[name]:
364
+ raise DesignError(f"line {line}: ::: {name} has no attribute {key}; it takes {', '.join(sorted(DIRECTIVE_KEYS[name]))}")
365
+ attrs[key] = value[1:-1].replace('\\"', '"') if value.startswith('"') else value
366
+ else:
367
+ args.append(m.group(3))
368
+ pos = m.end()
369
+ return args, attrs
370
+
371
+
372
+ def split_directives(text: str, offset: int = 0) -> list:
373
+ """The source as a list of Markdown strings and Directive blocks, in order. Fenced code stays text."""
374
+ lines = text.split("\n")
375
+ out, buf, i, code = [], [], 0, False
376
+ while i < len(lines):
377
+ line = lines[i]
378
+ if line.lstrip().startswith(("```", "~~~")):
379
+ code = not code
380
+ m = None if code else _OPEN.match(line)
381
+ if m:
382
+ fence, name = m.group(1), m.group(2)
383
+ if name not in DIRECTIVE_KEYS:
384
+ raise DesignError(f"line {offset + i + 1}: unknown directive ::: {name}; directives are {', '.join(DIRECTIVE_KEYS)}")
385
+ j = i + 1
386
+ while j < len(lines) and lines[j].strip() != fence:
387
+ j += 1
388
+ if j == len(lines):
389
+ raise DesignError(f"line {offset + i + 1}: ::: {name} is never closed (a line of {len(fence)} colons)")
390
+ if buf:
391
+ out.append("\n".join(buf))
392
+ buf = []
393
+ args, attrs = _parse_args(name, m.group(3), offset + i + 1)
394
+ out.append(Directive(name, args, attrs, "\n".join(lines[i + 1:j]), offset + i + 2))
395
+ i = j + 1
396
+ continue
397
+ if not code and re.match(r"^:{3,}\s*$", line):
398
+ raise DesignError(f"line {offset + i + 1}: a closing fence with no directive open")
399
+ buf.append(line)
400
+ i += 1
401
+ if buf:
402
+ out.append("\n".join(buf))
403
+ return out
404
+
405
+
406
+ def has_directives(text: str) -> bool:
407
+ return any(isinstance(b, Directive) for b in split_directives(text)) or bool(COLUMN_BREAK.search(text))
408
+
409
+
410
+ # ── XML helpers ─────────────────────────────────────────────────────────────
411
+
412
+ PPR_ORDER = ["pStyle", "keepNext", "keepLines", "pageBreakBefore", "framePr", "widowControl", "numPr", "suppressLineNumbers", "pBdr", "shd",
413
+ "tabs", "suppressAutoHyphens", "kinsoku", "wordWrap", "overflowPunct", "topLinePunct", "autoSpaceDE", "autoSpaceDN", "bidi",
414
+ "adjustRightInd", "snapToGrid", "spacing", "ind", "contextualSpacing", "mirrorIndents", "suppressOverlap", "jc", "textDirection",
415
+ "textAlignment", "textboxTightWrap", "outlineLvl", "divId", "cnfStyle", "rPr", "sectPr", "pPrChange"]
416
+ TBLPR_ORDER = ["tblStyle", "tblpPr", "tblOverlap", "bidiVisual", "tblStyleRowBandSize", "tblStyleColBandSize", "tblW", "jc", "tblCellSpacing",
417
+ "tblInd", "tblBorders", "shd", "tblLayout", "tblCellMar", "tblLook", "tblCaption", "tblDescription"]
418
+ TCPR_ORDER = ["cnfStyle", "tcW", "gridSpan", "hMerge", "vMerge", "tcBorders", "shd", "noWrap", "tcMar", "textDirection", "tcFitText", "vAlign", "hideMark"]
419
+ RPR_ORDER = ["rStyle", "rFonts", "b", "bCs", "i", "iCs", "caps", "smallCaps", "strike", "dstrike", "outline", "shadow", "emboss", "imprint",
420
+ "noProof", "snapToGrid", "vanish", "webHidden", "color", "spacing", "w", "kern", "position", "sz", "szCs", "highlight", "u",
421
+ "effect", "bdr", "shd", "fitText", "vertAlign", "rtl", "cs", "em", "lang", "eastAsianLayout", "specVanish", "oMath"]
422
+ SECTPR_ORDER = ["headerReference", "footerReference", "footnotePr", "endnotePr", "type", "pgSz", "pgMar", "paperSrc", "pgBorders", "lnNumType",
423
+ "pgNumType", "cols", "formProt", "vAlign", "noEndnote", "titlePg", "textDirection", "bidi", "rtlGutter", "docGrid", "printerSettings"]
424
+
425
+
426
+ def _el(tag: str, **attrs):
427
+ el = OxmlElement(f"w:{tag}")
428
+ for key, value in attrs.items():
429
+ el.set(qn(f"w:{key}"), str(value))
430
+ return el
431
+
432
+
433
+ def _put(parent, child, order):
434
+ """Insert child into parent in schema order, replacing an element of the same tag."""
435
+ for old in parent.findall(child.tag):
436
+ parent.remove(old)
437
+ names = [qn(f"w:{n}") for n in order]
438
+ later = set(names[names.index(child.tag) + 1:]) if child.tag in names else set()
439
+ for el in parent:
440
+ if el.tag in later:
441
+ el.addprevious(child)
442
+ return child
443
+ parent.append(child)
444
+ return child
445
+
446
+
447
+ def _borders(tag: str, sides: dict, order=None):
448
+ box = _el(tag)
449
+ for side in order or ("top", "left", "bottom", "right", "insideH", "insideV"):
450
+ if side in sides:
451
+ spec = sides[side]
452
+ if spec is None:
453
+ box.append(_el(side, val="nil"))
454
+ else:
455
+ sz, colour = spec[:2]
456
+ space = spec[2] if len(spec) > 2 else 0
457
+ box.append(_el(side, val="single", sz=int(sz), space=space, color=colour))
458
+ return box
459
+
460
+
461
+ def para_border(p: Paragraph, sides: dict):
462
+ _put(p._p.get_or_add_pPr(), _borders("pBdr", sides, ("top", "left", "bottom", "right", "between")), PPR_ORDER)
463
+
464
+
465
+ def run_shade(run, fill: str):
466
+ _put(run._r.get_or_add_rPr(), _el("shd", val="clear", color="auto", fill=fill), RPR_ORDER)
467
+
468
+
469
+ def set_run_fonts(rpr, latin: str, hangul: str):
470
+ rf = rpr.find(qn("w:rFonts"))
471
+ if rf is None:
472
+ rf = _put(rpr, _el("rFonts"), RPR_ORDER)
473
+ for key in ("asciiTheme", "hAnsiTheme", "eastAsiaTheme", "cstheme", "hint"):
474
+ if rf.get(qn(f"w:{key}")) is not None:
475
+ del rf.attrib[qn(f"w:{key}")]
476
+ rf.set(qn("w:ascii"), latin)
477
+ rf.set(qn("w:hAnsi"), latin)
478
+ rf.set(qn("w:cs"), latin)
479
+ rf.set(qn("w:eastAsia"), hangul)
480
+
481
+
482
+ def styled_run(p: Paragraph, text: str, size: float | None = None, colour: str | None = None, bold: bool | None = None, font: tuple | None = None):
483
+ run = p.add_run(text)
484
+ if size:
485
+ run.font.size = Pt(size)
486
+ if colour:
487
+ run.font.color.rgb = RGBColor.from_string(colour)
488
+ if bold is not None:
489
+ run.bold = bold
490
+ if font:
491
+ set_run_fonts(run._r.get_or_add_rPr(), *font)
492
+ return run
493
+
494
+
495
+ def _advance(text: str, size: float) -> float:
496
+ """Estimated width in points of bold display type: a Hangul syllable a full em, Latin by letter class."""
497
+ em = 0.0
498
+ for ch in text:
499
+ if "가" <= ch <= "힣" or "ㄱ" <= ch <= "ㆎ" or "一" <= ch <= "鿿":
500
+ em += 1.0
501
+ elif ch == " ":
502
+ em += 0.28
503
+ elif ch.isupper() or ch in "mwMW%&@":
504
+ em += 0.74
505
+ elif ch.isdigit():
506
+ em += 0.62
507
+ elif ch.isalpha():
508
+ em += 0.58
509
+ else:
510
+ em += 0.4
511
+ return em * size
512
+
513
+
514
+ TITLE_LINES = 3
515
+
516
+
517
+ def wrap_words(text: str, size: float, width_pt: float) -> list[str]:
518
+ """Break a display line between words only, into the fewest lines that fit the measure, with the
519
+ lines as even as that count allows (least squared slack); a line never ends inside a word (제/안서)."""
520
+ words = text.split()
521
+ if not words or _advance(text, size) <= width_pt:
522
+ return [" ".join(words)]
523
+ measure = lambda i, j: _advance(" ".join(words[i:j]), size) # noqa: E731
524
+ n = len(words)
525
+ for lines in range(2, n + 1):
526
+ best = {0: (0.0, [])} # words placed -> (squared slack so far, break positions)
527
+ for _ in range(lines):
528
+ nxt = {}
529
+ for i, (cost, cuts) in best.items():
530
+ for j in range(i + 1, n + 1):
531
+ w = measure(i, j)
532
+ if w > width_pt:
533
+ break
534
+ cand = (cost + (width_pt - w) ** 2, cuts + [j])
535
+ if j not in nxt or cand[0] < nxt[j][0]:
536
+ nxt[j] = cand
537
+ best = nxt
538
+ if n in best:
539
+ cuts = [0] + best[n][1]
540
+ return [" ".join(words[a:b]) for a, b in zip(cuts, cuts[1:])]
541
+ return [" ".join(words)]
542
+
543
+
544
+ def display_run(p: Paragraph, text: str, size: float, width_emu: int, colour: str, bold: bool, font: tuple):
545
+ """A title at its size, broken between words for its measure in at most three lines; a word wider
546
+ than the measure, or a fourth line, steps the size down."""
547
+ width_pt = width_emu / 12700 * 0.94 # keep a margin for metric differences between renderers
548
+ words = str(text).split() or [""]
549
+ while size > 14 and (max(_advance(w, size) for w in words) > width_pt or len(wrap_words(str(text), size, width_pt)) > TITLE_LINES):
550
+ size -= 1
551
+ lines = wrap_words(str(text), size, width_pt)
552
+ for i, line in enumerate(lines):
553
+ last = i == len(lines) - 1
554
+ run = styled_run(p, line if last else line + " ", size, colour, bold, font) # the space keeps the text whole
555
+ if not last:
556
+ run.add_break()
557
+ return size
558
+
559
+
560
+ def add_field(p: Paragraph, instr: str, size: float, colour: str, placeholder: str = "1"):
561
+ fld = _el("fldSimple", instr=instr)
562
+ r = OxmlElement("w:r")
563
+ rpr = OxmlElement("w:rPr")
564
+ _put(rpr, _el("color", val=colour), RPR_ORDER)
565
+ _put(rpr, _el("sz", val=int(size * 2)), RPR_ORDER)
566
+ r.append(rpr)
567
+ t = OxmlElement("w:t")
568
+ t.text = placeholder
569
+ r.append(t)
570
+ fld.append(r)
571
+ p._p.append(fld)
572
+
573
+
574
+ def tiny(p: Paragraph):
575
+ """A structural paragraph (section or column break carrier) that takes no visible height."""
576
+ pf = p.paragraph_format
577
+ pf.space_before = Pt(0)
578
+ pf.space_after = Pt(0)
579
+ pf.line_spacing = Pt(1)
580
+ rpr = p._p.get_or_add_pPr()
581
+ mark = _put(rpr, _el("rPr"), PPR_ORDER)
582
+ mark.append(_el("sz", val=2))
583
+
584
+
585
+ def tbl_set(table, tag: str, el):
586
+ tblPr = table._tbl.tblPr
587
+ _put(tblPr, el, TBLPR_ORDER)
588
+
589
+
590
+ def cell_set(cell, el):
591
+ _put(cell._tc.get_or_add_tcPr(), el, TCPR_ORDER)
592
+
593
+
594
+ def cell_margins(table, top: float, bottom: float, left: float, right: float):
595
+ mar = _el("tblCellMar")
596
+ for side, v in (("top", top), ("left", left), ("bottom", bottom), ("right", right)):
597
+ mar.append(_el(side, w=int(v * 20), type="dxa"))
598
+ tbl_set(table, "tblCellMar", mar)
599
+
600
+
601
+ def mark_component(table, kind: str):
602
+ tbl_set(table, "tblCaption", _el("tblCaption", val=kind))
603
+
604
+
605
+ def table_width(table, width_emu: int, widths: list | None = None):
606
+ tbl_set(table, "tblW", _el("tblW", w=int(width_emu / 635), type="dxa"))
607
+ tbl_set(table, "tblLayout", _el("tblLayout", type="fixed"))
608
+ table.autofit = False
609
+ cols = len(table.columns)
610
+ widths = widths or [width_emu // cols] * cols
611
+ for ci, column in enumerate(table.columns):
612
+ column.width = Emu(widths[ci])
613
+ for row in table.rows:
614
+ for ci, cell in enumerate(row.cells):
615
+ cell.width = Emu(widths[ci])
616
+
617
+
618
+ def no_borders(table):
619
+ tbl_set(table, "tblBorders", _borders("tblBorders", {s: None for s in ("top", "left", "bottom", "right", "insideH", "insideV")}))
620
+
621
+
622
+ # ── Containers ──────────────────────────────────────────────────────────────
623
+
624
+ class _FrameSection:
625
+ """Stands in for a section where shape_table reads the usable width (a cell or a column)."""
626
+
627
+ def __init__(self, width: int):
628
+ self.page_width, self.left_margin, self.right_margin = Emu(width), Emu(0), Emu(0)
629
+
630
+
631
+ class Box:
632
+ """A table cell that html_to_docx can write into as it writes into a document."""
633
+
634
+ def __init__(self, cell, width: int, doc):
635
+ self.cell, self.width, self.doc = cell, width, doc
636
+ self.sections = [_FrameSection(width)]
637
+ self.styles = doc.styles
638
+ self._fresh = True
639
+
640
+ def add_paragraph(self, text: str = "", style=None):
641
+ if self._fresh and len(self.cell.paragraphs) == 1 and not self.cell.paragraphs[0].text and not len(self.cell.tables):
642
+ p = self.cell.paragraphs[0]
643
+ if text:
644
+ p.add_run(text)
645
+ if style:
646
+ p.style = style
647
+ else:
648
+ p = self.cell.add_paragraph(text, style)
649
+ self._fresh = False
650
+ return p
651
+
652
+ def add_heading(self, text: str = "", level: int = 1):
653
+ return self.add_paragraph(text, f"Heading {level}")
654
+
655
+ def add_table(self, rows: int, cols: int):
656
+ self._fresh = False
657
+ return self.cell.add_table(rows, cols)
658
+
659
+ @property
660
+ def paragraphs(self):
661
+ return self.cell.paragraphs
662
+
663
+
664
+ def frame_width(doc) -> int:
665
+ s = doc.sections[-1]
666
+ return int(s.page_width - s.left_margin - s.right_margin)
667
+
668
+
669
+ def frame_height(doc) -> int:
670
+ s = doc.sections[-1]
671
+ return int(s.page_height - s.top_margin - s.bottom_margin)
672
+
673
+
674
+ def span(doc, n: int, of: int = 12, width: int | None = None) -> int:
675
+ """n of 12 grid columns with a 4 mm gutter (docx-spec D1.3)."""
676
+ w = width or frame_width(doc)
677
+ gutter = Mm(4)
678
+ col = (w - (of - 1) * gutter) / of
679
+ return int(n * col + (n - 1) * gutter)
680
+
681
+
682
+ # ── Document setup: page, styles, fonts ─────────────────────────────────────
683
+
684
+ def set_page(section, T: Tonality):
685
+ size = ((T.docx.get("page") or {}).get("size", "A4"))
686
+ section.page_width, section.page_height = (Mm(215.9), Mm(279.4)) if size == "Letter" else (Mm(210), Mm(297))
687
+ top, bottom, left, right = T.margins_mm
688
+ section.top_margin, section.bottom_margin, section.left_margin, section.right_margin = Mm(top), Mm(bottom), Mm(left), Mm(right)
689
+ section.header_distance = section.footer_distance = Mm(min(12, top - 10))
690
+
691
+
692
+ def _style(doc, name: str, base: str | None = "Normal"):
693
+ from docx.enum.style import WD_STYLE_TYPE
694
+ try:
695
+ return doc.styles[name]
696
+ except KeyError:
697
+ st = doc.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH)
698
+ if base:
699
+ st.base_style = doc.styles[base]
700
+ return st
701
+
702
+
703
+ def _fmt(st, size=None, colour=None, bold=None, italic=False, before=None, after=None, line=None, keep=None, font=None):
704
+ if size:
705
+ st.font.size = Pt(size)
706
+ if colour:
707
+ st.font.color.rgb = RGBColor.from_string(colour)
708
+ if bold is not None:
709
+ st.font.bold = bold
710
+ st.font.italic = italic
711
+ pf = st.paragraph_format
712
+ if before is not None:
713
+ pf.space_before = Pt(before)
714
+ if after is not None:
715
+ pf.space_after = Pt(after)
716
+ if line is not None:
717
+ pf.line_spacing = line
718
+ if keep is not None:
719
+ pf.keep_with_next = keep
720
+ if font:
721
+ set_run_fonts(st.element.get_or_add_rPr(), *font)
722
+
723
+
724
+ def korean_line_breaking(doc):
725
+ """Hangul wraps between words (어절) in Word: wordWrap on, kinsoku on, and the text marked Korean. The probe
726
+ through Word itself (task-12b/word-probe) broke between syllables with wordWrap 0 and between words with
727
+ wordWrap 1 or none; LibreOffice breaks between syllables whatever the paragraph says."""
728
+ ppr = doc.styles["Normal"].element.get_or_add_pPr()
729
+ _put(ppr, _el("kinsoku", val=1), PPR_ORDER)
730
+ _put(ppr, _el("wordWrap", val=1), PPR_ORDER)
731
+ rpr = doc.styles.element.find(qn("w:docDefaults")).find(qn("w:rPrDefault")).find(qn("w:rPr"))
732
+ lang = rpr.find(qn("w:lang"))
733
+ if lang is None:
734
+ lang = _put(rpr, _el("lang"), RPR_ORDER)
735
+ lang.set(qn("w:eastAsia"), "ko-KR")
736
+
737
+
738
+ def setup_styles(doc, T: Tonality):
739
+ f = T.fonts
740
+ body_font = (f["latin"], f["hangul"])
741
+ head_font = (f["heading"], f["hangul"])
742
+ ink, muted = T.colour("ink"), T.colour("ink_muted")
743
+ after = (5 if T.locale != "en" else 4) if T.tight else (6 if T.locale != "en" else 5) # paragraphs part by space, never by space and an indent
744
+ normal = doc.styles["Normal"]
745
+ _fmt(normal, T.body_pt, ink, None, False, 0, after, T.leading, None, body_font)
746
+ normal.paragraph_format.widow_control = True
747
+ normal.paragraph_format.first_line_indent = Pt(0)
748
+ normal.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY if T.justify else WD_ALIGN_PARAGRAPH.LEFT
749
+ sizes = T.sizes
750
+ # Levels part by weight and space (space above about twice the space below), never by colour.
751
+ steps = ((1, 12, 5), (2, 10, 4), (3, 9, 3), (4, 8, 3)) if T.tight else ((1, 22, 9), (2, 15, 6), (3, 11, 4), (4, 9, 3))
752
+ for level, before, below in steps:
753
+ st = doc.styles[f"Heading {level}"]
754
+ _fmt(st, sizes[f"h{level}"], ink, True, False, before, below, T.line(1.3, f["heading"]), True, head_font)
755
+ st.paragraph_format.left_indent = Pt(0)
756
+ st.paragraph_format.first_line_indent = Pt(0)
757
+ st.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
758
+ if T.design.get("h1_rule") == "above":
759
+ # Brief: an unnumbered section opens under a full-width ink hairline instead of a number.
760
+ _put(doc.styles["Heading 1"].element.get_or_add_pPr(), _borders("pBdr", {"top": (4, ink, 6)}, ("top", "left", "bottom", "right", "between")), PPR_ORDER)
761
+ caption = _style(doc, "Caption")
762
+ _fmt(caption, T.table_pt, ink, False, False, 4, 4, T.line(1.4), None, body_font)
763
+ caption.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
764
+ note = _style(doc, "Source Note")
765
+ _fmt(note, T.note_pt, muted, False, False, 3, 8, T.line(1.4), None, body_font)
766
+ note.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
767
+ quote = _style(doc, "Quote")
768
+ _fmt(quote, T.body_pt, ink, False, False, 4, 6, T.leading, None, body_font)
769
+ quote.paragraph_format.left_indent = Mm(6)
770
+ for name in ("List Bullet", "List Number", "List Bullet 2", "List Number 2"):
771
+ try:
772
+ _fmt(doc.styles[name], T.body_pt, ink, None, False, 0, 3, T.leading, None, body_font)
773
+ doc.styles[name].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
774
+ except KeyError:
775
+ pass
776
+ for name in ("Title", "Subtitle", "Intense Quote", "TOC Heading"):
777
+ try:
778
+ set_run_fonts(doc.styles[name].element.get_or_add_rPr(), *head_font)
779
+ except KeyError:
780
+ pass
781
+ # Every style the document carries is in ink, including the ones this build does not use (Heading 5-9,
782
+ # Title, Intense Quote): a reader who applies them later gets no colour either.
783
+ for el in doc.styles.element.iter(qn("w:color")):
784
+ el.set(qn("w:val"), ink)
785
+ for key in ("themeColor", "themeShade", "themeTint"):
786
+ if el.get(qn(f"w:{key}")) is not None:
787
+ del el.attrib[qn(f"w:{key}")]
788
+ declare_fonts(doc, body_font, head_font, T.locale)
789
+ if T.locale != "en":
790
+ korean_line_breaking(doc)
791
+
792
+
793
+ def setup_component_styles(doc, T: Tonality):
794
+ """Only the styles the components need, for a document whose other styles belong to a publisher."""
795
+ _fmt(_style(doc, "Source Note"), T.note_pt, T.colour("ink_muted"), False, False, 3, 8, 1.2)
796
+
797
+
798
+ def declare_fonts(doc, body_font: tuple, head_font: tuple, locale: str = "en"):
799
+ """Name the pack's faces everywhere a renderer looks: the document defaults, every style that
800
+ names a font or a theme font, the theme itself and the bullet glyphs of the numbering part.
801
+ Word's own defaults (Calibri, Cambria, Symbol, the theme's Hangul face) are what LibreOffice
802
+ replaced with Carlito, Caladea and Malgun Gothic before. Korean lists take a plain dash."""
803
+ styles = doc.styles.element
804
+ defaults = styles.find(qn("w:docDefaults"))
805
+ rpr = defaults.find(qn("w:rPrDefault")).find(qn("w:rPr"))
806
+ set_run_fonts(rpr, *body_font)
807
+ for st in styles.findall(qn("w:style")):
808
+ r = st.find(qn("w:rPr"))
809
+ rf = r.find(qn("w:rFonts")) if r is not None else None
810
+ if rf is None:
811
+ continue
812
+ if (rf.get(qn("w:ascii")) or "").startswith("Courier"):
813
+ set_run_fonts(r, "Courier New", body_font[1])
814
+ continue
815
+ heading = (st.get(qn("w:styleId")) or "").startswith(("Heading", "Title", "Subtitle"))
816
+ set_run_fonts(r, *(head_font if heading else body_font))
817
+ for part in doc.part.package.iter_parts():
818
+ if str(part.partname).startswith("/word/theme/"):
819
+ blob = part.blob.decode("utf-8")
820
+ blob = re.sub(r'(<a:(?:latin|ea|cs) typeface=")[^"]*(")', rf"\g<1>{body_font[1]}\g<2>", blob)
821
+ blob = re.sub(r'<a:font script="[^"]*" typeface="[^"]*"/>', "", blob)
822
+ part._blob = blob.encode("utf-8")
823
+ try:
824
+ numbering = doc.part.numbering_part.element
825
+ except Exception:
826
+ return
827
+ glyphs = ["–", "–", "–"] if locale != "en" else ["•", "–", "▪"]
828
+ for lvl in numbering.iter(qn("w:lvl")):
829
+ fmt = lvl.find(qn("w:numFmt"))
830
+ if fmt is not None and fmt.get(qn("w:val")) == "bullet":
831
+ level = int(lvl.get(qn("w:ilvl"), "0"))
832
+ lvl.find(qn("w:lvlText")).set(qn("w:val"), glyphs[level % 3])
833
+ r = lvl.find(qn("w:rPr"))
834
+ if r is None:
835
+ r = OxmlElement("w:rPr")
836
+ lvl.append(r)
837
+ set_run_fonts(r, body_font[1], body_font[1])
838
+
839
+
840
+ # ── Components ──────────────────────────────────────────────────────────────
841
+
842
+ def _strip_md(text: str) -> str:
843
+ return re.sub(r"[*_`]", "", text).strip()
844
+
845
+
846
+ def _inline(p: Paragraph, text: str, size=None, colour=None, bold=None):
847
+ """Markdown bold (**…**) inside a short line, as runs."""
848
+ for i, part in enumerate(re.split(r"\*\*(.+?)\*\*", text)):
849
+ if part:
850
+ styled_run(p, part, size, colour, True if i % 2 else bold)
851
+
852
+
853
+ def _with_basis(label: str, basis: list) -> str:
854
+ """A key figure's label with its basis in brackets; a label that already ends in brackets takes the basis
855
+ inside them ("품목 (예시, 2026년 9월 기준)"), never a second pair."""
856
+ if not basis:
857
+ return label
858
+ if label.endswith(")"):
859
+ return f"{label[:-1]}, {', '.join(basis)})"
860
+ return f"{label} ({', '.join(basis)})"
861
+
862
+
863
+ def keyfigure_items(body: str, line: int) -> list:
864
+ """`- **figure** label` items; an indented `- …` under one is its basis (period and source)."""
865
+ items = []
866
+ for raw in body.split("\n"):
867
+ if not raw.strip():
868
+ continue
869
+ m = re.match(r"^(\s*)[-*]\s+(.*)$", raw)
870
+ if not m:
871
+ raise DesignError(f"line {line}: ::: keyfigures holds one list; {raw.strip()!r} is not a list item")
872
+ if m.group(1) and items:
873
+ items[-1]["basis"].append(m.group(2).strip())
874
+ continue
875
+ fm = re.match(r"^\*\*(.+?)\*\*\s*(.*)$", m.group(2))
876
+ if not fm or not re.search(r"\d", fm.group(1)):
877
+ raise DesignError(f"line {line}: a key figure is `**<figure with a number>** <label>`, got {m.group(2)!r}")
878
+ items.append({"figure": fm.group(1), "label": fm.group(2), "basis": []})
879
+ if not 1 <= len(items) <= 8:
880
+ raise DesignError(f"line {line}: ::: keyfigures takes 1 to 8 items, got {len(items)}")
881
+ return items
882
+
883
+
884
+ def add_keyfigures(ctx, container, d: Directive, width: int):
885
+ """One row of figures over a hairline in ink: the figure one step above the body, its label, its basis."""
886
+ T = ctx.T
887
+ items = keyfigure_items(d.body, d.line)
888
+ cfg = T.components.get("keyfigures") or {}
889
+ cols = min(len(items), int(d.attrs.get("cols") or cfg.get("per_row", 3)), 4)
890
+ rows = math.ceil(len(items) / cols)
891
+ table = container.add_table(rows, cols)
892
+ mark_component(table, "keyfigures")
893
+ no_borders(table)
894
+ table_width(table, width)
895
+ cell_margins(table, 5, 4, 0, 10)
896
+ for row in table.rows:
897
+ row._tr.get_or_add_trPr().append(_el("cantSplit"))
898
+ for i, item in enumerate(items):
899
+ cell = table.cell(i // cols, i % cols)
900
+ cell_set(cell, _borders("tcBorders", {"top": (4, T.colour("ink"), 0)}))
901
+ p = cell.paragraphs[0]
902
+ p.paragraph_format.space_after = Pt(1)
903
+ p.paragraph_format.line_spacing = T.line(1.2, "Pretendard")
904
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
905
+ styled_run(p, _strip_md(item["figure"]), T.keyfigure_pt, T.colour("ink"), True)
906
+ lp = cell.add_paragraph()
907
+ lp.paragraph_format.space_after = Pt(1)
908
+ lp.paragraph_format.line_spacing = T.line(1.4)
909
+ lp.alignment = WD_ALIGN_PARAGRAPH.LEFT
910
+ _inline(lp, item["label"], T.table_pt, T.colour("ink"))
911
+ for basis in item["basis"]:
912
+ bp = cell.add_paragraph()
913
+ bp.paragraph_format.space_after = Pt(0)
914
+ bp.paragraph_format.line_spacing = T.line(1.4)
915
+ bp.alignment = WD_ALIGN_PARAGRAPH.LEFT
916
+ _inline(bp, basis, T.note_pt, T.colour("ink_muted"))
917
+ for cell in table._cells[len(items):]:
918
+ cell.paragraphs[0].text = ""
919
+ # The box stays whole: every paragraph but those of the last row keeps with the next.
920
+ for row in table.rows[:-1]:
921
+ for cell in row.cells:
922
+ for q in cell.paragraphs:
923
+ q.paragraph_format.keep_with_next = True
924
+ ctx.spacer(container)
925
+ return table
926
+
927
+
928
+ def add_callout(ctx, container, d: Directive, width: int):
929
+ """One callout style per document: a ruled box in the vocabulary of the tables (0.75 pt above, 0.5 pt below, in
930
+ the pack's accent), no side stripe, no fill, the title in bold ink."""
931
+ T = ctx.T
932
+ kind = d.attrs.get("kind")
933
+ if kind not in CALLOUT_KINDS:
934
+ raise DesignError(f"line {d.line}: ::: callout needs kind= one of {', '.join(CALLOUT_KINDS)}")
935
+ table = container.add_table(1, 1)
936
+ mark_component(table, f"callout {kind}")
937
+ table_width(table, width)
938
+ no_borders(table)
939
+ cell_margins(table, 5, 5, 0, 0)
940
+ table.rows[0]._tr.get_or_add_trPr().append(_el("cantSplit"))
941
+ cell = table.cell(0, 0)
942
+ rule = T.accent_for("callout_rule")
943
+ cell_set(cell, _borders("tcBorders", {"top": (6, rule, 0), "bottom": (4, rule, 0)}))
944
+ box = Box(cell, width, ctx.doc)
945
+ label = d.attrs.get("title") or LABELS[ctx.lang][kind]
946
+ p = box.add_paragraph()
947
+ p.paragraph_format.space_after = Pt(2)
948
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
949
+ styled_run(p, label, T.body_pt, T.colour("ink"), True)
950
+ ctx.render(box, d.body)
951
+ for q in cell.paragraphs:
952
+ q.paragraph_format.keep_with_next = True
953
+ if q.paragraph_format.space_after is None or q is cell.paragraphs[-1]:
954
+ q.paragraph_format.space_after = Pt(0)
955
+ ctx.spacer(container)
956
+ return table
957
+
958
+
959
+ def add_sidebar(ctx, container, d: Directive, width: int):
960
+ """A box beside the text (Manual): a hairline down its left side, no fill, table-size text."""
961
+ T = ctx.T
962
+ cfg = T.components.get("sidebar") or {}
963
+ which = d.attrs.get("width") or cfg.get("default_width", "third")
964
+ float_side = d.attrs.get("float") or cfg.get("float", "right")
965
+ if ctx.column_count > 1:
966
+ float_side = "none"
967
+ w = width if float_side == "none" else span(ctx.doc, 6 if which == "half" else 4, width=width)
968
+ table = container.add_table(1, 1)
969
+ mark_component(table, "sidebar")
970
+ table_width(table, w)
971
+ table.rows[0]._tr.get_or_add_trPr().append(_el("cantSplit"))
972
+ no_borders(table)
973
+ cell_margins(table, 2, 2, 8, 0)
974
+ if float_side in ("right", "left"):
975
+ tbl_set(table, "tblpPr", _el("tblpPr", leftFromText=284, rightFromText=284, topFromText=57, bottomFromText=113,
976
+ vertAnchor="text", horzAnchor="margin", tblpXSpec=float_side))
977
+ cell = table.cell(0, 0)
978
+ cell_set(cell, _borders("tcBorders", {"left": (6, T.accent_for("sidebar_rule"), 0)}))
979
+ box = Box(cell, w - Mm(4), ctx.doc)
980
+ if d.attrs.get("title"):
981
+ p = box.add_paragraph()
982
+ p.paragraph_format.space_after = Pt(2)
983
+ styled_run(p, d.attrs["title"], T.table_pt, T.colour("ink"), True)
984
+ ctx.render(box, d.body, size=T.table_pt)
985
+ return table
986
+
987
+
988
+ def add_columns(ctx, d: Directive):
989
+ T = ctx.T
990
+ n = int(d.args[0]) if d.args else 2
991
+ if n not in (1, 2, 3):
992
+ raise DesignError(f"line {d.line}: ::: columns takes 1, 2 or 3, got {n}")
993
+ gap = float(d.attrs.get("gap") or T.column_gap_mm)
994
+ parts = COLUMN_BREAK.split(d.body)
995
+ if len(parts) > 1 and n > 1:
996
+ # The author placed the break: each part gets its own cell of one borderless row, tops aligned.
997
+ # A column section with a manual column break is not balanced by LibreOffice: it ran to the page
998
+ # foot and the next block started a new page.
999
+ side_by_side(ctx, parts[: n - 1] + ["\n\n".join(parts[n - 1:])], gap, d.attrs.get("rule") in ("true", "1"))
1000
+ return
1001
+ ctx.section_break(cols=n, gap=gap, rule=d.attrs.get("rule") in ("true", "1"))
1002
+ for i, part in enumerate(parts):
1003
+ if i:
1004
+ p = ctx.doc.add_paragraph()
1005
+ tiny(p)
1006
+ p.add_run().add_break(WD_BREAK.COLUMN)
1007
+ ctx.render(ctx.doc, part)
1008
+ ctx.section_break(cols=T.columns, gap=T.column_gap_mm)
1009
+
1010
+
1011
+ def balanced_parts(d: Directive) -> bool:
1012
+ """Two columns only when the parts are within 20 % of each other's length (A4.5); a column section
1013
+ without a break balances itself."""
1014
+ parts = [len(_strip_md(p).replace(" ", "")) for p in COLUMN_BREAK.split(d.body) if p.strip()]
1015
+ return len(parts) < 2 or min(parts) >= 0.8 * max(parts)
1016
+
1017
+
1018
+ def side_by_side(ctx, parts: list, gap_mm: float, rule: bool):
1019
+ T, doc = ctx.T, ctx.doc
1020
+ n = len(parts)
1021
+ full = frame_width(doc) if ctx.column_count == 1 else int((frame_width(doc) - Mm(T.column_gap_mm) * (ctx.column_count - 1)) / ctx.column_count)
1022
+ half = int(Mm(gap_mm) / 2)
1023
+ text_w = int((full - 2 * half * (n - 1)) / n)
1024
+ widths = [text_w + half * ((i > 0) + (i < n - 1)) for i in range(n)]
1025
+ table = doc.add_table(1, n)
1026
+ mark_component(table, "columns")
1027
+ no_borders(table)
1028
+ table_width(table, sum(widths), widths)
1029
+ cell_margins(table, 0, 0, 0, 0)
1030
+ for i, part in enumerate(parts):
1031
+ cell = table.cell(0, i)
1032
+ mar = _el("tcMar")
1033
+ mar.append(_el("left", w=int(half / 635) if i else 0, type="dxa"))
1034
+ mar.append(_el("right", w=int(half / 635) if i < n - 1 else 0, type="dxa"))
1035
+ cell_set(cell, mar)
1036
+ if rule and i < n - 1:
1037
+ cell_set(cell, _borders("tcBorders", {"right": (4, T.colour("line"), 0)}))
1038
+ box = Box(cell, text_w, doc)
1039
+ ctx.render(box, part)
1040
+ ctx.spacer(doc)
1041
+ return table
1042
+
1043
+
1044
+ def settle_sidebars(doc, T: Tonality):
1045
+ """A floating sidebar needs text beside it down to its own foot. When the paragraphs before the next
1046
+ heading are shorter than the box, the next heading would start beside it, so the box stands full width
1047
+ in the flow instead."""
1048
+ full = frame_width(doc)
1049
+ lead = T.body_pt * 1.8
1050
+
1051
+ def listed(q):
1052
+ return q.find(f"{qn('w:pPr')}/{qn('w:numPr')}") is not None or "List" in (Paragraph(q, doc._body).style.name or "")
1053
+
1054
+ for tbl in doc.element.body.iter(qn("w:tbl")):
1055
+ cap = tbl.find(f"{qn('w:tblPr')}/{qn('w:tblCaption')}")
1056
+ pos = tbl.find(f"{qn('w:tblPr')}/{qn('w:tblpPr')}")
1057
+ if cap is None or cap.get(qn("w:val")) != "sidebar" or pos is None:
1058
+ continue
1059
+ w_box = int(tbl.find(f"{qn('w:tblPr')}/{qn('w:tblW')}").get(qn("w:w"))) * 635
1060
+ # Measured on rendered pages: box lines run about 1.9 x the table size, a list item loses its indent.
1061
+ box_h = sum(max(1, math.ceil(_advance("".join(t.text or "" for t in q.iter(qn("w:t"))), T.table_pt) / (w_box / 12700 - 16 - (18 if listed(q) else 0))))
1062
+ * T.table_pt * 1.9 + 4 for q in tbl.iter(qn("w:p"))) + 16
1063
+ beside, el = 0.0, tbl.getnext()
1064
+ while el is not None and el.tag == qn("w:p") and not _level(Paragraph(el, doc._body)):
1065
+ text = "".join(t.text or "" for t in el.iter(qn("w:t")))
1066
+ if text.strip():
1067
+ beside += math.ceil(_advance(text, T.body_pt) * 0.9 / ((full - w_box) / 12700 - 12 - (18 if listed(el) else 0))) * lead + T.body_pt * 0.4
1068
+ el = el.getnext()
1069
+ if beside < box_h:
1070
+ tbl.find(qn("w:tblPr")).remove(pos)
1071
+ table_width(Table(tbl, doc._body), full)
1072
+
1073
+
1074
+ def flow_paragraphs(doc):
1075
+ """Body paragraphs in reading order, with those inside a side-by-side columns row."""
1076
+ for el in doc.element.body.iterchildren():
1077
+ if el.tag == qn("w:p"):
1078
+ yield Paragraph(el, doc._body)
1079
+ elif el.tag == qn("w:tbl"):
1080
+ cap = el.find(f"{qn('w:tblPr')}/{qn('w:tblCaption')}")
1081
+ if cap is not None and cap.get(qn("w:val")) == "columns":
1082
+ for tc in el.iter(qn("w:tc")):
1083
+ for q in tc.iterchildren(qn("w:p")):
1084
+ yield Paragraph(q, doc._body)
1085
+
1086
+
1087
+ # ── Title blocks and covers ─────────────────────────────────────────────────
1088
+
1089
+ def _byline(front: dict) -> str:
1090
+ """Author and organisation, the organisation left out when the author already names it."""
1091
+ authors = front.get("authors") or front.get("author")
1092
+ if isinstance(authors, list):
1093
+ authors = ", ".join(str(a.get("name", a)) if isinstance(a, dict) else str(a) for a in authors)
1094
+ org = front.get("organization")
1095
+ parts = [str(authors)] if authors else []
1096
+ if org and not (authors and str(org) in str(authors)):
1097
+ parts.append(str(org))
1098
+ return ", ".join(parts)
1099
+
1100
+
1101
+ def _meta_line(front: dict, lang: str = "ko") -> str:
1102
+ """The plain profile's meta line: author, organisation and date."""
1103
+ date = format_date(front["date"], lang) if front.get("date") else None
1104
+ return " ".join(v for v in (_byline(front), date) if v)
1105
+
1106
+
1107
+ def notice_tag(p: Paragraph, text: str, size: float = 8.5):
1108
+ run = styled_run(p, f" {text} ", size, NOTICE[0], True)
1109
+ run_shade(run, NOTICE[1])
1110
+ return run
1111
+
1112
+
1113
+ def notice_line(container, T: Tonality, text: str, before: float = 2, after: float = 0):
1114
+ """The sample-data notice, once, in ink at the furniture size (A4.7)."""
1115
+ p = container.add_paragraph()
1116
+ p.paragraph_format.space_before = Pt(before)
1117
+ p.paragraph_format.space_after = Pt(after)
1118
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
1119
+ styled_run(p, text, T.furniture_pt, T.colour("ink_muted"))
1120
+ return p
1121
+
1122
+
1123
+ def _abstract(ctx, container, front: dict):
1124
+ T, lab = ctx.T, LABELS[ctx.lang]
1125
+ if front.get("abstract"):
1126
+ p = container.add_paragraph()
1127
+ p.paragraph_format.space_before = Pt(8)
1128
+ p.paragraph_format.space_after = Pt(2)
1129
+ styled_run(p, lab["abstract"], T.body_pt, T.colour("ink"), True)
1130
+ a = container.add_paragraph()
1131
+ a.paragraph_format.space_after = Pt(4)
1132
+ styled_run(a, str(front["abstract"]), T.body_pt, T.colour("ink"))
1133
+ keywords = front.get("keywords")
1134
+ if keywords:
1135
+ k = container.add_paragraph()
1136
+ k.paragraph_format.space_after = Pt(4)
1137
+ k.alignment = WD_ALIGN_PARAGRAPH.LEFT
1138
+ styled_run(k, f"{lab['keywords']}: ", T.table_pt, T.colour("ink"), True)
1139
+ styled_run(k, "; ".join(str(x) for x in keywords) if isinstance(keywords, list) else str(keywords), T.table_pt, T.colour("ink"))
1140
+
1141
+
1142
+ MEMO_PAIRS = re.compile(r"^\s*(?:To|From|Date|Subject|Cc|받는 사람|보내는 사람|날짜|제목|참조)\s*:")
1143
+
1144
+
1145
+ def memo_pairs(line: str, lang: str) -> list:
1146
+ """`To: … · From: … · Subject: …` as (label, value) pairs; an English value starts with a capital."""
1147
+ pairs = [tuple(x.strip() for x in part.split(":", 1)) for part in line.split(" · ") if ":" in part]
1148
+ return [(k, v[:1].upper() + v[1:] if lang == "en" else v) for k, v in pairs]
1149
+
1150
+
1151
+ def _pairs_table(ctx, pairs: list, caption: str):
1152
+ """Label and value rows between two hairlines (the memo block and the manual's control block)."""
1153
+ doc, T = ctx.doc, ctx.T
1154
+ table = doc.add_table(len(pairs), 2)
1155
+ mark_component(table, caption)
1156
+ no_borders(table)
1157
+ tbl_set(table, "tblBorders", _borders("tblBorders", {"top": (4, T.colour("ink"), 0), "bottom": (4, T.colour("ink"), 0), "left": None, "right": None,
1158
+ "insideH": None, "insideV": None}))
1159
+ label_w = span(doc, 2)
1160
+ table_width(table, frame_width(doc), [label_w, frame_width(doc) - label_w])
1161
+ cell_margins(table, 2, 2, 0, 6)
1162
+ for i, (key, value) in enumerate(pairs):
1163
+ for ci, (text, bold) in enumerate(((key, True), (value, False))):
1164
+ p = table.cell(i, ci).paragraphs[0]
1165
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
1166
+ p.paragraph_format.space_after = Pt(0)
1167
+ styled_run(p, text, T.table_pt, T.colour("ink"), bold)
1168
+ return table
1169
+
1170
+
1171
+ def _title(ctx, front: dict, size: float, after: float = 6):
1172
+ doc, T = ctx.doc, ctx.T
1173
+ t = doc.add_paragraph()
1174
+ t.paragraph_format.space_after = Pt(after)
1175
+ t.paragraph_format.line_spacing = T.line(1.22, T.fonts["heading"])
1176
+ t.alignment = WD_ALIGN_PARAGRAPH.LEFT
1177
+ display_run(t, str(front["title"]), size, frame_width(doc), T.colour("ink"), True, (T.fonts["heading"], T.fonts["hangul"]))
1178
+ return t
1179
+
1180
+
1181
+ def title_block(ctx, front: dict, d: Directive | None):
1182
+ """Page 1 opens with the document's own title block above the body (no cover page):
1183
+
1184
+ masthead a series line (kind left, date right), the title, the subtitle, the byline, one rule, the notice;
1185
+ a journal adds affiliations, abstract and keywords
1186
+ memo a label, the subject as title, To / From / Date / Subject rows between hairlines, the notice
1187
+ manual the title and subtitle over a document-control block (document, owner, organisation, issued)
1188
+ """
1189
+ doc, T, lab = ctx.doc, ctx.T, LABELS[ctx.lang]
1190
+ kicker = d.attrs.get("kicker") if d is not None else None
1191
+ date = format_date(front["date"], ctx.lang) if front.get("date") else ""
1192
+ inner = [b for b in split_directives(d.body, d.line)] if d is not None else []
1193
+ lead = "\n".join(b for b in inner if isinstance(b, str)).strip()
1194
+ sizes = T.sizes
1195
+ if T.title_block == "memo":
1196
+ k = doc.add_paragraph()
1197
+ k.paragraph_format.space_after = Pt(4)
1198
+ styled_run(k, kicker or lab["memo"], T.table_pt, T.colour("ink_muted"), True)
1199
+ _title(ctx, front, _half(T.body_pt * 1.8), 8)
1200
+ pairs, rest = [], []
1201
+ for line in lead.split("\n"):
1202
+ if MEMO_PAIRS.match(line):
1203
+ pairs += memo_pairs(line, ctx.lang)
1204
+ elif line.strip():
1205
+ rest.append(line)
1206
+ if date and not any(k in (lab["date"], "Date", "날짜") for k, _ in pairs):
1207
+ at = next((i + 1 for i, (k, _) in enumerate(pairs) if k in (lab["from"], "From", "보내는 사람")), len(pairs))
1208
+ pairs.insert(at, (lab["date"], date))
1209
+ if pairs:
1210
+ _pairs_table(ctx, pairs, "cover memo")
1211
+ if front.get("notice"):
1212
+ notice_line(doc, T, str(front["notice"]), 4, 10)
1213
+ else:
1214
+ ctx.spacer(doc)
1215
+ if rest:
1216
+ ctx.render(doc, "\n".join(rest))
1217
+ return
1218
+ if kicker or date:
1219
+ s = doc.add_paragraph()
1220
+ s.paragraph_format.space_after = Pt(10)
1221
+ s.alignment = WD_ALIGN_PARAGRAPH.LEFT
1222
+ s.paragraph_format.tab_stops.add_tab_stop(Emu(frame_width(doc)), WD_TAB_ALIGNMENT.RIGHT)
1223
+ styled_run(s, kicker or "", T.furniture_pt + 0.5, T.colour("ink"), True)
1224
+ if date and T.title_block != "manual":
1225
+ styled_run(s, f"\t{date}", T.furniture_pt + 0.5, T.colour("ink"))
1226
+ _title(ctx, front, sizes["title"])
1227
+ if front.get("subtitle"):
1228
+ sub = doc.add_paragraph()
1229
+ sub.paragraph_format.space_after = Pt(6)
1230
+ sub.alignment = WD_ALIGN_PARAGRAPH.LEFT
1231
+ styled_run(sub, str(front["subtitle"]), sizes["h2"], T.colour("ink_muted"))
1232
+ if T.title_block == "manual":
1233
+ pairs = [(lab["doc"], str(front.get("short_title") or front["title"]))]
1234
+ for key, value in ((lab["owner"], front.get("author")), (lab["org"], front.get("organization")), (lab["issued"], date)):
1235
+ if value:
1236
+ pairs.append((key, str(value)))
1237
+ sp = doc.add_paragraph()
1238
+ tiny(sp)
1239
+ sp.paragraph_format.space_before = Pt(6)
1240
+ _pairs_table(ctx, pairs, "cover manual")
1241
+ if front.get("notice"):
1242
+ notice_line(doc, T, str(front["notice"]), 4, 0)
1243
+ else:
1244
+ byline = _byline(front)
1245
+ if byline:
1246
+ m = doc.add_paragraph()
1247
+ m.paragraph_format.space_after = Pt(2)
1248
+ m.alignment = WD_ALIGN_PARAGRAPH.LEFT
1249
+ styled_run(m, byline, T.table_pt, T.colour("ink"))
1250
+ affs = front.get("affiliations")
1251
+ if isinstance(affs, dict):
1252
+ for key in sorted(affs, key=str):
1253
+ a = doc.add_paragraph()
1254
+ a.paragraph_format.space_after = Pt(0)
1255
+ a.alignment = WD_ALIGN_PARAGRAPH.LEFT
1256
+ styled_run(a, f"{key} {affs[key]}", T.note_pt, T.colour("ink_muted"))
1257
+ if front.get("corresponding_email"):
1258
+ c = doc.add_paragraph()
1259
+ c.alignment = WD_ALIGN_PARAGRAPH.LEFT
1260
+ styled_run(c, f"* {front['corresponding_email']}", T.note_pt, T.colour("ink_muted"))
1261
+ rule = doc.add_paragraph()
1262
+ tiny(rule)
1263
+ rule.paragraph_format.space_before = Pt(4)
1264
+ para_border(rule, {"bottom": (6, T.accent_for("title_rule"), 1)})
1265
+ if front.get("notice"):
1266
+ notice_line(doc, T, str(front["notice"]), 4, 0)
1267
+ if lead:
1268
+ ctx.spacer(doc)
1269
+ lines = lead.split("\n")
1270
+ for line in [x for x in lines if MEMO_PAIRS.match(x)]:
1271
+ # To / From / Subject in a title block that is not a memo: one line, labels bold, no middle dots.
1272
+ m = doc.add_paragraph()
1273
+ m.paragraph_format.space_after = Pt(4)
1274
+ for i, (key, value) in enumerate(memo_pairs(line, ctx.lang)):
1275
+ styled_run(m, ("\u2003" if i else "") + key + " ", T.body_pt, T.colour("ink"), True)
1276
+ styled_run(m, value, T.body_pt, T.colour("ink"))
1277
+ lead = "\n".join(x for x in lines if not MEMO_PAIRS.match(x)).strip()
1278
+ before = len(doc.paragraphs)
1279
+ ctx.render(doc, lead)
1280
+ for p in doc.paragraphs[before:]:
1281
+ for r in p.runs:
1282
+ r.font.size = Pt(T.body_pt + 0.5)
1283
+ _abstract(ctx, doc, front)
1284
+ end = doc.add_paragraph()
1285
+ tiny(end)
1286
+ end.paragraph_format.space_after = Pt(10)
1287
+ ctx.title_end = end
1288
+
1289
+
1290
+ def masthead(ctx, front: dict, d: Directive | None):
1291
+ """The plain profile's title block: title, subtitle, one meta line, affiliations, abstract and keywords,
1292
+ closed by a hairline."""
1293
+ doc, T = ctx.doc, ctx.T
1294
+ tb = T.design.get("title_block_pt") or {}
1295
+ _title(ctx, front, float(tb.get("title", 22)), 4)
1296
+ if front.get("subtitle"):
1297
+ s = doc.add_paragraph()
1298
+ s.paragraph_format.space_after = Pt(4)
1299
+ styled_run(s, str(front["subtitle"]), 13, T.colour("ink_muted"))
1300
+ lead = "\n".join(b for b in split_directives(d.body, d.line) if isinstance(b, str)).strip() if d is not None else ""
1301
+ meta = _meta_line(front, ctx.lang)
1302
+ if meta:
1303
+ m = doc.add_paragraph()
1304
+ m.paragraph_format.space_after = Pt(2)
1305
+ styled_run(m, meta, T.body_pt, T.colour("ink_muted"))
1306
+ affs = front.get("affiliations")
1307
+ if isinstance(affs, dict):
1308
+ for key in sorted(affs, key=str):
1309
+ a = doc.add_paragraph()
1310
+ a.paragraph_format.space_after = Pt(0)
1311
+ styled_run(a, f"{key} {affs[key]}", T.table_pt, T.colour("ink_muted"))
1312
+ if front.get("corresponding_email"):
1313
+ c = doc.add_paragraph()
1314
+ styled_run(c, f"* {front['corresponding_email']}", T.table_pt, T.colour("ink_muted"))
1315
+ if lead:
1316
+ ctx.render(doc, lead)
1317
+ _abstract(ctx, doc, front)
1318
+ rule = doc.add_paragraph()
1319
+ tiny(rule)
1320
+ para_border(rule, {"bottom": (6, T.colour("line"), 1)})
1321
+ rule.paragraph_format.space_after = Pt(12)
1322
+
1323
+
1324
+ def cover_page(ctx, front: dict, d: Directive | None):
1325
+ """A typographic cover on page 1, its own section (A4.7): the kind, the title left-aligned in the upper
1326
+ third, one short rule, the subtitle and the lead; the byline, date and notice at the foot of the page.
1327
+ No colour block, no key figures. The body starts on the next page with page number 1."""
1328
+ doc, T = ctx.doc, ctx.T
1329
+ section = doc.sections[0]
1330
+ H, top, W = section.page_height, section.top_margin, frame_width(doc)
1331
+ kicker = d.attrs.get("kicker") if d is not None else None
1332
+ lead = "\n".join(b for b in split_directives(d.body, d.line) if isinstance(b, str)).strip() if d is not None else ""
1333
+ first = doc.paragraphs[0] if doc.paragraphs and not doc.paragraphs[0].text else doc.add_paragraph()
1334
+ tiny(first)
1335
+ first.paragraph_format.space_before = Pt(max(0, (0.22 * H - top) / 12700))
1336
+ if kicker:
1337
+ k = doc.add_paragraph()
1338
+ k.paragraph_format.space_after = Pt(10)
1339
+ k.alignment = WD_ALIGN_PARAGRAPH.LEFT
1340
+ styled_run(k, kicker, T.table_pt + 0.5, T.colour("ink"), True)
1341
+ t = doc.add_paragraph()
1342
+ t.alignment = WD_ALIGN_PARAGRAPH.LEFT # a justified paragraph would spread the broken title lines
1343
+ t.paragraph_format.space_after = Pt(12)
1344
+ t.paragraph_format.line_spacing = T.line(1.22, T.fonts["heading"])
1345
+ t.paragraph_format.right_indent = Emu(int(W - span(doc, 10)))
1346
+ display_run(t, str(front["title"]), T.sizes["title"], span(doc, 10), T.colour("ink"), True, (T.fonts["heading"], T.fonts["hangul"]))
1347
+ r = doc.add_paragraph()
1348
+ tiny(r)
1349
+ r.paragraph_format.right_indent = Emu(max(0, W - Mm(36)))
1350
+ para_border(r, {"bottom": (8, T.accent_for("title_rule"), 1)})
1351
+ r.paragraph_format.space_after = Pt(14)
1352
+ if front.get("subtitle"):
1353
+ s = doc.add_paragraph()
1354
+ s.paragraph_format.space_after = Pt(10)
1355
+ s.paragraph_format.right_indent = Emu(int(W - span(doc, 9)))
1356
+ s.alignment = WD_ALIGN_PARAGRAPH.LEFT
1357
+ styled_run(s, str(front["subtitle"]), T.sizes["h2"], T.colour("ink_muted"))
1358
+ if lead:
1359
+ before = len(doc.paragraphs)
1360
+ ctx.render(doc, lead)
1361
+ for p in doc.paragraphs[before:]:
1362
+ p.paragraph_format.right_indent = Emu(int(W - span(doc, 9)))
1363
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
1364
+ # The byline, the date and the notice stand at the foot of the cover, in the cover section's own footer.
1365
+ footer = section.footer
1366
+ footer.is_linked_to_previous = False
1367
+ lines = [(_byline(front), T.table_pt, T.colour("ink"), True), (format_date(front["date"], ctx.lang) if front.get("date") else "", T.table_pt, T.colour("ink"), False),
1368
+ (str(front.get("notice") or ""), T.furniture_pt, T.colour("ink_muted"), False)]
1369
+ fp = footer.paragraphs[0]
1370
+ for i, (text, size, colour, bold) in enumerate(x for x in lines if x[0]):
1371
+ p = fp if i == 0 else footer.add_paragraph()
1372
+ p.paragraph_format.space_after = Pt(1)
1373
+ styled_run(p, text, size, colour, bold)
1374
+ section.header.is_linked_to_previous = False
1375
+ new = doc.add_section(WD_SECTION.NEW_PAGE)
1376
+ set_page(new, T)
1377
+ _put(new._sectPr, _el("pgNumType", start=1), SECTPR_ORDER)
1378
+ for p in doc.paragraphs[-1:]:
1379
+ tiny(p)
1380
+ ctx.title_end = None
1381
+
1382
+
1383
+ # ── Post-passes over the body ───────────────────────────────────────────────
1384
+
1385
+ def _level(p: Paragraph) -> int:
1386
+ name = p.style.name if p.style is not None else ""
1387
+ m = re.match(r"Heading (\d)$", name)
1388
+ return int(m.group(1)) if m else 0
1389
+
1390
+
1391
+ def _prefix_runs(p: Paragraph, runs: list):
1392
+ """Insert runs (text, size, colour, bold) and an optional tab at the start of a paragraph."""
1393
+ anchor = p._p.find(qn("w:pPr"))
1394
+ for spec in reversed(runs):
1395
+ r = OxmlElement("w:r")
1396
+ rpr = OxmlElement("w:rPr")
1397
+ if spec == "\t":
1398
+ r.append(rpr)
1399
+ r.append(OxmlElement("w:tab"))
1400
+ else:
1401
+ text, size, colour, bold = spec
1402
+ if bold:
1403
+ _put(rpr, _el("b"), RPR_ORDER)
1404
+ _put(rpr, _el("color", val=colour), RPR_ORDER)
1405
+ if size:
1406
+ _put(rpr, _el("sz", val=int(size * 2)), RPR_ORDER)
1407
+ r.append(rpr)
1408
+ t = OxmlElement("w:t")
1409
+ t.text = text
1410
+ t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
1411
+ r.append(t)
1412
+ if anchor is not None:
1413
+ anchor.addnext(r)
1414
+ else:
1415
+ p._p.insert(0, r)
1416
+
1417
+
1418
+ def _hang(p: Paragraph, mm: float):
1419
+ ind = _el("ind", left=int(mm * 56.693), hanging=int(mm * 56.693))
1420
+ _put(p._p.get_or_add_pPr(), ind, PPR_ORDER)
1421
+ tabs = _el("tabs")
1422
+ tabs.append(_el("tab", val="left", pos=int(mm * 56.693)))
1423
+ _put(p._p.get_or_add_pPr(), tabs, PPR_ORDER)
1424
+
1425
+
1426
+ def heading_number(scheme: str, counters: list, level: int) -> str | None:
1427
+ """Plain ink numbering at the heading's own size: 1 / 1.1 / 1.1.1, or the Korean institute order Ⅰ. / 1. / 가."""
1428
+ if scheme == "decimal":
1429
+ return ".".join(str(c) for c in counters[:level])
1430
+ if scheme == "roman-ko":
1431
+ n = counters[level - 1]
1432
+ if level == 1:
1433
+ return f"{ROMAN[n - 1]}." if n <= len(ROMAN) else f"{n}."
1434
+ if level == 2:
1435
+ return f"{n}."
1436
+ return f"{GANADA[n - 1]}." if n <= len(GANADA) else f"{n})"
1437
+ return None
1438
+
1439
+
1440
+ HANG_MM = {"decimal": (8, 11, 13)}
1441
+
1442
+
1443
+ def treat_headings(doc, T: Tonality):
1444
+ counters = [0, 0, 0]
1445
+ scheme = T.numbering
1446
+ numbered = []
1447
+ for p in flow_paragraphs(doc):
1448
+ level = _level(p)
1449
+ if not level or level > 3 or not p.text.strip():
1450
+ continue
1451
+ if scheme == "none" or BACK_MATTER.match(p.text.strip()):
1452
+ continue
1453
+ counters[level - 1] += 1
1454
+ for i in range(level, 3):
1455
+ counters[i] = 0
1456
+ if 0 in counters[:level]:
1457
+ continue # a level under a missing parent stays unnumbered
1458
+ number = heading_number(scheme, counters, level)
1459
+ if number and scheme == "roman-ko":
1460
+ # The institute manner: "Ⅴ. 소요 예산" with one space. A tab after a Roman numeral landed at different
1461
+ # places in LibreOffice, so the gaps after Ⅰ., Ⅳ. and Ⅴ. differed.
1462
+ _prefix_runs(p, [(number, None, T.colour("ink"), True), (" ", None, T.colour("ink"), False)])
1463
+ elif number:
1464
+ _prefix_runs(p, [(number, None, T.colour("ink"), True), "\t"])
1465
+ numbered.append((p, level, number))
1466
+ # Decimal numbers: one hang per level, wide enough for the widest number (2.10) plus a gap of about 3 mm, so
1467
+ # the heading texts of a level start on one line.
1468
+ hang = {}
1469
+ for _, level, number in numbered:
1470
+ need = _advance(number, T.sizes[f"h{level}"]) * 1.1 / 2.835 + 3
1471
+ hang[level] = max(hang.get(level, HANG_MM[scheme][level - 1]), need)
1472
+ for p, level, _ in numbered:
1473
+ _hang(p, hang[level])
1474
+
1475
+
1476
+ def bookmark_h1(doc) -> list:
1477
+ """Each numbered h1 gets a bookmark the contents list points at; returns (text, bookmark) in order."""
1478
+ out = []
1479
+ for i, p in enumerate(q for q in flow_paragraphs(doc) if _level(q) == 1 and q.text.strip()):
1480
+ name = f"_LitSec{i + 1}"
1481
+ start = _el("bookmarkStart", id=900 + i, name=name)
1482
+ end = _el("bookmarkEnd", id=900 + i)
1483
+ anchor = p._p.find(qn("w:pPr"))
1484
+ if anchor is not None:
1485
+ anchor.addnext(start)
1486
+ else:
1487
+ p._p.insert(0, start)
1488
+ p._p.append(end)
1489
+ out.append((p.text.replace("\t", " ").strip(), name))
1490
+ return out
1491
+
1492
+
1493
+ def add_contents(ctx, entries: list):
1494
+ """A short contents list after the title block: each h1, a dotted leader and its page (PAGEREF)."""
1495
+ doc, T = ctx.doc, ctx.T
1496
+ anchor = ctx.title_end
1497
+ if anchor is None or not entries:
1498
+ return
1499
+ W = frame_width(doc)
1500
+ made = []
1501
+ head = doc.add_paragraph()
1502
+ head.paragraph_format.space_after = Pt(4)
1503
+ head.paragraph_format.keep_with_next = True
1504
+ styled_run(head, LABELS[ctx.lang]["contents"], T.table_pt + 0.5, T.colour("ink"), True)
1505
+ made.append(head)
1506
+ for text, name in entries:
1507
+ p = doc.add_paragraph()
1508
+ p.paragraph_format.space_after = Pt(0)
1509
+ p.paragraph_format.line_spacing = T.line(1.6)
1510
+ p.paragraph_format.keep_with_next = True
1511
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
1512
+ p.paragraph_format.tab_stops.add_tab_stop(Emu(W), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)
1513
+ styled_run(p, f"{text}\t", T.table_pt, T.colour("ink"))
1514
+ add_field(p, f"PAGEREF {name} \\h", T.table_pt, T.colour("ink"), "")
1515
+ made.append(p)
1516
+ made[-1].paragraph_format.keep_with_next = False
1517
+ rule = doc.add_paragraph()
1518
+ tiny(rule)
1519
+ para_border(rule, {"bottom": (4, T.colour("line"), 1)})
1520
+ rule.paragraph_format.space_after = Pt(10)
1521
+ made.append(rule)
1522
+ for p in reversed(made):
1523
+ anchor._p.addnext(p._p)
1524
+
1525
+
1526
+ def summary_points(doc, T: Tonality):
1527
+ """Brief: the paragraphs of the first section become numbered points ①-④, each a bold lead sentence then
1528
+ plain text (the conclusion-first summary of a briefing)."""
1529
+ paras = list(flow_paragraphs(doc))
1530
+ start = next((i for i, p in enumerate(paras) if _level(p) == 1), None)
1531
+ if start is None:
1532
+ return
1533
+ n = 0
1534
+ for p in paras[start + 1:]:
1535
+ if _level(p):
1536
+ break
1537
+ style = p.style.name if p.style is not None else ""
1538
+ text = p.text.strip()
1539
+ if not text or style != "Normal" or n >= len(CIRCLED) - 1:
1540
+ continue
1541
+ m = re.match(r"^(.+?(?:다\.|[.!?]))(\s+|$)(.*)$", text, re.S)
1542
+ lead, rest = (m.group(1), m.group(3)) if m else (text, "")
1543
+ for r in list(p.runs):
1544
+ r._r.getparent().remove(r._r)
1545
+ styled_run(p, f"{CIRCLED[n]} ", None, T.colour("ink"), True)
1546
+ styled_run(p, lead, None, T.colour("ink"), True)
1547
+ if rest:
1548
+ styled_run(p, " " + rest, None, T.colour("ink"))
1549
+ _hang(p, 5.5)
1550
+ p.paragraph_format.tab_stops.clear_all()
1551
+ n += 1
1552
+
1553
+
1554
+ def keep_short_followers(doc):
1555
+ """A heading carries at least two lines of its section: a short paragraph after it keeps with
1556
+ what follows too (docx-spec D12.2)."""
1557
+ ps = doc.paragraphs
1558
+ for i, p in enumerate(ps[:-1]):
1559
+ if _level(p) and not _level(ps[i + 1]) and len(ps[i + 1].text) < 60:
1560
+ ps[i + 1].paragraph_format.keep_with_next = True
1561
+
1562
+
1563
+ def last_line_company(doc):
1564
+ """A closing paragraph of up to about four lines does not stand alone on the last page: the block before it
1565
+ keeps with it (docx-spec Amendments 6: one paragraph on an otherwise empty last page read as left over)."""
1566
+ body = [el for el in doc.element.body.iterchildren() if el.tag in (qn("w:p"), qn("w:tbl"))]
1567
+ body = [el for el in body if el.tag == qn("w:tbl") or "".join(t.text or "" for t in el.iter(qn("w:t"))).strip()]
1568
+ if len(body) < 2 or body[-1].tag != qn("w:p") or body[-2].tag != qn("w:p"):
1569
+ return
1570
+ last, prev = Paragraph(body[-1], doc._body), Paragraph(body[-2], doc._body)
1571
+ if len(last.text) <= 400 and not _level(prev):
1572
+ prev.paragraph_format.keep_with_next = True
1573
+
1574
+
1575
+ REFERENCE_ENTRY = re.compile(r"^\[\d+\]\s")
1576
+
1577
+
1578
+ def _listed(p: Paragraph) -> bool:
1579
+ # A reference list ("[1] Author …") keeps together like any short list.
1580
+ return ((p.style is not None and p.style.name.startswith("List")) or p._p.find(f"{qn('w:pPr')}/{qn('w:numPr')}") is not None
1581
+ or bool(REFERENCE_ENTRY.match(p.text.strip())))
1582
+
1583
+
1584
+ def _column_paragraphs(doc) -> set:
1585
+ """The body paragraphs set in a section of two or more columns."""
1586
+ found, pending = set(), []
1587
+ for el in doc.element.body.iterchildren():
1588
+ if el.tag == qn("w:p"):
1589
+ pending.append(el)
1590
+ sect = el if el.tag == qn("w:sectPr") else el.find(f"{qn('w:pPr')}/{qn('w:sectPr')}") if el.tag == qn("w:p") else None
1591
+ if sect is not None:
1592
+ cols = sect.find(qn("w:cols"))
1593
+ if cols is not None and int(cols.get(qn("w:num"), "1") or 1) >= 2:
1594
+ found.update(pending)
1595
+ pending = []
1596
+ return found
1597
+
1598
+
1599
+ def keep_short_lists(doc, most: int = 6):
1600
+ """A list of up to six items reads as one block: every item but the last keeps with the next, and a lead-in of
1601
+ a line or two right before it ("다음 단계는 아래와 같다.") keeps with the list (docx-spec Amendments 6). In a
1602
+ column the block moved whole and left the column before it a third empty: there the list keeps its first two
1603
+ items with the lead-in and its last two together, and may break between them (docx-spec Amendments 7)."""
1604
+ body = list(doc.element.body.iterchildren())
1605
+ in_columns = _column_paragraphs(doc)
1606
+ run = []
1607
+
1608
+ def close():
1609
+ if 2 <= len(run) <= most:
1610
+ split = len(run) >= 5 and run[0]._p in in_columns
1611
+ for k, q in enumerate(run[:-1]):
1612
+ q.paragraph_format.keep_with_next = not split or k == 0 or k == len(run) - 2
1613
+ first = run[0]._p.getprevious()
1614
+ if first is not None and first.tag == qn("w:p"):
1615
+ lead = Paragraph(first, doc._body)
1616
+ if lead.text.strip() and not _level(lead) and not _listed(lead) and len(lead.text) <= 160:
1617
+ lead.paragraph_format.keep_with_next = True
1618
+ run.clear()
1619
+
1620
+ for el in body:
1621
+ if el.tag == qn("w:p"):
1622
+ p = Paragraph(el, doc._body)
1623
+ if _listed(p) and p.text.strip():
1624
+ run.append(p)
1625
+ continue
1626
+ close()
1627
+ close()
1628
+
1629
+
1630
+ def keep_heading_with_table(doc):
1631
+ """A heading whose first block is a short lead sentence and then a table keeps all three together: the heading
1632
+ and its sentence never wait at a page foot while the table opens the next page (docx-spec Amendments 6)."""
1633
+ for el in doc.element.body.iterchildren(qn("w:p")):
1634
+ p = Paragraph(el, doc._body)
1635
+ if not _level(p):
1636
+ continue
1637
+ lead = el.getnext()
1638
+ if lead is None or lead.tag != qn("w:p"):
1639
+ continue
1640
+ after = lead.getnext()
1641
+ # A caption or a units line may stand between the sentence and its table.
1642
+ def between(q):
1643
+ text = "".join(t.text or "" for t in q.iter(qn("w:t"))).strip()
1644
+ return q.tag == qn("w:p") and bool(TABLE_CAPTION.match(text) or text.startswith(("(단위", "(unit", "(Unit")))
1645
+ while after is not None and between(after):
1646
+ Paragraph(after, doc._body).paragraph_format.keep_with_next = True
1647
+ after = after.getnext()
1648
+ # A short lead (about two lines) and a table of up to eight body rows: a longer chain moved whole and left
1649
+ # half a page empty behind it.
1650
+ rows = len(after.findall(qn("w:tr"))) if after is not None and after.tag == qn("w:tbl") else 99
1651
+ if after is not None and after.tag == qn("w:tbl") and rows <= 9 and len(re.sub(r"\s+", "", "".join(t.text or "" for t in lead.iter(qn("w:t"))))) <= 200:
1652
+ p.paragraph_format.keep_with_next = True
1653
+ Paragraph(lead, doc._body).paragraph_format.keep_with_next = True
1654
+
1655
+
1656
+ def keep_closing_section(doc, T: Tonality):
1657
+ """A closing section of a few lines and a short list, with no table or picture, keeps whole: its paragraph
1658
+ travels with the list to the last page instead of leaving the list and a closing line alone there
1659
+ (docx-spec Amendments 7)."""
1660
+ body = [el for el in doc.element.body.iterchildren() if el.tag in (qn("w:p"), qn("w:tbl"))]
1661
+ heads = [i for i, el in enumerate(body) if el.tag == qn("w:p") and _level(Paragraph(el, doc._body))]
1662
+ if not heads:
1663
+ return
1664
+ rest = body[heads[-1] + 1:]
1665
+ if any(el.tag == qn("w:tbl") or el.find(f".//{qn('w:drawing')}") is not None for el in rest):
1666
+ return
1667
+ paras = [Paragraph(el, doc._body) for el in rest if "".join(t.text or "" for t in el.iter(qn("w:t"))).strip()]
1668
+ width = frame_width(doc) / 12700
1669
+ lines = sum(_est_lines(p.text, width, T.body_pt) for p in paras)
1670
+ if 2 <= len(paras) <= 10 and lines <= 12:
1671
+ for p in paras[:-1]:
1672
+ p.paragraph_format.keep_with_next = True
1673
+
1674
+
1675
+ def single_rule_after_boxes(doc):
1676
+ """A section that opens under a hairline right after a ruled box draws no second rule: the box's own bottom
1677
+ rule parts the two (docx-spec Amendments 6: a teal and a black rule stacked under "Fire lane")."""
1678
+ for el in doc.element.body.iterchildren(qn("w:p")):
1679
+ p = Paragraph(el, doc._body)
1680
+ prev = el.getprevious()
1681
+ # An empty spacer paragraph after the box does not part the two rules.
1682
+ while prev is not None and prev.tag == qn("w:p") and not "".join(t.text or "" for t in prev.iter(qn("w:t"))).strip() and prev.find(f".//{qn('w:drawing')}") is None:
1683
+ prev = prev.getprevious()
1684
+ if _level(p) == 1 and prev is not None and prev.tag == qn("w:tbl") and prev.find(f".//{qn('w:tcBorders')}/{qn('w:bottom')}") is not None:
1685
+ para_border(p, {"top": None})
1686
+
1687
+
1688
+ def restart_numbered_lists(doc):
1689
+ """Each numbered list counts from 1. "List Number" numbers through one style-level list, so a second
1690
+ list went on at 4; every list after the first gets its own instance with a start override."""
1691
+ try:
1692
+ style_num = doc.styles["List Number"].element.pPr.numPr.numId.val
1693
+ except (KeyError, AttributeError):
1694
+ return
1695
+ numbering = doc.part.numbering_part.element
1696
+ abstract = next((n.abstractNumId.val for n in numbering.num_lst if n.numId == style_num), None)
1697
+ if abstract is None:
1698
+ return
1699
+ seen, prev = 0, False
1700
+ for p in doc.paragraphs:
1701
+ is_item = p.style is not None and p.style.name == "List Number"
1702
+ if is_item and not prev:
1703
+ seen += 1
1704
+ num_id = None
1705
+ if seen > 1:
1706
+ num = numbering.add_num(abstract)
1707
+ num.add_lvlOverride(ilvl=0).add_startOverride(1)
1708
+ num_id = num.numId
1709
+ if is_item and seen > 1:
1710
+ p_pr = p._p.get_or_add_pPr()
1711
+ p_pr.get_or_add_numPr().get_or_add_ilvl().val = 0
1712
+ p_pr.get_or_add_numPr().get_or_add_numId().val = num_id
1713
+ prev = is_item if p.text.strip() or is_item else prev
1714
+
1715
+
1716
+ def space_after_lists(doc):
1717
+ """A paragraph that follows a list stands a paragraph's space clear of the list's last item (list items part by
1718
+ a smaller step), so the list reads as one block and the paragraph after it as the next."""
1719
+ def listed(q):
1720
+ return q.style is not None and q.style.name.startswith("List") or q._p.find(f"{qn('w:pPr')}/{qn('w:numPr')}") is not None
1721
+ prev = None
1722
+ for p in doc.paragraphs:
1723
+ if prev is not None and listed(prev) and not listed(p) and p.text.strip() and not _level(p) and p.paragraph_format.space_before in (None, Pt(0)):
1724
+ p.paragraph_format.space_before = Pt(6)
1725
+ prev = p
1726
+
1727
+
1728
+ def lone_list_items(doc):
1729
+ """A bulleted list of one item is a plain paragraph: a lone item takes no symbol (A4.10)."""
1730
+ ps = doc.paragraphs
1731
+ for i, p in enumerate(ps):
1732
+ if p.style is None or p.style.name != "List Bullet" or not p.text.strip():
1733
+ continue
1734
+ before = ps[i - 1].style.name if i and ps[i - 1].style is not None else ""
1735
+ after = ps[i + 1].style.name if i + 1 < len(ps) and ps[i + 1].style is not None else ""
1736
+ if before != "List Bullet" and after != "List Bullet":
1737
+ p.style = doc.styles["Normal"]
1738
+
1739
+
1740
+ def hangul_upright(doc):
1741
+ """Hangul is emphasised by weight only, never set in italic (A4.10)."""
1742
+ for p in doc.paragraphs:
1743
+ for r in p.runs:
1744
+ if r.italic and re.search(r"[가-힣]", r.text):
1745
+ r.italic = False
1746
+
1747
+
1748
+ def style_source_lines(doc, lang: str = "en"):
1749
+ for p in doc.paragraphs:
1750
+ text = p.text.strip()
1751
+ if SOURCE_LINE.match(text) and not _level(p) and (p.style is None or p.style.name in ("Normal", "Body Text")):
1752
+ p.style = doc.styles["Source Note"]
1753
+ if lang != "en" and text.startswith("출처") and p.runs:
1754
+ # Korean tables name their source as 자료: (주: notes first, then 자료:).
1755
+ p.runs[0].text = re.sub(r"^출처(\s*[::])", r"자료\1", p.runs[0].text)
1756
+
1757
+
1758
+ def korean_captions(doc):
1759
+ """Korean captions in the institute form: <표 1> above a table, [그림 1] for a figure, the label bold."""
1760
+ for p in doc.paragraphs:
1761
+ if p.style is None or p.style.name != "Caption":
1762
+ continue
1763
+ text = p.text.strip()
1764
+ m = re.match(r"^(표|그림)\s*(\d+)[.:]\s*(.*)$", text, re.S)
1765
+ if not m:
1766
+ continue
1767
+ label = f"<표 {m.group(2)}>" if m.group(1) == "표" else f"[그림 {m.group(2)}]"
1768
+ size = next((r.font.size for r in p.runs if r.font.size), None)
1769
+ for r in list(p.runs):
1770
+ r._r.getparent().remove(r._r)
1771
+ a = p.add_run(label + " ")
1772
+ a.bold = True
1773
+ b = p.add_run(m.group(3))
1774
+ for r in (a, b):
1775
+ if size:
1776
+ r.font.size = size
1777
+
1778
+
1779
+ def english_captions(doc):
1780
+ """An English table caption keeps its label bold ("Table 1.")."""
1781
+ for p in doc.paragraphs:
1782
+ if p.style is None or p.style.name != "Caption" or not p.runs or p.runs[0].bold:
1783
+ continue
1784
+ m = re.match(r"^(Table\s*\d+[.:])(.*)$", p.text.strip(), re.S)
1785
+ if m:
1786
+ for r in list(p.runs):
1787
+ r._r.getparent().remove(r._r)
1788
+ p.add_run(m.group(1)).bold = True
1789
+ p.add_run(m.group(2))
1790
+
1791
+
1792
+ def recolour_links(doc, T: Tonality):
1793
+ for hl in doc.element.body.iter(qn("w:hyperlink")):
1794
+ for c in hl.iter(qn("w:color")):
1795
+ c.set(qn("w:val"), T.colour("ink"))
1796
+
1797
+
1798
+ def _all_tables(doc):
1799
+ for tbl in doc.element.body.iter(qn("w:tbl")):
1800
+ cap = tbl.find(f"{qn('w:tblPr')}/{qn('w:tblCaption')}")
1801
+ if cap is None:
1802
+ yield Table(tbl, doc._body)
1803
+
1804
+
1805
+ def _est_lines(text: str, width_pt: float, size: float) -> int:
1806
+ ems = sum(1.0 if "가" <= ch <= "힣" else 0.55 for ch in text)
1807
+ return max(1, math.ceil(ems * size * 1.05 / max(width_pt, 1)))
1808
+
1809
+
1810
+ NUMERIC = re.compile(r"^[+\-−±▲▼△▽]?\s*[\d.,:]+\s*(?:\([^)]*\))?\s*(?:%p?|배|x|pt|[가-힣]{1,3}|[A-Za-z]{1,3})?$")
1811
+ DASH_CELL = re.compile(r"^[—–\-]?$")
1812
+ MINUS = re.compile(r"(?:^|(?<=[\s(]))-(?=\d)")
1813
+
1814
+
1815
+ def style_table(doc, T: Tonality, table):
1816
+ """Booktabs (A4.4): a 1 pt rule above and below, 0.5 pt under the header, no verticals, no fills; the header
1817
+ bold ink; a total row bold under a 0.5 pt rule; numbers right-aligned in tabular figures."""
1818
+ ink = T.colour("ink")
1819
+ table.style = None
1820
+ rows = table.rows
1821
+ total = len(rows) > 2 and bool(TOTALS.match(rows[-1].cells[0].text.strip()))
1822
+ tbl_set(table, "tblBorders", _borders("tblBorders", {"top": (8, ink), "left": None, "bottom": (8, ink), "right": None, "insideH": None, "insideV": None}))
1823
+ cell_margins(table, 2 if T.tight else 3.5, 2 if T.tight else 3.5, 5, 5)
1824
+ cols = len(table.columns)
1825
+ numeric = []
1826
+ for ci in range(cols):
1827
+ data = [r.cells[ci].text.strip() for r in rows[1:] if ci < len(r.cells)]
1828
+ data = [t for t in data if not DASH_CELL.match(t)]
1829
+ numeric.append(bool(data) and all(NUMERIC.match(t) for t in data))
1830
+ for ri, row in enumerate(rows):
1831
+ for ci, cell in enumerate(row.cells):
1832
+ if ri == 0:
1833
+ cell_set(cell, _borders("tcBorders", {"bottom": (4, ink)}))
1834
+ elif total and ri == len(rows) - 1:
1835
+ cell_set(cell, _borders("tcBorders", {"top": (4, ink)}))
1836
+ for shd in cell._tc.findall(f"{qn('w:tcPr')}/{qn('w:shd')}"):
1837
+ shd.getparent().remove(shd)
1838
+ for p in cell.paragraphs:
1839
+ p.paragraph_format.line_spacing = T.line(1.25 if T.tight else 1.4)
1840
+ if ci < len(numeric) and numeric[ci]:
1841
+ p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1842
+ elif p.alignment in (None, WD_ALIGN_PARAGRAPH.JUSTIFY):
1843
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
1844
+ for r in p.runs:
1845
+ # A negative figure takes the minus sign, never a hyphen (docx-spec Amendments 6), Korean too.
1846
+ if ri and r.text:
1847
+ r.text = MINUS.sub("\u2212", r.text)
1848
+ r.font.size = Pt(T.table_pt)
1849
+ r.font.color.rgb = RGBColor.from_string(ink)
1850
+ if ri == 0 or (total and ri == len(rows) - 1):
1851
+ r.bold = True
1852
+ if ci < len(numeric) and numeric[ci] and ri:
1853
+ r._r.get_or_add_rPr().append(OxmlElement("w14:numSpacing", {qn("w14:val"): "tabular"}))
1854
+
1855
+
1856
+ def hoist_units(doc, table, lang: str):
1857
+ """When every unit-bearing header cell names the same unit, the unit moves to one "(단위: …)" line
1858
+ right-aligned above the table and leaves the header cells (Korean tables, A4.4)."""
1859
+ if lang == "en":
1860
+ return None
1861
+ head = table.rows[0].cells
1862
+ units = [re.search(r"\s*\(([^()]+)\)\s*$", c.text) for c in head[1:]]
1863
+ found = [u.group(1).strip() for u in units if u]
1864
+ if len(found) < 2 or len(set(found)) != 1 or len(found) != len(head) - 1:
1865
+ return None
1866
+ for cell in head[1:]:
1867
+ for p in cell.paragraphs:
1868
+ for r in p.runs:
1869
+ r.text = re.sub(r"\s*\([^()]+\)\s*$", "", r.text)
1870
+ return found[0]
1871
+
1872
+
1873
+ def fit_word_widths(table, size: float):
1874
+ """No column narrower than its longest word plus the cell margins, so "Proposed" never wraps inside the
1875
+ word; the room comes from the widest column, and the table keeps its total width."""
1876
+ cols = len(table.columns)
1877
+ widths = [c.width or 0 for c in table.rows[0].cells][:cols]
1878
+ if cols < 2 or not all(widths):
1879
+ return
1880
+ need = [0] * cols
1881
+ for row in table.rows:
1882
+ for ci, cell in enumerate(row.cells[:cols]):
1883
+ for word in re.findall(r"[^\s()]+", cell.text):
1884
+ need[ci] = max(need[ci], int(Pt(_advance(word, size) + 14)))
1885
+ short = [ci for ci in range(cols) if widths[ci] < need[ci]]
1886
+ if not short:
1887
+ return
1888
+ for ci in short:
1889
+ donor = max(range(cols), key=lambda k: widths[k] - need[k])
1890
+ give = min(need[ci] - widths[ci], max(0, widths[donor] - need[donor]))
1891
+ widths[donor] -= give
1892
+ widths[ci] += give
1893
+ table_width(table, sum(widths), widths)
1894
+
1895
+
1896
+ def balance_columns(table, size: float):
1897
+ """A text column that wraps while other columns hold their longest cell with room to spare takes that room (all of
1898
+ it when that is less than its longest cell needs, so it wraps onto fewer lines; "Harbour Road" no longer breaks);
1899
+ the table keeps its width and no column drops under its own longest cell (docx-spec Amendments 6)."""
1900
+ cols = len(table.columns)
1901
+ widths = [c.width or 0 for c in table.rows[0].cells][:cols]
1902
+ if cols < 2 or not all(widths):
1903
+ return
1904
+ # Data cells set the need; a header may take two lines (its longest word still fits, fit_word_widths).
1905
+ body = list(table.rows)[1:] or list(table.rows)
1906
+ line = [max(int(Pt(_advance(row.cells[ci].text.strip(), size) + 14)) for row in body if ci < len(row.cells)) for ci in range(cols)]
1907
+ # A donor keeps its own longest cell on one line and every word of its header whole.
1908
+ words = [max([int(Pt(_advance(w, size) + 14)) for row in table.rows if ci < len(row.cells) for w in re.findall(r"[^\s()]+", row.cells[ci].text)] or [0]) for ci in range(cols)]
1909
+ # ... and its header within three lines.
1910
+ head = list(table.rows)[0].cells
1911
+ words = [max(words[ci], int(Pt(_advance(head[ci].text.strip(), size) / 3 + 14)) if ci < len(head) else 0) for ci in range(cols)]
1912
+ spare = [max(0, widths[k] - max(line[k], words[k])) for k in range(cols)]
1913
+ changed = False
1914
+ for ci in sorted((c for c in range(cols) if widths[c] < line[c]), key=lambda c: line[c] - widths[c]):
1915
+ deficit = line[ci] - widths[ci]
1916
+ donors = [k for k in range(cols) if k != ci and spare[k] > 0]
1917
+ # The room the others can spare, all of it when it is less than the column needs: fewer lines still help.
1918
+ gain = min(deficit, sum(spare[k] for k in donors))
1919
+ if gain < Pt(12):
1920
+ continue
1921
+ left = gain
1922
+ for k in sorted(donors, key=lambda k: -spare[k]):
1923
+ give = min(spare[k], left)
1924
+ widths[k] -= give
1925
+ spare[k] -= give
1926
+ left -= give
1927
+ if not left:
1928
+ break
1929
+ widths[ci] += gain
1930
+ spare[ci] = max(0, widths[ci] - max(line[ci], words[ci]))
1931
+ changed = True
1932
+ if changed:
1933
+ table_width(table, sum(widths), widths)
1934
+
1935
+
1936
+ def boxes_clear(doc):
1937
+ """A component box (callout, sidebar) right under a paragraph or list item stands 6 pt clear of it: its top rule
1938
+ touched the line above (docx-spec Amendments 6)."""
1939
+ for el in doc.element.body.iterchildren(qn("w:tbl")):
1940
+ cap = el.find(f"{qn('w:tblPr')}/{qn('w:tblCaption')}")
1941
+ if cap is not None and (cap.get(qn("w:val")) or "").split(" ")[0] in KINDS:
1942
+ lead_in_clear(Table(el, doc._body), boxes=True)
1943
+
1944
+
1945
+ def lead_in_clear(table, boxes=False):
1946
+ """A table without a caption under a sentence stands clear of it: the sentence keeps 6 pt under itself (a table
1947
+ cannot take space above), so the header rule never touches the line above (docx-spec Amendments 6)."""
1948
+ prev = table._tbl.getprevious()
1949
+ if prev is None or prev.tag != qn("w:p"):
1950
+ return
1951
+ p = Paragraph(prev, table._parent)
1952
+ text = p.text.strip()
1953
+ if not text or (not boxes and TABLE_CAPTION.match(text)) or _level(p) or (p.style is not None and p.style.name in ("Caption", "Source Note")):
1954
+ return
1955
+ if p.paragraph_format.space_after is None or p.paragraph_format.space_after < Pt(6):
1956
+ p.paragraph_format.space_after = Pt(6)
1957
+
1958
+
1959
+ def finish_tables(doc, T: Tonality, lang: str):
1960
+ """Every data table in booktabs, its caption kept with it (with a units line under the caption when the
1961
+ unit moves out of the header), and kept on one page when it fits there."""
1962
+ frame_h = frame_height(doc) / 12700
1963
+ for table in list(_all_tables(doc)):
1964
+ prev = table._tbl.getprevious()
1965
+ caption = Paragraph(prev, table._parent) if prev is not None and prev.tag == qn("w:p") else None
1966
+ if caption is not None and TABLE_CAPTION.match(caption.text.strip()):
1967
+ caption.style = doc.styles["Caption"]
1968
+ caption.paragraph_format.keep_with_next = True
1969
+ unit = hoist_units(doc, table, lang)
1970
+ style_table(doc, T, table)
1971
+ if unit:
1972
+ p = Paragraph(OxmlElement("w:p"), table._parent)
1973
+ table._tbl.addprevious(p._p)
1974
+ p.style = doc.styles["Source Note"]
1975
+ p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1976
+ p.paragraph_format.space_before = Pt(0)
1977
+ p.paragraph_format.space_after = Pt(2)
1978
+ p.paragraph_format.keep_with_next = True
1979
+ p.add_run(f"({LABELS[lang]['unit']}: {unit})")
1980
+ if caption is not None:
1981
+ caption.paragraph_format.space_after = Pt(0)
1982
+ fit_word_widths(table, T.table_pt)
1983
+ balance_columns(table, T.table_pt)
1984
+ lead_in_clear(table)
1985
+ widths = [c.width / 12700 if c.width else 100 for c in table.rows[0].cells]
1986
+ heights = [7 + T.table_pt * 1.4 * max(_est_lines(c.text, (widths[i] if i < len(widths) else 100) - 12, T.table_pt) for i, c in enumerate(row.cells)) for row in table.rows]
1987
+ est = sum(heights)
1988
+ if est <= 0.9 * frame_h:
1989
+ # A source or note line under the table keeps with it, so it never opens the next page alone.
1990
+ nxt = table._tbl.getnext()
1991
+ noted = nxt is not None and nxt.tag == qn("w:p") and bool(SOURCE_LINE.match("".join(t.text or "" for t in nxt.iter(qn("w:t"))).strip()))
1992
+ rows = list(table.rows)
1993
+ # Spec Amendments 3: a long table (header + 6 body rows or more) may break between rows, header repeated,
1994
+ # only where a quarter of the frame or more is left: the header keeps rows worth a quarter of the frame
1995
+ # (and at least three body rows) with it, so the table can only break when moving it whole would leave
1996
+ # the page under 0.75 filled; the last three body rows stay together.
1997
+ head, filled = 0, 0.0
1998
+ while head < len(rows) and (head < 4 or filled < 0.25 * frame_h):
1999
+ filled += heights[head]
2000
+ head += 1
2001
+ if len(rows) >= 7 and head <= len(rows) - 3:
2002
+ keep = rows[:head - 1] + rows[-3:-1] + ([rows[-1]] if noted else [])
2003
+ else:
2004
+ keep = rows if noted else rows[:-1]
2005
+ for row in keep:
2006
+ for cell in row.cells:
2007
+ cell.paragraphs[0].paragraph_format.keep_with_next = True
2008
+ space_after_table(table)
2009
+
2010
+
2011
+ def space_after_table(table):
2012
+ """The text under a table stands clear of its bottom rule: a note or source line 3 pt below it, the next
2013
+ paragraph 8 pt below the table or its last note (it touched the rule)."""
2014
+ nxt = table._tbl.getnext()
2015
+ gap = 3
2016
+ while nxt is not None and nxt.tag == qn("w:p"):
2017
+ if nxt.find(f"{qn('w:pPr')}/{qn('w:sectPr')}") is not None:
2018
+ # The section break after a page-wide table in a column body: the text below starts after it.
2019
+ nxt = nxt.getnext()
2020
+ continue
2021
+ p = Paragraph(nxt, table._parent)
2022
+ note = bool(SOURCE_LINE.match(p.text.strip())) or (p.style is not None and p.style.name == "Source Note")
2023
+ if not note and _level(p):
2024
+ return
2025
+ current = p.paragraph_format.space_before
2026
+ if current is None or current.pt < (gap if note else 8):
2027
+ p.paragraph_format.space_before = Pt(gap if note else 8)
2028
+ if not note:
2029
+ return
2030
+ gap = 0
2031
+ nxt = nxt.getnext()
2032
+
2033
+
2034
+ def size_figures(doc, T: Tonality, start: int, width: int):
2035
+ shapes = list(doc.inline_shapes)[start:]
2036
+ max_h = frame_height(doc) * float((T.design.get("figure_style") or {}).get("max_height_ratio", 0.45))
2037
+ for shape in shapes:
2038
+ w, h = shape.width, shape.height
2039
+ if not w or not h:
2040
+ continue
2041
+ scale = min(width / w, max_h / h)
2042
+ shape.width, shape.height = Emu(int(w * scale)), Emu(int(h * scale))
2043
+
2044
+
2045
+ def single_spaced_figures(doc):
2046
+ """A paragraph holding a picture is single spaced: a Latin body multiple under 1 cut the top off the image."""
2047
+ for p in doc.element.body.iter(qn("w:p")):
2048
+ if p.find(f".//{qn('w:drawing')}") is not None:
2049
+ Paragraph(p, doc._body).paragraph_format.line_spacing = 1.0
2050
+
2051
+
2052
+ # ── Header and footer ───────────────────────────────────────────────────────
2053
+
2054
+ def short_title(front: dict) -> str:
2055
+ if front.get("short_title"):
2056
+ return str(front["short_title"])
2057
+ title = str(front.get("title") or "")
2058
+ if len(title) <= 40:
2059
+ return title
2060
+ cut = title[:40].rsplit(" ", 1)[0]
2061
+ return cut or title[:40]
2062
+
2063
+
2064
+ def _running_line(p: Paragraph, items: list, front: dict, T: Tonality, width: int, align: str):
2065
+ """Running-head items on one line at about 82 % of the body size, regular, in the muted ink: the first
2066
+ item at the left edge, the last at the right; a folio alone takes the pack's alignment."""
2067
+ size, muted = T.furniture_pt, T.colour("ink_muted")
2068
+ p.paragraph_format.space_before = Pt(0)
2069
+ p.paragraph_format.space_after = Pt(0)
2070
+
2071
+ def put(item):
2072
+ if item == "title":
2073
+ styled_run(p, short_title(front), size, muted)
2074
+ elif item == "folio":
2075
+ add_field(p, "PAGE", size, muted)
2076
+ elif item == "section":
2077
+ add_field(p, 'STYLEREF "Heading 1"', size, muted, "")
2078
+
2079
+ if len(items) == 1:
2080
+ p.alignment = {"center": WD_ALIGN_PARAGRAPH.CENTER, "left": WD_ALIGN_PARAGRAPH.LEFT}.get(align, WD_ALIGN_PARAGRAPH.RIGHT) if items[0] == "folio" else WD_ALIGN_PARAGRAPH.LEFT
2081
+ put(items[0])
2082
+ return
2083
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
2084
+ # The Header and Footer styles carry a centre tab mid-line; cleared, or the folio stops there.
2085
+ style = p.style
2086
+ while style is not None:
2087
+ for stop in style.paragraph_format.tab_stops:
2088
+ if stop.position < width:
2089
+ p.paragraph_format.tab_stops.add_tab_stop(stop.position, WD_TAB_ALIGNMENT.CLEAR)
2090
+ style = style.base_style
2091
+ p.paragraph_format.tab_stops.add_tab_stop(Emu(width), WD_TAB_ALIGNMENT.RIGHT)
2092
+ put(items[0])
2093
+ p.add_run("\t")
2094
+ put(items[-1])
2095
+
2096
+
2097
+ def headers(ctx, front: dict, first_body: int):
2098
+ """The running head and folio the pack names (A4.8); none on a cover page or on page 1 of a document that
2099
+ opens with its title block. The notice is never repeated here."""
2100
+ doc, T = ctx.doc, ctx.T
2101
+ section = doc.sections[first_body]
2102
+ W = frame_width(doc)
2103
+ header, footer = section.header, section.footer
2104
+ header.is_linked_to_previous = False
2105
+ footer.is_linked_to_previous = False
2106
+ rh = T.running_head
2107
+ if not first_body:
2108
+ section.different_first_page_header_footer = True
2109
+ if rh.get("header"):
2110
+ _running_line(header.paragraphs[0], rh["header"], front, T, W, rh.get("folio_align", "right"))
2111
+ if rh.get("footer"):
2112
+ _running_line(footer.paragraphs[0], rh["footer"], front, T, W, rh.get("folio_align", "right"))
2113
+
2114
+
2115
+ def neutral_headers(ctx, front: dict):
2116
+ """The plain profile: the notice tag in every header."""
2117
+ if front.get("notice"):
2118
+ notice_tag(ctx.doc.sections[0].header.paragraphs[0], str(front["notice"]))
2119
+
2120
+
2121
+ # ── The build ───────────────────────────────────────────────────────────────
2122
+
2123
+ def _plain_text(text: str) -> str:
2124
+ return re.sub(r"\s+", "", re.sub(r"[*_`#>|\-]", "", text))
2125
+
2126
+
2127
+ def estimate_pages(body: str, T: Tonality) -> float:
2128
+ """A rough page count for the component budget: characters of running text plus about one line of
2129
+ characters per table row, over the characters a page holds at the pack's size and leading."""
2130
+ rows = sum(1 for line in body.split("\n") if line.strip().startswith("|"))
2131
+ chars = len(_plain_text(body)) + rows * (40 if T.locale != "en" else 90)
2132
+ per_page = 1500 if T.locale != "en" else 3300
2133
+ return chars / per_page
2134
+
2135
+
2136
+ class Build:
2137
+ """One conversion: the document, its tokens and the Markdown renderer the converter lends it."""
2138
+
2139
+ def __init__(self, doc, T: Tonality, render_md, lang: str, filters=None):
2140
+ self.doc, self.T, self._render_md, self.lang = doc, T, render_md, lang
2141
+ self.filters = filters or (lambda s: s)
2142
+ self.column_count = T.columns
2143
+ self.kinds = []
2144
+ self.callouts_ok = None # the callouts drawn as boxes, by kind, title and text (None: every callout)
2145
+ self.keyfigures_drawn = 0
2146
+ self.body_text = ""
2147
+ self.title_end = None
2148
+ self.notes = []
2149
+
2150
+ def render(self, container, text: str, size: float | None = None):
2151
+ """Markdown (which may hold directives) into a container; figures sized to its width."""
2152
+ width = container.width if isinstance(container, Box) else frame_width(self.doc) if self.column_count == 1 else \
2153
+ int((frame_width(self.doc) - Mm(self.T.column_gap_mm) * (self.column_count - 1)) / self.column_count)
2154
+ for block in split_directives(text):
2155
+ if isinstance(block, Directive):
2156
+ self.directive(container, block, width)
2157
+ continue
2158
+ if COLUMN_BREAK.search(block):
2159
+ raise DesignError("<!-- column-break --> stands only inside ::: columns")
2160
+ block = re.sub(r"<!--.*?-->", "", block, flags=re.S)
2161
+ block = CAPTION_ATTR.sub(self._caption, block)
2162
+ if not block.strip():
2163
+ continue
2164
+ start = len(self.doc.inline_shapes)
2165
+ before = len(container.paragraphs) if size else 0
2166
+ tables = len(container.tables) if not isinstance(container, Box) else 0
2167
+ self._render_md(container, self.filters(block))
2168
+ size_figures(self.doc, self.T, start, width)
2169
+ if not isinstance(container, Box) and self.column_count > 1:
2170
+ for table in container.tables[tables:]:
2171
+ cols = [c.width or 1 for c in table.rows[0].cells]
2172
+ if len(cols) > 3:
2173
+ # Wider than a column reads: the table and its caption span the page (D6.6).
2174
+ self.span_page(table)
2175
+ full = frame_width(self.doc)
2176
+ table_width(table, full, [int(full * c / sum(cols)) for c in cols])
2177
+ else:
2178
+ # A table set in a column takes the column's width, its columns in proportion.
2179
+ table_width(table, width, [int(width * c / sum(cols)) for c in cols])
2180
+ if size:
2181
+ for p in container.paragraphs[before:]:
2182
+ for r in p.runs:
2183
+ r.font.size = Pt(size)
2184
+
2185
+ def _caption(self, m):
2186
+ style = m.group(2)
2187
+ if style not in TABLE_STYLES:
2188
+ raise DesignError(f"{{style={style}}}: table styles are {', '.join(TABLE_STYLES)}")
2189
+ if style != "booktabs" and not self.T.neutral:
2190
+ self.notes.append(f"{{style={style}}} on '{m.group(1).strip()[:30]}' is drawn as booktabs (every tonality)")
2191
+ return m.group(1)
2192
+
2193
+ def allowed(self, d: Directive) -> bool:
2194
+ """The component budget (A4.5): the pack's kinds, three kinds at most, one key-figure strip, the callouts
2195
+ chosen for the document's length, two columns only when the parts are balanced."""
2196
+ kind = d.name
2197
+ if self.T.neutral:
2198
+ return kind != "pullquote"
2199
+ if kind not in self.T.allowed_kinds:
2200
+ return False
2201
+ if kind == "keyfigures" and self.keyfigures_drawn >= 1:
2202
+ return False
2203
+ if kind == "callout" and self.callouts_ok is not None and _callout_key(d) not in self.callouts_ok:
2204
+ return False
2205
+ if kind == "columns" and not balanced_parts(d):
2206
+ return False
2207
+ if kind not in self.kinds:
2208
+ if len(self.kinds) >= 3:
2209
+ return False
2210
+ self.kinds.append(kind)
2211
+ return True
2212
+
2213
+ def directive(self, container, d: Directive, width: int):
2214
+ if d.name == "cover":
2215
+ raise DesignError(f"line {d.line}: ::: cover stands first in the document, before any other block")
2216
+ if d.name == "columns" and isinstance(container, Box):
2217
+ raise DesignError(f"line {d.line}: ::: columns stands at the top level only")
2218
+ if d.name == "pullquote" and not self.allowed(d):
2219
+ # Pull quotes are off: a sentence the body already says is left out, anything else stays as a paragraph.
2220
+ if _plain_text(d.body) in self.body_text:
2221
+ self.notes.append(f"line {d.line}: the pull quote repeats the body and is left out")
2222
+ return
2223
+ self.render(container, d.body)
2224
+ return
2225
+ if not self.allowed(d):
2226
+ # A component the direction does not use keeps its content as ordinary text.
2227
+ before = len(container.paragraphs)
2228
+ if d.attrs.get("title"):
2229
+ # A run-in head over the block's text: the space above it is a heading's, so it starts a block.
2230
+ p = container.add_paragraph()
2231
+ p.paragraph_format.keep_with_next = True
2232
+ p.paragraph_format.space_before = Pt(12)
2233
+ p.paragraph_format.space_after = Pt(2)
2234
+ styled_run(p, d.attrs["title"], None, self.T.colour("ink"), True)
2235
+ body = COLUMN_BREAK.sub("", d.body)
2236
+ if d.name == "keyfigures":
2237
+ body = "\n".join(f"- {i['figure'].join(['**', '**'])} {_with_basis(i['label'], i['basis'])}" for i in keyfigure_items(d.body, d.line))
2238
+ self.render(container, body)
2239
+ # A short block set inline (a sidebar of definitions, a figure list) stays together on one page.
2240
+ added = [q for q in container.paragraphs[before:] if q.text.strip()]
2241
+ if d.name in ("sidebar", "keyfigures", "callout") and len(added) <= 8:
2242
+ for q in added[:-1]:
2243
+ q.paragraph_format.keep_with_next = True
2244
+ return
2245
+ if d.name == "keyfigures":
2246
+ self.keyfigures_drawn += 1
2247
+ add_keyfigures(self, container, d, width)
2248
+ elif d.name == "callout":
2249
+ add_callout(self, container, d, width)
2250
+ elif d.name == "sidebar":
2251
+ add_sidebar(self, container, d, width)
2252
+ elif d.name == "columns":
2253
+ add_columns(self, d)
2254
+
2255
+ def spacer(self, container):
2256
+ p = container.add_paragraph()
2257
+ tiny(p)
2258
+ p.paragraph_format.space_after = Pt(8)
2259
+
2260
+ def span_page(self, table):
2261
+ """Set one table (and the caption above it) in a one-column section inside a column body."""
2262
+ sentinel = self.doc.element.body.find(qn("w:sectPr"))
2263
+
2264
+ def carrier(cols: int):
2265
+ sect = copy.deepcopy(sentinel)
2266
+ for el in sect.findall(qn("w:headerReference")) + sect.findall(qn("w:footerReference")) + sect.findall(qn("w:pgNumType")) + sect.findall(qn("w:titlePg")):
2267
+ sect.remove(el)
2268
+ _put(sect, _el("type", val="continuous"), SECTPR_ORDER)
2269
+ _put(sect, _el("cols", num=cols, space=int(self.T.column_gap_mm * 56.693)), SECTPR_ORDER)
2270
+ p = Paragraph(OxmlElement("w:p"), self.doc._body)
2271
+ tiny(p)
2272
+ _put(p._p.get_or_add_pPr(), sect, PPR_ORDER)
2273
+ return p._p
2274
+
2275
+ start = table._tbl
2276
+ prev = start.getprevious()
2277
+ if prev is not None and prev.tag == qn("w:p") and TABLE_CAPTION.match("".join(t.text or "" for t in prev.iter(qn("w:t"))).strip()):
2278
+ start = prev
2279
+ start.addprevious(carrier(self.column_count))
2280
+ # A source or note line under the table spans with it: left in the column section it opened a short
2281
+ # column at the page foot, and the heading after it stood there alone (docx-spec Amendments 7).
2282
+ end = table._tbl
2283
+ while end.getnext() is not None and end.getnext().tag == qn("w:p") and SOURCE_LINE.match("".join(t.text or "" for t in end.getnext().iter(qn("w:t"))).strip()):
2284
+ end = end.getnext()
2285
+ end.addnext(carrier(1))
2286
+
2287
+ def section_break(self, cols: int, gap: float, rule: bool = False):
2288
+ doc = self.doc
2289
+ new = doc.add_section(WD_SECTION.CONTINUOUS)
2290
+ tiny(doc.paragraphs[-1])
2291
+ # Page numbers run on through a column section; only the first body section restarts them.
2292
+ for restart in new._sectPr.findall(qn("w:pgNumType")) + new._sectPr.findall(qn("w:titlePg")):
2293
+ new._sectPr.remove(restart)
2294
+ el = _el("cols", num=cols, space=int(gap * 56.693))
2295
+ if rule:
2296
+ el.set(qn("w:sep"), "1")
2297
+ _put(new._sectPr, el, SECTPR_ORDER)
2298
+ self.column_count = cols
2299
+
2300
+ def balance_last_page(self):
2301
+ """A column body ends with a continuous break, so its last page sets the columns to an even depth instead
2302
+ of one column of text beside an empty one (docx-spec Amendments 7)."""
2303
+ cols = self.doc.element.body.find(qn("w:sectPr")).find(qn("w:cols"))
2304
+ if cols is None or int(cols.get(qn("w:num"), "1") or 1) < 2:
2305
+ return
2306
+ # LibreOffice gave up balancing when widow control held a short closing paragraph whole (docx-spec
2307
+ # Amendments 7: LitHermes example 06-journal-en kept one column beside an empty one).
2308
+ last = next((p for p in reversed(self.doc.paragraphs) if p.text.strip()), None)
2309
+ if last is not None:
2310
+ last.paragraph_format.widow_control = False
2311
+ self.section_break(1, self.T.column_gap_mm)
2312
+ # The closing section holds one hidden 1 pt paragraph: an empty one took a body line of its own, and a last
2313
+ # page whose columns could not balance spilled it onto a blank page.
2314
+ end = self.doc.add_paragraph()
2315
+ tiny(end)
2316
+ end._p.pPr.find(qn("w:rPr")).insert(0, _el("vanish"))
2317
+
2318
+
2319
+ def choose_callouts(blocks: list, T: Tonality, body: str) -> set | None:
2320
+ """The callouts drawn as boxes: about one per four pages (the pack may cap it), the decision request first,
2321
+ then warnings, then notes; the others keep their content as text."""
2322
+ if T.neutral:
2323
+ return None
2324
+ found = [b for b in blocks if isinstance(b, Directive) and b.name == "callout"]
2325
+ cap = T.components.get("callout_max")
2326
+ budget = max(1, round(estimate_pages(body, T) / 4))
2327
+ if cap is not None:
2328
+ budget = min(budget, int(cap))
2329
+ ranked = sorted(found, key=lambda b: (CALLOUT_PRIORITY.get(b.attrs.get("kind"), 3), b.line))
2330
+ return {_callout_key(b) for b in ranked[:budget]}
2331
+
2332
+
2333
+ def _callout_key(d: Directive) -> tuple:
2334
+ return (d.attrs.get("kind"), d.attrs.get("title"), d.body.strip())
2335
+
2336
+
2337
+ def _place_after_first_paragraph(blocks: list, directive: Directive) -> list:
2338
+ """Put a directive after the first paragraph of the first section (the summary)."""
2339
+ for i, b in enumerate(blocks):
2340
+ if isinstance(b, str) and re.search(r"^#{1,2}\s", b, re.M):
2341
+ m = re.search(r"^#{1,2}\s.*$", b, re.M)
2342
+ rest = b[m.end():]
2343
+ para = re.search(r"\S.*?(?:\n\s*\n|\Z)", rest, re.S)
2344
+ if not para:
2345
+ return blocks[:i + 1] + [directive] + blocks[i + 1:]
2346
+ cut = m.end() + para.end()
2347
+ return blocks[:i] + [b[:cut], directive, b[cut:]] + blocks[i + 1:]
2348
+ return [directive] + blocks
2349
+
2350
+
2351
+ def build(doc, front: dict, body: str, T: Tonality, render_md, lang: str, filters=None):
2352
+ """Convert a body (frontmatter already parsed) into doc with the tonality T."""
2353
+ # A source short enough for about one page is set tight in any tonality, as a memo is, so a page of text never
2354
+ # spills a few lines onto a near-empty second page (docx-spec Amendments 6).
2355
+ if not T.neutral and not T.tight and estimate_pages(body, T) <= 1.0:
2356
+ T.design["spacing"] = "tight"
2357
+ print(f"Note: a source of about one page is set with tight spacing so it stays on one page")
2358
+ ctx = Build(doc, T, render_md, lang, filters)
2359
+ ctx.body_text = _plain_text(body)
2360
+ set_page(doc.sections[0], T)
2361
+ setup_styles(doc, T)
2362
+ blocks = split_directives(body)
2363
+ while blocks and isinstance(blocks[0], str) and not blocks[0].strip():
2364
+ blocks.pop(0)
2365
+ cover = blocks.pop(0) if blocks and isinstance(blocks[0], Directive) and blocks[0].name == "cover" else None
2366
+ if any(isinstance(b, Directive) and b.name == "cover" for b in blocks):
2367
+ raise DesignError("::: cover stands first in the document, before any other block")
2368
+ if cover is not None:
2369
+ _check(cover.attrs.get("variant") or "typographic", COVERS, f"line {cover.line}: cover variant")
2370
+ if not front.get("title"):
2371
+ raise DesignError(f"line {cover.line}: a cover takes its title from frontmatter title:, which is missing")
2372
+ # Key figures never stand on a cover: they move to the summary when the tonality uses them, and
2373
+ # otherwise stay out (the summary states the same numbers).
2374
+ figures = [b for b in split_directives(cover.body, cover.line) if isinstance(b, Directive) and b.name == "keyfigures"]
2375
+ if figures and not T.neutral:
2376
+ if "keyfigures" in T.allowed_kinds:
2377
+ blocks = _place_after_first_paragraph(blocks, figures[0])
2378
+ else:
2379
+ ctx.notes.append(f"{T.name} sets no key figures; the cover's figures stay in the summary text")
2380
+ if T.design.get("conclusion_first"):
2381
+ # Brief: the decision request opens the document, right under the title block.
2382
+ key = next((b for b in blocks if isinstance(b, Directive) and b.name == "callout" and b.attrs.get("kind") == "key"), None)
2383
+ if key is not None:
2384
+ blocks.remove(key)
2385
+ blocks.insert(0, key)
2386
+ ctx.callouts_ok = choose_callouts(blocks, T, body)
2387
+ first_body = 0
2388
+ if T.neutral:
2389
+ if front.get("title"):
2390
+ masthead(ctx, front, cover)
2391
+ elif T.title_block == "cover" and front.get("title"):
2392
+ cover_page(ctx, front, cover)
2393
+ first_body = 1
2394
+ elif front.get("title"):
2395
+ title_block(ctx, front, cover)
2396
+ if T.columns > 1:
2397
+ if first_body:
2398
+ _put(doc.sections[-1]._sectPr, _el("cols", num=T.columns, space=int(T.column_gap_mm * 56.693)), SECTPR_ORDER)
2399
+ else:
2400
+ ctx.column_count = 1
2401
+ ctx.section_break(T.columns, T.column_gap_mm)
2402
+ rest = "\n".join(b if isinstance(b, str) else _unsplit(b) for b in blocks)
2403
+ ctx.render(doc, rest)
2404
+ if not T.neutral:
2405
+ treat_headings(doc, T)
2406
+ if T.design.get("summary_form") == "points":
2407
+ summary_points(doc, T)
2408
+ settle_sidebars(doc, T)
2409
+ keep_short_followers(doc)
2410
+ keep_short_lists(doc)
2411
+ if T.columns == 1:
2412
+ # In a column body the chain jumped to the next column and left the one before it empty.
2413
+ keep_heading_with_table(doc)
2414
+ keep_closing_section(doc, T)
2415
+ single_rule_after_boxes(doc)
2416
+ last_line_company(doc)
2417
+ single_spaced_figures(doc)
2418
+ restart_numbered_lists(doc)
2419
+ space_after_lists(doc)
2420
+ style_source_lines(doc, lang)
2421
+ finish_tables(doc, T, lang)
2422
+ boxes_clear(doc)
2423
+ if not T.neutral:
2424
+ lone_list_items(doc)
2425
+ if lang != "en":
2426
+ korean_captions(doc)
2427
+ hangul_upright(doc)
2428
+ else:
2429
+ english_captions(doc)
2430
+ if T.design.get("contents") and estimate_pages(body, T) >= 5:
2431
+ add_contents(ctx, bookmark_h1(doc))
2432
+ recolour_links(doc, T)
2433
+ if T.neutral:
2434
+ neutral_headers(ctx, front)
2435
+ else:
2436
+ headers(ctx, front, first_body)
2437
+ if T.columns > 1:
2438
+ ctx.balance_last_page()
2439
+ for note in ctx.notes:
2440
+ print(f"Note: {note}")
2441
+ return ctx
2442
+
2443
+
2444
+ def _unsplit(d: Directive) -> str:
2445
+ """A directive written back as source, so the body renders in one ordered pass."""
2446
+ depth = 3 + max([len(m.group(1)) - 2 for m in re.finditer(r"^(:{3,})", d.body, re.M)] or [0])
2447
+ fence = ":" * depth
2448
+ attrs = " ".join([*d.args, *(f'{k}="{v}"' for k, v in d.attrs.items())])
2449
+ return f"{fence} {d.name} {attrs}\n{d.body}\n{fence}"