@litfamily/lithermes 1.0.16 → 1.0.18

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