Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@
All notable changes to this skill are documented here. The format is based on
[Keep a Changelog](https://keepachangelog.com/), and the project uses semantic versioning.

## [1.4.0] - 2026-07-07

Driven by two real-world failures: a delivered report whose three-line table kept the
table style's blue `firstRow` header shading, and formulas that were appended to
paragraph ends as (italic) duplicates instead of replacing the original text in place
(`……如图 1 所示。F = 44.5 km²L = 15.4 kmL/J^(1/3) = 75.1`).

### Added
- Formula workflow: an explicit **In-Place Replacement Contract** — every OMML object replaces the original token at its exact position; the plain-text original must be gone; never append math at paragraph ends, never merge adjacent expressions (`km²L`), never leave stray fragments (`mm,Cv`); self-check by comparing the math-stripped paragraph text against the original.
- Three-line table recipe: a **white-background section** — drop the `w:tblStyle` reference (header shading usually comes from the style's `firstRow` conditional format in styles.xml, invisible in document.xml), zero the `w:tblLook` flags, and clear every `w:shd` to `val=clear fill=auto`.
- Auditor checks: `TABLE_SHADING` (FAIL — direct or table-style-driven shading, resolved through the style's `basedOn` chain and `tblStylePr` conditional formats in `word/styles.xml`), `TABLE_RULES` (WARN — missing visible top/bottom rules, row-to-row `insideH` borders, or a header rule not thinner than the top/bottom rules), and `MATH_DUPLICATE` (FAIL — an OMML object's text still present as plain text in the same paragraph, i.e. append-instead-of-replace).
- Tests for all three checks; the non-compliant sample now demonstrates a shaded header cell, and the compliant sample builds a real explicit three-line table (borders + cleared shading).

### Changed
- `SKILL.md`: reading `references/three-line-table-ooxml.md` is now a required workflow step for any document with tables; the in-place replacement rule joined the formula workflow step; the Must-Fix Audit gained "any cell shading / non-white fill" and "appended/duplicated rendered math" items.
- Auditor scope now includes `word/styles.xml` (table-style shading/borders only). Standard version → 2026-07-07.

## [1.3.0] - 2026-06-29

### Added
Expand Down Expand Up @@ -55,6 +72,7 @@ All notable changes to this skill are documented here. The format is based on
### Added
- Initial release: the written standard (`SKILL.md` + `references/`), the `audit_docx_format.py` guardrail (punctuation, headings, fonts, captions, tables, citations, formulas; `--json` output and a FAIL/WARN summary), the `normalize_docx.py` safe auto-fixer, a non-compliant example, standard-library unit tests, and GitHub Actions CI.

[1.4.0]: https://github.com/AllenWang2005/Word-typesetting/releases/tag/v1.4.0
[1.3.0]: https://github.com/AllenWang2005/Word-typesetting/releases/tag/v1.3.0
[1.2.2]: https://github.com/AllenWang2005/Word-typesetting/releases/tag/v1.2.2
[1.2.1]: https://github.com/AllenWang2005/Word-typesetting/releases/tag/v1.2.1
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,22 @@ with a `FAIL/WARN` summary, and notes any per-code truncation. Checks include:
| `HEADING_NO_STYLE` | WARN | Heading-looking line that uses no Word heading style |
| `TABLE_SIZE` | FAIL | Table text or in-table formula not 五号/10.5 pt (小四 ok; never larger than body) |
| `TABLE_BORDERS` | WARN | Table has vertical/inner borders (not a three-line table) |
| `TABLE_SHADING` | FAIL | Table/cell shading, direct or from the table style's `firstRow` format (three-line tables are white) |
| `TABLE_RULES` | WARN | Missing/wrong three-line rules: no visible top/bottom rules, row-to-row insideH, or header rule not thinner |
| `CAPTION_POSITION` | WARN | Table caption below table / figure caption above figure |
| `COLOR` | WARN | Stray non-black font color (hyperlinks/theme colors excluded) |
| `CITATION_BRACKETS` | FAIL | Full-width citation brackets `[1]` |
| `CITATION_FIELDS` | FAIL | Citations exist but no `REF ref_###` fields |
| `CITATION_NO_BRACKETS` | WARN | Bare superscript number citation missing its brackets |
| `VISIBLE_LATEX` | FAIL | Visible LaTeX source instead of OMML |
| `FORMULA_TEXT` | FAIL/WARN | Plain-text formula / quantity symbol that should be OMML |
| `MATH_DUPLICATE` | FAIL | Rendered OMML whose text still exists as plain text in the same paragraph (append-instead-of-replace) |
| `FORMULA_DIGIT_ITALIC` | WARN | A number/operator in a formula is italic (only variables should be italic) |
| `EQUATION_NUMBER_CENTER` | WARN | A numbered display formula is centered (the number should be right-aligned) |

It is intentionally **domain-neutral** — no hard-coded field-specific symbol list.

**Audit scope:** the script inspects the main document story in `word/document.xml`.
**Audit scope:** the script inspects the main document story in `word/document.xml`, plus `word/styles.xml` for table-style shading and borders.
It does not audit headers, footers, footnotes, endnotes, comments, or embedded parts —
verify those visually or with a deeper OOXML pass when they matter. Table-cell text is
checked for font size and borders only, not punctuation/heading/formula (this avoids
Expand Down
5 changes: 4 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,22 @@ python scripts/audit_docx_format.py path/to/report.docx --json # 机器可读
| `HEADING_NO_STYLE` | WARN | 看着像标题但没用 Word 标题样式 |
| `TABLE_SIZE` | FAIL | 表内文字或表内公式非五号/10.5 pt(小四亦可;不得大于正文) |
| `TABLE_BORDERS` | WARN | 表格有竖线/内部网格(非三线表) |
| `TABLE_SHADING` | FAIL | 表格/单元格带底纹,含表格样式 `firstRow` 条件格式带来的表头底纹(三线表必须白底) |
| `TABLE_RULES` | WARN | 三线不对:顶/底线缺失、行间横线、或表头下线不比顶/底线细 |
| `CAPTION_POSITION` | WARN | 表题在表下 / 图题在图上 |
| `COLOR` | WARN | 多余的非黑色字体(已排除超链接/主题色) |
| `CITATION_BRACKETS` | FAIL | 全角引用括号 `[1]` |
| `CITATION_FIELDS` | FAIL | 有引用但无 `REF ref_###` 字段 |
| `CITATION_NO_BRACKETS` | WARN | 裸上标数字引用、丢了中括号 |
| `VISIBLE_LATEX` | FAIL | 残留可见 LaTeX 源码而非 OMML |
| `FORMULA_TEXT` | FAIL/WARN | 本应是 OMML 的纯文本公式/量符号 |
| `MATH_DUPLICATE` | FAIL | 公式对象的内容仍以纯文本形式留在同一段落(追加而非原位替换) |
| `FORMULA_DIGIT_ITALIC` | WARN | 公式里的数字/运算符被斜体(只有变量该斜体) |
| `EQUATION_NUMBER_CENTER` | WARN | 带编号的独立公式整体居中(编号应靠右) |

它刻意保持**领域中立**——不写死任何学科专有符号表。

**审计范围:** 脚本只检查 `word/document.xml` 主文档流,不检查页眉、页脚、脚注、尾注、批注或嵌入部件——这些需人工或更深的 OOXML 检查。表格单元格内的文字只查字号和边框,不查标点/标题/公式(以避免单元格里的数字和短片段造成误报)。
**审计范围:** 脚本检查 `word/document.xml` 主文档流(另读 `word/styles.xml` 以核查表格样式底纹/边框),不检查页眉、页脚、脚注、尾注、批注或嵌入部件——这些需人工或更深的 OOXML 检查。表格单元格内的文字只查字号和边框,不查标点/标题/公式(以避免单元格里的数字和短片段造成误报)。

## 自动修复脚本

Expand Down
10 changes: 6 additions & 4 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ description: Apply Allen's formal Word report formatting standard. Use when crea

Use this skill to format formal Chinese Word reports consistently with Allen's preferred standard. It complements the general DOCX/document skill: use the document tooling for implementation and rendering, and use this skill for the required typography, formula, table, figure, reference/citation, and appendix-code rules.

**Standard version: 2026-06-29.** Detailed rules live in `references/`:
**Standard version: 2026-07-07.** Detailed rules live in `references/`:

- `references/formatting-standard.md` — main formatting checklist (typography, language/punctuation, headings, tables, formulas, figures, numbers/units, citations, lists/footnotes, appendix code).
- `references/document-structure-and-page-setup.md` — document structure and order, page setup, headers/footers, page numbering and sections, TOC, font-size hierarchy, multilevel numbering, widow/orphan control.
Expand All @@ -20,12 +20,12 @@ Use this skill to format formal Chinese Word reports consistently with Allen's p

## Required Workflow

1. Read `references/formatting-standard.md` before creating or substantially editing a Word report; also read `references/document-structure-and-page-setup.md` when the document needs structure, page setup, page numbering, a table of contents, or the font-size hierarchy.
1. Read `references/formatting-standard.md` before creating or substantially editing a Word report; also read `references/document-structure-and-page-setup.md` when the document needs structure, page setup, page numbering, a table of contents, or the font-size hierarchy. For any document that contains or will contain tables, read `references/three-line-table-ooxml.md` before building or normalizing the tables — it specifies which borders to set and how to clear shading; do not build tables from memory of "三线表".
2. Determine the dominant document language before punctuation cleanup. Chinese documents use Chinese punctuation in Chinese prose; English documents use ASCII punctuation in prose. Preserve English punctuation inside English phrases/quotes and protected tokens such as URLs, DOIs, code, formulas, file paths, decimals, and citation brackets.
3. Apply the standard unless the user, school template, or provided rubric explicitly overrides it.
4. Preserve existing document content and structure during edit tasks; make only the local formatting changes needed.
5. For any document containing formulas, variables, quantity symbols, subscripts/superscripts, units, or math-like expressions, read `references/latex-omml-formula-workflow.md` and run a formula discovery pass before styling. This includes bare one-letter quantity symbols in definition/explanation prose, such as `式中 Q 为流量,N 为出力`.
6. Write formulas, inline variables, math objects, and quantity symbols as LaTeX first, then render them into native Word OMML equations. Do not satisfy this standard by manually italicizing normal text.
6. Write formulas, inline variables, math objects, and quantity symbols as LaTeX first, then render them into native Word OMML equations. Every conversion is an **in-place replacement**: the OMML object goes exactly where the original token was and the original plain text is removed; never append rendered math at the end of a paragraph or merge adjacent expressions. Do not satisfy this standard by manually italicizing normal text.
7. For paper-style citations, read `references/citation-crossrefs-ooxml.md` and convert body citations such as `[1]`, `[1][2]`, `[1,2]`, or `[1-3]` into superscript Word cross-references to the matching bibliography entries; format the bibliography entries themselves per `references/reference-style-gbt7714.md` (GB/T 7714).
8. If editing an existing DOCX and Python is available, run `scripts/audit_docx_format.py <path-to-docx>` after formatting. Fix `FAIL` items and inspect `WARN` items; this script is a guardrail, not a substitute for visual QA. For the two safest mechanical fixes (full-width citation brackets and ASCII punctuation between CJK characters) you may run `scripts/normalize_docx.py <path-to-docx>`.
9. Before delivery, run a formatting audit against the checklist in `references/formatting-standard.md`.
Expand All @@ -39,7 +39,7 @@ Use this skill to format formal Chinese Word reports consistently with Allen's p
- Body punctuation: match the dominant document language. Chinese prose uses Chinese punctuation; English prose uses ASCII punctuation. Keep citation brackets ASCII `[` and `]`. Use the Chinese ellipsis `……`, em dash `——`, and book-title marks `《 》` where applicable.
- Body color: keep body text, headings, captions, tables, formulas, abstract, keywords, and references black unless the user explicitly requests otherwise. Appendix code comments are the standard red exception.
- Abstract and keywords: left aligned with left indent 0 and first-line indent 0.
- Tables: white three-line tables — the top and bottom rules visible and **thicker** (~1.5 pt, `w:sz≈12`), a single **thinner** header rule in the middle (~0.75 pt, `w:sz≈6`), and every other border (verticals, inside horizontals) set to none. Do not use a gridded or header-shaded table style; set the borders explicitly (see `references/three-line-table-ooxml.md`). A "no top/bottom rule, thick middle line" result is wrong. Table text — including in-table formulas and symbols — is 五号/10.5 pt (one size below the body; 小四 also accepted, never larger than body) and centered by default; units go in the header. The table caption goes **above** the table, centered. Repeat the header row across page breaks; do not split a table mid-row. Normalize existing tables that do not meet the standard.
- Tables: white three-line tables — the top and bottom rules visible and **thicker** (~1.5 pt, `w:sz≈12`), a single **thinner** header rule in the middle (~0.75 pt, `w:sz≈6`), and every other border (verticals, inside horizontals) set to none. **Every cell must be shading-free (white)**: remove the table style reference (or use a plain style), zero the `w:tblLook` conditional-formatting flags, and clear every `w:shd` — header shading usually comes from the table style's `firstRow` conditional format, not from a manual fill. Do not use a gridded or header-shaded table style; set the borders explicitly (see `references/three-line-table-ooxml.md`). A "no top/bottom rule, thick middle line" result is wrong. Table text — including in-table formulas and symbols — is 五号/10.5 pt (one size below the body; 小四 also accepted, never larger than body) and centered by default; units go in the header. The table caption goes **above** the table, centered. Repeat the header row across page breaks; do not split a table mid-row. Normalize existing tables that do not meet the standard.
- Figures: the figure caption goes **below** the figure, centered; keep plot titles out of the image when a Word caption is present.
- Numbering: number figures, tables, and equations by chapter (`图 1-1`, `表 2-3`, `式(1-1)`); refer to them in text as “如图 1-1 所示” / “式(1-1)”. Figures and tables must appear **after** they are first referenced (proximity rule).
- Formulas and symbols: author every formula, inline variable, math object, and quantity symbol in LaTeX and convert it to native Word OMML, including bare symbols such as `Q`, `N`, `H`, or `V` when they define or denote physical quantities. Variables are italic; digits, operators, units, function names, constants, explanatory text, and explanatory subscripts are upright — do **not** blanket-italicize the whole equation (that slants the digits too). Multi-letter coefficients use one variable + upright subscript (`C_I`, not `CI`). Put a display equation on a left-aligned paragraph with a center tab (equation) and a right tab (number) so the number is right-aligned; do not center the whole line. Formula font size follows its context — body formulas at the body size (小四), in-table formulas at the table size (五号).
Expand All @@ -64,6 +64,8 @@ Fail the formatting pass and revise if any of these remain:
- Figures, tables, or equations are not numbered by chapter, or a figure/table appears before it is first referenced in the text.
- Level-1 Chinese headings do not have a blank-line visual gap before them when they follow body text, or a heading is stranded at the bottom of a page.
- Table text is larger than the body or not the expected 五号/10.5 pt (小四/12 pt also accepted), unless the user or official template explicitly requires a different size.
- A table has any cell shading / non-white fill (including header shading inherited from a table style's `firstRow` conditional format), or lacks visible thick top/bottom rules with a single thinner header rule.
- Rendered math was appended instead of replacing the original text in place: a paragraph contains both an OMML object and the same expression as plain text, a trailing cluster of formulas repeats values from the prose, adjacent expressions were merged into one object, or stray fragments (`mm,Cv`) remain at a paragraph end.
- Formulas, inline variables, quantity symbols, subscripts/superscripts, or math objects remain as ordinary styled text instead of LaTeX-rendered Word OMML, including bare one-letter quantity symbols in `式中` / `其中` / `表示` / `为` definition contexts.
- A document with formulas/symbols was edited without a formula discovery pass and a LaTeX source list/registry.
- A formula is blanket-italicized (digits/operators slanted), or a numbered display equation is centered instead of having a right-aligned number, or appendix code is not Times New Roman 小四.
Expand Down
43 changes: 41 additions & 2 deletions examples/make_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* non-black body font color
* a heading in Songti that ends with punctuation
* a table caption placed below its table
* a shaded (non-white) table header cell
"""

from __future__ import annotations
Expand All @@ -27,10 +28,42 @@

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Pt, RGBColor


def _set_border(parent, tag: str, val: str, sz: str = "") -> None:
element = OxmlElement(f"w:{tag}")
element.set(qn("w:val"), val)
if sz:
element.set(qn("w:sz"), sz)
element.set(qn("w:space"), "0")
element.set(qn("w:color"), "000000")
parent.append(element)


def make_three_line(table) -> None:
"""Give a python-docx table explicit three-line borders and a white background."""
tbl_pr = table._tbl.tblPr
borders = OxmlElement("w:tblBorders")
_set_border(borders, "top", "single", "12")
_set_border(borders, "bottom", "single", "12")
for tag in ("left", "right", "insideH", "insideV"):
_set_border(borders, tag, "none")
tbl_pr.append(borders)
for cell in table.rows[0].cells:
tc_pr = cell._tc.get_or_add_tcPr()
cell_borders = OxmlElement("w:tcBorders")
_set_border(cell_borders, "bottom", "single", "6")
tc_pr.append(cell_borders)
shd = OxmlElement("w:shd")
shd.set(qn("w:val"), "clear")
shd.set(qn("w:color"), "auto")
shd.set(qn("w:fill"), "auto")
tc_pr.append(shd)


def build(path: str) -> None:
doc = Document()

Expand Down Expand Up @@ -71,12 +104,17 @@ def build(path: str) -> None:
run.font.name = "宋体"
run._element.get_or_add_rPr().get_or_add_rFonts().set(qn("w:eastAsia"), "宋体")

# A table whose text is not small-four (12 pt).
# A table whose text is not small-four (12 pt), with a shaded header cell
# (a three-line table must be all white).
table = doc.add_table(rows=1, cols=2)
for idx, label in enumerate(("方案", "流量")):
cell = table.cell(0, idx)
run = cell.paragraphs[0].add_run(label)
run.font.size = Pt(14) # -> w:sz=28, not the required 24
shd = OxmlElement("w:shd")
shd.set(qn("w:val"), "clear")
shd.set(qn("w:fill"), "D9E2F3") # light blue header shading
table.cell(0, 0)._tc.get_or_add_tcPr().append(shd)

# A table caption placed BELOW the table (table captions belong above).
doc.add_paragraph("表 1-1 方案比较结果")
Expand Down Expand Up @@ -114,12 +152,13 @@ def build_compliant(path: str) -> None:
cap = doc.add_paragraph("表 1-1 主要计算参数")
cap.alignment = WD_ALIGN_PARAGRAPH.CENTER

# Default table (no borders) with 五号 (10.5 pt) text.
# A proper white three-line table with 五号 (10.5 pt) text.
table = doc.add_table(rows=2, cols=2)
for row in table.rows:
for cell in row.cells:
run = cell.paragraphs[0].add_run("参数")
run.font.size = Pt(10.5) # 五号 -> w:sz=21
make_three_line(table)

doc.save(path)
print(f"wrote {path}")
Expand Down
Loading
Loading