@litfamily/litgrok 1.0.13 → 1.0.15

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