@litfamily/litcodex 1.0.15 → 1.0.17

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 (123) hide show
  1. package/README-Ko-KR.md +10 -10
  2. package/README.md +10 -10
  3. package/dist/install/codex.d.ts +1 -9
  4. package/dist/install/codex.js +7 -1
  5. package/dist/install/generated-skill-payload-hashes.d.ts +101 -40
  6. package/dist/install/generated-skill-payload-hashes.js +101 -40
  7. package/dist/install/index.js +1 -0
  8. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  9. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  10. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  11. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  12. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  13. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  14. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  15. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  16. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  17. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  18. package/marketplace/plugins/litcodex/skills/frontend-ui-ux/THIRD-PARTY-NOTICE.txt +0 -2
  19. package/marketplace/plugins/litcodex/skills/lit-docx/SKILL.md +16 -12
  20. package/marketplace/plugins/litcodex/skills/lit-docx/references/components.md +113 -0
  21. package/marketplace/plugins/litcodex/skills/lit-docx/references/direction-step.md +164 -0
  22. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/01-report-ko.md +95 -0
  23. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/02-brief-ko.md +45 -0
  24. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/03-manual-ko.md +105 -0
  25. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/04-proposal-ko.md +97 -0
  26. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/05-memo-en.md +34 -0
  27. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/06-journal-en.md +89 -0
  28. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/07-report-en.md +101 -0
  29. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/08-proposal-en.md +94 -0
  30. package/marketplace/plugins/litcodex/skills/lit-docx/references/examples/09-memo-ko.md +34 -0
  31. package/marketplace/plugins/litcodex/skills/lit-docx/references/page-composition.md +141 -0
  32. package/marketplace/plugins/litcodex/skills/lit-docx/references/tonalities/brief.md +70 -0
  33. package/marketplace/plugins/litcodex/skills/lit-docx/references/tonalities/journal.md +73 -0
  34. package/marketplace/plugins/litcodex/skills/lit-docx/references/tonalities/manual.md +70 -0
  35. package/marketplace/plugins/litcodex/skills/lit-docx/references/tonalities/memo.md +75 -0
  36. package/marketplace/plugins/litcodex/skills/lit-docx/references/tonalities/proposal.md +71 -0
  37. package/marketplace/plugins/litcodex/skills/lit-docx/references/tonalities/report.md +83 -0
  38. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/convert_md_to_docx.py +401 -58
  39. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/docx_craft.py +124 -1
  40. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/docx_design.py +2446 -0
  41. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/docx_layout.py +960 -0
  42. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/slop_lint.py +21 -6
  43. package/marketplace/plugins/litcodex/skills/lit-docx/templates/tonalities/brief.yaml +28 -0
  44. package/marketplace/plugins/litcodex/skills/lit-docx/templates/tonalities/journal.yaml +26 -0
  45. package/marketplace/plugins/litcodex/skills/lit-docx/templates/tonalities/manual.yaml +26 -0
  46. package/marketplace/plugins/litcodex/skills/lit-docx/templates/tonalities/memo.yaml +27 -0
  47. package/marketplace/plugins/litcodex/skills/lit-docx/templates/tonalities/proposal.yaml +27 -0
  48. package/marketplace/plugins/litcodex/skills/lit-docx/templates/tonalities/report.yaml +27 -0
  49. package/marketplace/plugins/litcodex/skills/lit-pptx/SKILL.md +12 -11
  50. package/marketplace/plugins/litcodex/skills/lit-pptx/pretendard-font/public/static/Pretendard-Bold.otf +0 -0
  51. package/marketplace/plugins/litcodex/skills/lit-pptx/pretendard-font/public/static/Pretendard-Regular.otf +0 -0
  52. package/marketplace/plugins/litcodex/skills/lit-pptx/references/anti-slop-checklist.md +33 -29
  53. package/marketplace/plugins/litcodex/skills/lit-pptx/references/authoring-guide.md +11 -2
  54. package/marketplace/plugins/litcodex/skills/lit-pptx/references/density-and-fill.md +179 -0
  55. package/marketplace/plugins/litcodex/skills/lit-pptx/references/design-system-azure.md +1 -1
  56. package/marketplace/plugins/litcodex/skills/lit-pptx/references/direction-step.md +203 -0
  57. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/01-pitch-signal-ko.md +185 -0
  58. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/02-pitch-studio-en.md +162 -0
  59. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/03-business-review-ledger-ko.md +229 -0
  60. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/04-research-talk-paper-en.md +212 -0
  61. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/05-research-keynote-night-ko.md +191 -0
  62. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/06-lecture-chalk-ko.md +175 -0
  63. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/07-data-review-night-en.md +241 -0
  64. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/08-field-report-atlas-ko.md +168 -0
  65. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/09-briefing-gazette-ko.md +219 -0
  66. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/10-status-update-ledger-en.md +157 -0
  67. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/11-portfolio-studio-ko.md +183 -0
  68. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/12-tutorial-chalk-en.md +176 -0
  69. package/marketplace/plugins/litcodex/skills/lit-pptx/references/examples/13-status-update-gazette-ko.md +157 -0
  70. package/marketplace/plugins/litcodex/skills/lit-pptx/references/interview-protocol.md +1 -1
  71. package/marketplace/plugins/litcodex/skills/lit-pptx/references/layout-families.md +210 -0
  72. package/marketplace/plugins/litcodex/skills/lit-pptx/references/title-treatments.md +146 -0
  73. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/atlas.md +113 -0
  74. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/chalk.md +115 -0
  75. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/gazette.md +118 -0
  76. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/ledger.md +129 -0
  77. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/night.md +126 -0
  78. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/paper.md +109 -0
  79. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/signal.md +121 -0
  80. package/marketplace/plugins/litcodex/skills/lit-pptx/references/tonalities/studio.md +111 -0
  81. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/compile-deck.js +65 -17
  82. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/craft_extras.py +654 -11
  83. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/embed_fonts.py +1 -1
  84. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/inventory.py +32 -2
  85. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/directive-parser.js +2 -2
  86. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/grid-resolver.js +521 -0
  87. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/layout-resolver.js +401 -16
  88. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/markdown-loader.js +6 -4
  89. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/render-adapter-html.js +2 -2
  90. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/render-adapter-pptx.js +498 -145
  91. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/render-pack.js +3558 -0
  92. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/slide-ast.js +54 -6
  93. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/lib/template-registry.js +335 -11
  94. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/office-run.mjs +2 -1
  95. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/qa_deck.py +99 -19
  96. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/validate_pptx.py +6 -1
  97. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/boilerplate_professional.css +6 -6
  98. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/enrolled/AZURE-A2Z/layout-mapping.yaml +1 -1
  99. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/enrolled/AZURE-A2Z/template.yaml +4 -1
  100. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/enrolled/AZURE-PRO/layout-mapping.yaml +1 -1
  101. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/enrolled/AZURE-PRO/template.yaml +4 -1
  102. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/atlas/pack.yaml +105 -0
  103. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/chalk/pack.yaml +110 -0
  104. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/gazette/pack.yaml +105 -0
  105. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/ledger/pack.yaml +106 -0
  106. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/night/pack.yaml +106 -0
  107. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/paper/pack.yaml +111 -0
  108. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/signal/pack.yaml +107 -0
  109. package/marketplace/plugins/litcodex/skills/lit-pptx/templates/tonalities/studio/pack.yaml +105 -0
  110. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/THIRD_PARTY_NOTICES +1 -1
  111. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/fonts.mjs +6 -6
  112. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/gate.mjs +1 -1
  113. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/stage-qa.mjs +2 -2
  114. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/runtime.md +1 -1
  115. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/stage.md +1 -1
  116. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/style-bibles.md +2 -2
  117. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/treatment.md +1 -1
  118. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/type-and-timing.md +3 -3
  119. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  120. package/package.json +2 -2
  121. package/readme-assets/badge-version.svg +1 -1
  122. package/marketplace/plugins/litcodex/skills/lit-pptx/pretendard-font/public/static/PretendardGOV-Bold.otf +0 -0
  123. package/marketplace/plugins/litcodex/skills/lit-pptx/pretendard-font/public/static/PretendardGOV-Regular.otf +0 -0
@@ -17,10 +17,17 @@ Features:
17
17
  journal design discipline: title block from YAML frontmatter, curly
18
18
  quotes, en/em dashes, nbsp before units, ellipsis, heading auto-numbering,
19
19
  booktabs tables, banned-font/style stripping, CJK font pairing.
20
+ - --tonality NAME (or frontmatter `tonality:`) builds the document in one of
21
+ the six design directions of templates/tonalities/ (docx_design.py), with
22
+ the page components written as ::: directives; --density and --variance
23
+ move the pack's dials. Without a tonality or a publisher the plain profile
24
+ runs through the same builders with neutral tokens.
20
25
  """
21
26
 
22
27
  from __future__ import annotations
28
+
23
29
  import argparse
30
+ import copy
24
31
  import re
25
32
  import sys
26
33
  from pathlib import Path
@@ -41,6 +48,7 @@ try:
41
48
  from docx.enum.style import WD_STYLE_TYPE
42
49
  from docx.oxml.ns import qn
43
50
  from docx.oxml import OxmlElement
51
+ from docx.text.paragraph import Paragraph
44
52
  except ImportError:
45
53
  print("Error: 'python-docx' library not found. Install with: pip install python-docx")
46
54
  sys.exit(1)
@@ -51,6 +59,8 @@ except ImportError:
51
59
  print("Error: 'beautifulsoup4' library not found. Install with: pip install beautifulsoup4")
52
60
  sys.exit(1)
53
61
 
62
+ import docx_design # needs the runtime's python-docx and PyYAML
63
+
54
64
 
55
65
  # ===========================================================================
56
66
  # Legacy HTML→DOCX helpers (unchanged from pre-M1 — preserved byte-for-byte)
@@ -153,10 +163,16 @@ def process_list(doc: Document, element, md_path: Path, ordered: bool = False, l
153
163
  if level > 0:
154
164
  para.paragraph_format.left_indent = Inches(0.5 * level)
155
165
 
156
- # Process direct text content
157
- for child in li.children:
166
+ # Process direct text content. Only the item's own edges are trimmed: the space after a bold lead
167
+ # ("**1,200개** 태그") belongs to the text.
168
+ children = list(li.children)
169
+ for ci, child in enumerate(children):
158
170
  if isinstance(child, NavigableString):
159
- text = str(child).strip()
171
+ text = str(child).replace("\n", " ")
172
+ if ci == 0 or getattr(children[ci - 1], "name", None) in ('ul', 'ol', 'p'):
173
+ text = text.lstrip()
174
+ if ci == len(children) - 1 or getattr(children[ci + 1], "name", None) in ('ul', 'ol', 'p'):
175
+ text = text.rstrip()
160
176
  if text:
161
177
  para.add_run(text)
162
178
  elif child.name in ('ul', 'ol'):
@@ -185,26 +201,6 @@ def process_table(doc: Document, element, md_path: Path):
185
201
 
186
202
  table = doc.add_table(rows=len(rows), cols=cols)
187
203
  table.style = 'Table Grid'
188
- table.autofit = False
189
-
190
- # Word otherwise divides every column equally and lets long prose collapse
191
- # into narrow vertical strips. Size to the usable page, with a compact label
192
- # column for the common two-column report table.
193
- section = doc.sections[-1]
194
- usable = int(section.page_width - section.left_margin - section.right_margin)
195
- if cols == 2:
196
- widths = [int(usable * 0.28), usable - int(usable * 0.28)]
197
- else:
198
- widths = [usable // cols] * cols
199
- widths[-1] += usable - sum(widths)
200
- for index, width in enumerate(widths):
201
- table.columns[index].width = width
202
- for row in table.rows:
203
- row_properties = row._tr.get_or_add_trPr()
204
- row_properties.append(OxmlElement('w:cantSplit'))
205
- for index, cell in enumerate(row.cells):
206
- cell.width = widths[index]
207
- table.rows[0]._tr.get_or_add_trPr().append(OxmlElement('w:tblHeader'))
208
204
 
209
205
  for row_idx, tr in enumerate(rows):
210
206
  cells = tr.find_all(['th', 'td'])
@@ -216,15 +212,82 @@ def process_table(doc: Document, element, md_path: Path):
216
212
  para = table_cell.paragraphs[0]
217
213
  for child in cell.children:
218
214
  process_inline_elements(para, child, md_path)
219
- para.paragraph_format.keep_together = True
220
- if row_idx == 0:
221
- para.paragraph_format.keep_with_next = True
222
215
 
223
216
  # Bold for header cells
224
217
  if cell.name == 'th':
225
218
  for run in para.runs:
226
219
  run.bold = True
227
220
 
221
+ shape_table(doc, table, [[c.get_text(" ", strip=True) for c in tr.find_all(['th', 'td'])] for tr in rows])
222
+
223
+
224
+ # A cell reads as a number when, after signs and units, only digits remain.
225
+ NUMERIC_CELL = re.compile(r"^[+\-−±▲▼△▽]?\s*[\d.,]+\s*(?:%p?|배|x|pt|[가-힣]{1,3}|[A-Za-z]{1,3})?$")
226
+
227
+
228
+ def shape_table(doc, table, texts: list[list[str]]) -> None:
229
+ """Give a table readable columns and keep it whole on the page.
230
+
231
+ Column widths follow the longest cell of each column (Hangul counted wider)
232
+ with a floor, so a short column never squeezes a long one into one word per
233
+ line. The header row repeats on a new page, a row never splits across pages,
234
+ and columns of numbers are right-aligned.
235
+ """
236
+ if not texts or not texts[0]:
237
+ return
238
+ cols = len(table.columns)
239
+ section = doc.sections[-1]
240
+ usable = section.page_width - section.left_margin - section.right_margin
241
+
242
+ def width_of(text: str) -> float:
243
+ # Hangul runs a little over twice as wide as Latin; +3 covers the cell padding.
244
+ return sum(2.3 if "\uac00" <= ch <= "\ud7a3" else 1.0 for ch in text) + 3.0
245
+
246
+ want = []
247
+ for ci in range(cols):
248
+ column = [row[ci] for row in texts if ci < len(row)]
249
+ want.append(max([width_of(t) for t in column] + [4.0]))
250
+ # Each column first gets its natural width (about 0.085 in per Latin character at
251
+ # body size, capped at 45% of the line); columns that hit the cap share what is left.
252
+ unit = Inches(0.085)
253
+ cap = usable * 0.45
254
+ natural = [min(w * unit, cap) for w in want]
255
+ capped = [ci for ci in range(cols) if want[ci] * unit > cap]
256
+ spare = usable - sum(natural)
257
+ if spare > 0 and capped:
258
+ for ci in capped:
259
+ natural[ci] += spare / len(capped)
260
+ elif spare > 0:
261
+ natural = [w + spare / cols for w in natural]
262
+ scale = usable / sum(natural)
263
+ widths = [int(w * scale) for w in natural]
264
+
265
+ table.autofit = False
266
+ for ci, column in enumerate(table.columns):
267
+ column.width = widths[ci]
268
+ for ri, row in enumerate(table.rows):
269
+ tr_pr = row._tr.get_or_add_trPr()
270
+ # Schema order puts cantSplit before trHeight and tblHeader after it.
271
+ tr_pr.insert(0, OxmlElement("w:cantSplit"))
272
+ if ri == 0:
273
+ header = OxmlElement("w:tblHeader")
274
+ tr_pr.append(header)
275
+ for ci, cell in enumerate(row.cells):
276
+ if ci < cols:
277
+ cell.width = widths[ci]
278
+ for paragraph in cell.paragraphs:
279
+ # Body line spacing (1.6 in some profiles) makes every row a double row.
280
+ paragraph.paragraph_format.line_spacing = 1.15
281
+ paragraph.paragraph_format.space_after = Pt(0)
282
+ paragraph.paragraph_format.first_line_indent = Cm(0)
283
+
284
+ for ci in range(cols):
285
+ data = [row[ci] for row in texts[1:] if ci < len(row) and row[ci].strip()]
286
+ if data and all(NUMERIC_CELL.match(t.strip()) for t in data):
287
+ for row in table.rows:
288
+ for paragraph in row.cells[ci].paragraphs:
289
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
290
+
228
291
 
229
292
  def process_code_block(doc: Document, element):
230
293
  """Process code block with monospace formatting."""
@@ -242,6 +305,26 @@ def process_code_block(doc: Document, element):
242
305
  para._p.get_or_add_pPr().append(shading)
243
306
 
244
307
 
308
+ def add_figure_caption(doc, element, para) -> None:
309
+ """An image alone in its paragraph keeps its alt text as the caption under it
310
+ ("Figure 1." / "그림 1." bold), and the image keeps with the caption."""
311
+ images = element.find_all('img')
312
+ alt = images[0].get('alt', '').strip() if len(images) == 1 else ''
313
+ if not alt or element.get_text(strip=True):
314
+ return
315
+ para.paragraph_format.keep_with_next = True
316
+ try:
317
+ caption = doc.add_paragraph(style='Caption')
318
+ except KeyError:
319
+ caption = doc.add_paragraph()
320
+ label = docx_design.FIGURE_LABEL.match(alt)
321
+ if label:
322
+ caption.add_run(label.group(1)).bold = True
323
+ caption.add_run(alt[len(label.group(1)):])
324
+ else:
325
+ caption.add_run(alt)
326
+
327
+
245
328
  def html_to_docx(html: str, doc: Document, md_path: Path):
246
329
  """Convert HTML to DOCX elements."""
247
330
  soup = BeautifulSoup(html, 'html.parser')
@@ -260,7 +343,8 @@ def html_to_docx(html: str, doc: Document, md_path: Path):
260
343
  process_inline_elements(heading, child, md_path)
261
344
 
262
345
  elif element.name == 'p':
263
- add_paragraph_with_formatting(doc, element, md_path)
346
+ para = add_paragraph_with_formatting(doc, element, md_path)
347
+ add_figure_caption(doc, element, para)
264
348
 
265
349
  elif element.name == 'ul':
266
350
  process_list(doc, element, md_path, ordered=False)
@@ -633,6 +717,111 @@ def apply_table_style(doc, design: dict) -> None:
633
717
  existing_bottom.set(qn("w:color"), "000000")
634
718
 
635
719
 
720
+ def keep_tables_with_captions(doc) -> None:
721
+ """A table caption keeps with its table, and a table that fits one page keeps its rows together
722
+ (every row but the last keeps with the next). Pagination only: text, styles and rules are unchanged."""
723
+ section = doc.sections[-1]
724
+ frame_h = (section.page_height - section.top_margin - section.bottom_margin) / 12700
725
+ for table in doc.tables:
726
+ prev = table._tbl.getprevious()
727
+ if prev is not None and prev.tag == qn("w:p") and docx_design.TABLE_CAPTION.match("".join(t.text or "" for t in prev.iter(qn("w:t"))).strip()):
728
+ Paragraph(prev, table._parent).paragraph_format.keep_with_next = True
729
+ widths = [c.width / 12700 if c.width else 100 for c in table.rows[0].cells]
730
+ est = sum(6 + 11 * 1.3 * max(docx_design._est_lines(c.text, (widths[i] if i < len(widths) else 100) - 12, 11) for i, c in enumerate(row.cells)) for row in table.rows)
731
+ if est <= 0.9 * frame_h:
732
+ for row in table.rows[:-1]:
733
+ for cell in row.cells:
734
+ cell.paragraphs[0].paragraph_format.keep_with_next = True
735
+
736
+
737
+ def publisher_spacing(doc) -> None:
738
+ """Text never touches a table or a caption: the paragraph after a table stands three quarters of a body
739
+ line clear (8 pt read as half a line), a table caption after text 8 pt, and a figure caption keeps 8 pt
740
+ under it. A paragraph after a list stands 6 pt clear of its last item; a heading keeps its own, larger space."""
741
+ body = doc.element.body
742
+ normal = doc.styles["Normal"]
743
+ size = normal.font.size.pt if normal.font.size else 11
744
+ multiple = normal.paragraph_format.line_spacing if isinstance(normal.paragraph_format.line_spacing, float) else 1.15
745
+ clear = Pt(max(8, round(size * multiple * 1.2 * 0.75)))
746
+ for el in body.iterchildren(qn("w:tbl")):
747
+ nxt = el.getnext()
748
+ if nxt is not None and nxt.tag == qn("w:p") and "".join(t.text or "" for t in nxt.iter(qn("w:t"))).strip():
749
+ para = Paragraph(nxt, doc._body)
750
+ own = para.style.paragraph_format.space_before if para.style is not None else None
751
+ fmt = para.paragraph_format
752
+ if not (own and own >= clear) and (not fmt.space_before or fmt.space_before < clear):
753
+ fmt.space_before = clear
754
+ prev = el.getprevious()
755
+ if prev is not None and prev.tag == qn("w:p") and docx_design.TABLE_CAPTION.match("".join(t.text or "" for t in prev.iter(qn("w:t"))).strip()):
756
+ fmt = Paragraph(prev, doc._body).paragraph_format
757
+ if not fmt.space_before or fmt.space_before < Pt(8):
758
+ fmt.space_before = Pt(8)
759
+ docx_design.space_after_lists(doc)
760
+ for p in doc.paragraphs:
761
+ prev = p._p.getprevious()
762
+ under_picture = prev is not None and prev.find(f".//{qn('w:drawing')}") is not None
763
+ if docx_design.FIGURE_LABEL.match(p.text.strip()) and (under_picture or (p.style is not None and p.style.name == "Caption")):
764
+ if not p.paragraph_format.space_after or p.paragraph_format.space_after < Pt(8):
765
+ p.paragraph_format.space_after = Pt(8)
766
+
767
+
768
+ def plain_table_cells(doc) -> None:
769
+ """Table cells neither hyphenate nor justify: the body may (the profile's hyphenation), but a narrow cell
770
+ broke "Pro-posed" and a justified header spread "Conversion at"."""
771
+ for table in doc.tables:
772
+ for row in table.rows:
773
+ for cell in row.cells:
774
+ for paragraph in cell.paragraphs:
775
+ p_pr = paragraph._p.get_or_add_pPr()
776
+ if p_pr.find(qn("w:suppressAutoHyphens")) is None:
777
+ p_pr.insert_element_before(OxmlElement("w:suppressAutoHyphens"), *SUPPRESS_AFTER)
778
+ if paragraph.alignment in (None, WD_ALIGN_PARAGRAPH.JUSTIFY):
779
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
780
+
781
+
782
+ SUPPRESS_AFTER = ("w:kinsoku", "w:wordWrap", "w:overflowPunct", "w:topLinePunct", "w:autoSpaceDE", "w:autoSpaceDN", "w:bidi",
783
+ "w:adjustRightInd", "w:snapToGrid", "w:spacing", "w:ind", "w:contextualSpacing", "w:mirrorIndents",
784
+ "w:suppressOverlap", "w:jc", "w:textDirection", "w:textAlignment", "w:textboxTightWrap",
785
+ "w:outlineLvl", "w:divId", "w:cnfStyle", "w:rPr", "w:sectPr", "w:pPrChange")
786
+
787
+
788
+ def page_numbers(doc, design: dict) -> None:
789
+ """The profile's page numbering (registry design.header_footer): a centred PAGE field in the footer at the
790
+ footer size, and none on the first page when the profile says so (its header keeps the notice tag)."""
791
+ hf = design.get("header_footer") or {}
792
+ if hf.get("page_numbering") != "bottom_center":
793
+ return
794
+ size = Pt(float(hf.get("footer_font_size_pt") or 9))
795
+ for index, section in enumerate(doc.sections):
796
+ if index and section.footer.is_linked_to_previous:
797
+ continue
798
+ if not hf.get("page_numbering_first_page", True) and not section.different_first_page_header_footer:
799
+ section.different_first_page_header_footer = True
800
+ first = section.first_page_header
801
+ for paragraph in section.header.paragraphs:
802
+ first._element.append(copy.deepcopy(paragraph._p))
803
+ first._element.remove(first.paragraphs[0]._p)
804
+ footer = section.footer
805
+ paragraph = footer.paragraphs[0]
806
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
807
+ run = paragraph.add_run()
808
+ run.font.size = size
809
+ for kind, text in (("begin", None), (None, " PAGE "), ("separate", None), (None, "1"), ("end", None)):
810
+ if kind:
811
+ char = OxmlElement("w:fldChar")
812
+ char.set(qn("w:fldCharType"), kind)
813
+ run._r.append(char)
814
+ elif text == " PAGE ":
815
+ instr = OxmlElement("w:instrText")
816
+ instr.set(qn("xml:space"), "preserve")
817
+ instr.text = text
818
+ run._r.append(instr)
819
+ else:
820
+ t = OxmlElement("w:t")
821
+ t.text = text
822
+ run._r.append(t)
823
+
824
+
636
825
  def strip_banned(doc, design: dict) -> None:
637
826
  """Remove any banned font/style from runs and paragraphs."""
638
827
  banned = design.get("banned") or {}
@@ -677,6 +866,19 @@ def _set_run_fonts(run, latin: str, cjk: str | None) -> None:
677
866
  rfonts.set(qn("w:eastAsia"), cjk)
678
867
 
679
868
 
869
+ THEME_PAIRS = (("asciiTheme", "ascii"), ("hAnsiTheme", "hAnsi"), ("eastAsiaTheme", "eastAsia"), ("cstheme", "cs"))
870
+
871
+
872
+ def drop_shadowed_theme_fonts(doc) -> None:
873
+ """A style that names its face keeps no theme font beside it: Word and LibreOffice both let the theme
874
+ attribute win, so the profile's heading face (Times New Roman, Arial, Pretendard) rendered as the
875
+ theme's Calibri. Styles only; the document body is untouched."""
876
+ for rfonts in doc.styles.element.iter(qn("w:rFonts")):
877
+ for theme, named in THEME_PAIRS:
878
+ if rfonts.get(qn(f"w:{named}")) and rfonts.get(qn(f"w:{theme}")) is not None:
879
+ del rfonts.attrib[qn(f"w:{theme}")]
880
+
881
+
680
882
  def apply_cjk_font_pairing(doc, font_cfg: dict) -> None:
681
883
  body = font_cfg.get("body") or {}
682
884
  body_cjk = font_cfg.get("body_cjk") or {}
@@ -765,6 +967,17 @@ def inject_title_block(doc, frontmatter: dict, design: dict) -> None:
765
967
  )
766
968
  _add_run(tp, str(title), tb.get("title", {}).get("size_pt", 18), bold=True)
767
969
 
970
+ # Report-style frontmatter: a subtitle and one author / organisation / date line
971
+ # when there is no journal author list.
972
+ if frontmatter.get("subtitle"):
973
+ sp = _p_center(13, space_after=6)
974
+ _add_run(sp, str(frontmatter["subtitle"]), 13)
975
+ if not frontmatter.get("authors"):
976
+ meta = [str(v) for v in (frontmatter.get("author"), frontmatter.get("organization"), frontmatter.get("date")) if v]
977
+ if meta:
978
+ mp = _p_center(10.5, space_after=14)
979
+ _add_run(mp, " · ".join(meta), 10.5)
980
+
768
981
  # Authors
769
982
  authors = frontmatter.get("authors") or []
770
983
  if authors:
@@ -879,6 +1092,72 @@ def detect_locale(text: str) -> str:
879
1092
  # ===========================================================================
880
1093
 
881
1094
 
1095
+ NOTICE_INK, NOTICE_FILL = docx_design.NOTICE
1096
+
1097
+
1098
+ def _shade(element, fill: str) -> None:
1099
+ shd = OxmlElement("w:shd")
1100
+ shd.set(qn("w:val"), "clear")
1101
+ shd.set(qn("w:color"), "auto")
1102
+ shd.set(qn("w:fill"), fill)
1103
+ element.append(shd)
1104
+
1105
+
1106
+ def add_notice(doc, text: str) -> None:
1107
+ """The frontmatter `notice:` (e.g. "예시 데이터: 수치는 가정입니다") as a tag in
1108
+ every page header, so an example document cannot be mistaken for a sourced one
1109
+ on any page it is printed from. A profile whose title page has its own, empty
1110
+ header (korean-generic) gets a tinted band under the title block instead."""
1111
+ if doc.sections[0].different_first_page_header_footer:
1112
+ band = doc.add_paragraph()
1113
+ band_run = band.add_run(str(text))
1114
+ band_run.bold = True
1115
+ band_run.font.size = Pt(10.5)
1116
+ band_run.font.color.rgb = RGBColor.from_string(NOTICE_INK)
1117
+ band.paragraph_format.space_before = Pt(4)
1118
+ band.paragraph_format.space_after = Pt(14)
1119
+ _shade(band._p.get_or_add_pPr(), NOTICE_FILL)
1120
+ for index, section in enumerate(doc.sections):
1121
+ if index and section.header.is_linked_to_previous:
1122
+ continue
1123
+ header = section.header
1124
+ tag = header.paragraphs[0] if header.paragraphs and not header.paragraphs[0].text.strip() else header.add_paragraph()
1125
+ tag_run = tag.add_run(f"\u00a0{text}\u00a0")
1126
+ tag_run.bold = True
1127
+ tag_run.font.size = Pt(9)
1128
+ tag_run.font.color.rgb = RGBColor.from_string(NOTICE_INK)
1129
+ _shade(tag_run._r.get_or_add_rPr(), NOTICE_FILL)
1130
+
1131
+
1132
+ def read_source(md_path: Path) -> str:
1133
+ return md_path.read_text(encoding="utf-8")
1134
+
1135
+
1136
+ MD_EXTENSIONS = ['tables', 'fenced_code', 'nl2br', 'sane_lists']
1137
+
1138
+
1139
+ def _md_renderer(md_path: Path):
1140
+ """Markdown into a document or a component's cell, through the legacy HTML helpers."""
1141
+ def render(container, text: str) -> None:
1142
+ html_to_docx(markdown.Markdown(extensions=MD_EXTENSIONS).convert(text), container, md_path)
1143
+ return render
1144
+
1145
+
1146
+ def _typography(design: dict, lang: str = "en"):
1147
+ """The registry's micro-typography filters, for Markdown outside the directive fences; Korean text also
1148
+ writes ISO dates the Korean way (2026. 10. 1.)."""
1149
+ def apply(text: str) -> str:
1150
+ # Dates first: the dash filter would read 2026-06-30 as a number range.
1151
+ if lang != "en":
1152
+ text = docx_design.korean_dates(text)
1153
+ text = fix_dashes(text, design.get("micro_typography", {}).get("dashes"))
1154
+ text = fix_quotes(text)
1155
+ text = fix_unit_spacing(text)
1156
+ text = fix_ellipsis(text)
1157
+ return normalize_double_spaces(text)
1158
+ return apply
1159
+
1160
+
882
1161
  def convert_md_to_docx(
883
1162
  md_path: Path,
884
1163
  docx_path: Path,
@@ -886,33 +1165,43 @@ def convert_md_to_docx(
886
1165
  publisher_name: str | None = None,
887
1166
  registry_path: Path | None = None,
888
1167
  locale: str = "auto",
1168
+ tonality: str | None = None,
1169
+ density: int | None = None,
1170
+ variance: int | None = None,
889
1171
  ):
890
1172
  """Convert Markdown file to DOCX.
891
1173
 
892
- When publisher_name is None, behavior is byte-compatible with the pre-M1
893
- script: read md, convert to HTML, html_to_docx, save. Regression-guarded.
1174
+ With a tonality (argument or frontmatter `tonality:`), the document is built
1175
+ by docx_design in that design direction. Without a tonality or a publisher,
1176
+ the plain profile runs through the same builders with neutral tokens (A4,
1177
+ Pretendard, booktabs tables, notice in every header).
894
1178
 
895
1179
  When publisher_name is set, apply the full journal pipeline: registry
896
1180
  load, frontmatter parse, pre-MD filters, title-block injection, post-HTML
897
1181
  heading numbering, booktabs tables, banned stripping, CJK font pairing.
1182
+ A publisher run writes the same document.xml as before the tonality
1183
+ engine unless the source holds figures (captions) or directives.
898
1184
  """
899
1185
  if publisher_name is None:
900
- # --- Legacy code path (regression-critical: do not mutate) ---
901
- md_text = md_path.read_text(encoding='utf-8')
902
- md_converter = markdown.Markdown(extensions=[
903
- 'tables',
904
- 'fenced_code',
905
- 'nl2br',
906
- 'sane_lists',
907
- ])
908
- html = md_converter.convert(md_text)
909
- if template_path and template_path.exists():
910
- doc = Document(str(template_path))
911
- else:
912
- doc = Document()
913
- html_to_docx(html, doc, md_path)
1186
+ md_text = read_source(md_path)
1187
+ front, body = parse_frontmatter(md_text) if md_text.startswith("---") else ({}, md_text)
1188
+ name = tonality or front.get("tonality")
1189
+ lang = "en" if (detect_locale(body) if locale == "auto" else locale) == "en" else "ko"
1190
+ dials = {k: v for k, v in (("density", density if density is not None else front.get("density")),
1191
+ ("variance", variance if variance is not None else front.get("variance"))) if v is not None}
1192
+ try:
1193
+ if name:
1194
+ T = docx_design.load_tonality(name, locale=lang, **{k: int(v) for k, v in dials.items()})
1195
+ filters = _typography(T.design, lang)
1196
+ else:
1197
+ T, filters = docx_design.neutral_tonality(lang), None
1198
+ doc = Document(str(template_path)) if template_path and template_path.exists() else Document()
1199
+ docx_design.build(doc, front, body, T, _md_renderer(md_path), lang, filters)
1200
+ except docx_design.DesignError as exc:
1201
+ raise SystemExit(f"Error: {exc}") from exc
914
1202
  doc.save(str(docx_path))
915
- print(f"Successfully converted {md_path} to {docx_path}")
1203
+ label = f"tonality={T.name}, density={T.density}, variance={T.variance}" if not T.neutral else "plain profile"
1204
+ print(f"Successfully converted {md_path} to {docx_path} [{label}, locale={lang}]")
916
1205
  return
917
1206
 
918
1207
  # --- Journal workflow ---
@@ -922,24 +1211,41 @@ def convert_md_to_docx(
922
1211
  design = publisher["design"]
923
1212
  docx_font = publisher["docx"]["font"]
924
1213
 
925
- md_text = md_path.read_text(encoding="utf-8")
1214
+ md_text = read_source(md_path)
926
1215
  frontmatter, body = parse_frontmatter(md_text)
1216
+ # Without a frontmatter title, a publisher document takes its first H1 as the title.
927
1217
  if not frontmatter.get("title"):
928
1218
  first_heading = re.match(r"^\s*#\s+([^\n]+)\n+", body)
929
1219
  if first_heading:
930
1220
  frontmatter["title"] = first_heading.group(1).strip()
931
1221
  body = body[first_heading.end():]
1222
+ if frontmatter.get("tonality"):
1223
+ raise SystemExit(f"Error: frontmatter tonality: {frontmatter['tonality']} and --publisher {publisher_name} are mutually exclusive")
932
1224
 
933
1225
  # Locale detection (informational in M1; Korean rules land in M6)
934
1226
  detected_locale = detect_locale(body) if locale == "auto" else locale
935
1227
 
936
1228
  # Pre-MD micro-typography filters
1229
+ if detected_locale in ("ko", "mixed"):
1230
+ # On every path: no ISO dates in Korean text. Before the dash filter, which would
1231
+ # read 2026-06-30 as a number range.
1232
+ body = docx_design.korean_dates(body)
1233
+ if frontmatter.get("date"):
1234
+ frontmatter["date"] = docx_design.format_date(frontmatter["date"], "ko")
937
1235
  dash_rules = design.get("micro_typography", {}).get("dashes")
938
- body = fix_dashes(body, dash_rules)
939
- body = fix_quotes(body)
940
- body = fix_unit_spacing(body)
941
- body = fix_ellipsis(body)
942
- body = normalize_double_spaces(body)
1236
+
1237
+ def typeset(text: str) -> str:
1238
+ text = fix_dashes(text, dash_rules)
1239
+ text = fix_quotes(text)
1240
+ text = fix_unit_spacing(text)
1241
+ text = fix_ellipsis(text)
1242
+ return normalize_double_spaces(text)
1243
+
1244
+ # A ::: fence line holds component attributes (title="..."), and curling those quotes leaves the
1245
+ # component unparsed. Fence lines pass through untouched; each stretch between them is typeset
1246
+ # whole, so a source without components goes through the filters exactly as before.
1247
+ chunks = re.split(r"^([ \t]*:{3,}.*)$", body, flags=re.M)
1248
+ body = "".join(chunk if i % 2 else typeset(chunk) for i, chunk in enumerate(chunks))
943
1249
 
944
1250
  # Load template if available
945
1251
  template_docx = script_dir.parent / "templates" / "docx" / f"{publisher_name}.docx"
@@ -964,22 +1270,46 @@ def convert_md_to_docx(
964
1270
  # Title block (built from frontmatter) before main content
965
1271
  if frontmatter.get("title"):
966
1272
  inject_title_block(doc, frontmatter, design)
1273
+ if frontmatter.get("notice"):
1274
+ add_notice(doc, frontmatter["notice"])
1275
+ page_numbers(doc, design)
967
1276
 
968
1277
  # Main content
969
- md_converter = markdown.Markdown(extensions=[
970
- 'tables',
971
- 'fenced_code',
972
- 'nl2br',
973
- 'sane_lists',
974
- ])
975
- html = md_converter.convert(body)
976
- html_to_docx(html, doc, md_path)
1278
+ if docx_design.has_directives(body):
1279
+ # Components in a journal manuscript are drawn with neutral styling (ink and line only).
1280
+ neutral = docx_design.neutral_tonality("en" if detected_locale == "en" else "ko")
1281
+ docx_design.setup_component_styles(doc, neutral)
1282
+ ctx = docx_design.Build(doc, neutral, _md_renderer(md_path), "en" if detected_locale == "en" else "ko")
1283
+ try:
1284
+ ctx.render(doc, body)
1285
+ except docx_design.DesignError as exc:
1286
+ raise SystemExit(f"Error: {exc}") from exc
1287
+ print("Note: the ::: components are drawn with publisher-neutral styling under a publisher profile")
1288
+ else:
1289
+ md_converter = markdown.Markdown(extensions=[
1290
+ 'tables',
1291
+ 'fenced_code',
1292
+ 'nl2br',
1293
+ 'sane_lists',
1294
+ ])
1295
+ html = md_converter.convert(body)
1296
+ html_to_docx(html, doc, md_path)
977
1297
 
978
1298
  # Post-HTML design enforcement
979
1299
  apply_heading_numbering(doc, design)
980
1300
  apply_table_style(doc, design)
1301
+ keep_tables_with_captions(doc)
1302
+ plain_table_cells(doc)
1303
+ publisher_spacing(doc)
1304
+ # No column narrower than its longest word ("Cataly/st" in a narrow publisher column).
1305
+ normal = doc.styles["Normal"].font.size
1306
+ for table in doc.tables:
1307
+ docx_design.fit_word_widths(table, normal.pt if normal else 11)
1308
+ docx_design.restart_numbered_lists(doc)
1309
+ docx_design.keep_short_lists(doc)
981
1310
  strip_banned(doc, design)
982
1311
  apply_cjk_font_pairing(doc, docx_font)
1312
+ drop_shadowed_theme_fonts(doc)
983
1313
 
984
1314
  doc.save(str(docx_path))
985
1315
  print(
@@ -1009,6 +1339,14 @@ def parse_args() -> argparse.Namespace:
1009
1339
  help="Path to templates/registry.yaml (defaults to the one in this skill)",
1010
1340
  default=None,
1011
1341
  )
1342
+ parser.add_argument(
1343
+ "--tonality",
1344
+ help="Design direction from templates/tonalities/: Report, Brief, Manual, Proposal, Memo or Journal "
1345
+ "(frontmatter tonality: works too)",
1346
+ default=None,
1347
+ )
1348
+ parser.add_argument("--density", type=int, default=None, help="Density dial 1-10 (default: the pack's)")
1349
+ parser.add_argument("--variance", type=int, default=None, help="Variance dial 1-10 (default: the pack's)")
1012
1350
  parser.add_argument(
1013
1351
  "--locale",
1014
1352
  choices=("auto", "en", "ko", "mixed"),
@@ -1018,6 +1356,8 @@ def parse_args() -> argparse.Namespace:
1018
1356
  args = parser.parse_args()
1019
1357
  if args.publisher and args.template:
1020
1358
  parser.error("--publisher and --template are mutually exclusive")
1359
+ if args.publisher and args.tonality:
1360
+ parser.error("--tonality and --publisher are mutually exclusive: a tonality is a design direction, a publisher a journal profile")
1021
1361
  return args
1022
1362
 
1023
1363
 
@@ -1038,6 +1378,9 @@ def main() -> int:
1038
1378
  publisher_name=args.publisher,
1039
1379
  registry_path=registry_path,
1040
1380
  locale=args.locale,
1381
+ tonality=args.tonality,
1382
+ density=args.density,
1383
+ variance=args.variance,
1041
1384
  )
1042
1385
  return 0
1043
1386