diff --git a/.codex/INSTALL.md b/.codex/INSTALL.md
index 8caec89..70b72e4 100644
--- a/.codex/INSTALL.md
+++ b/.codex/INSTALL.md
@@ -38,6 +38,7 @@ Enable MiniMax skills in Codex via native skill discovery. Just clone and symlin
- **minimax-pdf** — Generate, fill, and reformat PDF documents with a token-based design system
- **pptx-generator** — Generate, edit, and read PowerPoint presentations
- **minimax-xlsx** — Open, create, read, analyze, edit, or validate Excel/spreadsheet files
+- **minimax-docx** — Professional DOCX document creation, editing, and formatting using OpenXML SDK
## Verify
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
index 034d663..7f627d8 100644
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "minimax-skills",
"displayName": "MiniMax Skills",
- "description": "MiniMax AI skills library: frontend development, fullstack development, Android native development, iOS application development, shader development, GIF sticker maker, PDF generation, PPTX presentations, and Excel/spreadsheet processing",
+ "description": "MiniMax AI skills library: frontend development, fullstack development, Android native development, iOS application development, shader development, GIF sticker maker, PDF generation, PPTX presentations, Excel/spreadsheet processing, and DOCX document processing",
"version": "1.0.0",
"author": {
"name": "MiniMax AI"
@@ -9,7 +9,7 @@
"homepage": "https://github.com/MiniMax-AI/skills",
"repository": "https://github.com/MiniMax-AI/skills",
"license": "MIT",
- "keywords": ["skills", "frontend", "fullstack", "android", "ios", "shader", "gif", "sticker", "pdf", "pptx", "xlsx", "excel", "spreadsheet", "minimax"],
+ "keywords": ["skills", "frontend", "fullstack", "android", "ios", "shader", "gif", "sticker", "pdf", "pptx", "xlsx", "excel", "spreadsheet", "docx", "word", "document", "minimax"],
"logo": "assets/logo.png",
"skills": "./skills/"
}
diff --git a/.opencode/INSTALL.md b/.opencode/INSTALL.md
index d544472..2a45d01 100644
--- a/.opencode/INSTALL.md
+++ b/.opencode/INSTALL.md
@@ -43,6 +43,7 @@ Verify by asking: "List available skills"
- **minimax-pdf** — Generate, fill, and reformat PDF documents with a token-based design system
- **pptx-generator** — Generate, edit, and read PowerPoint presentations
- **minimax-xlsx** — Open, create, read, analyze, edit, or validate Excel/spreadsheet files
+- **minimax-docx** — Professional DOCX document creation, editing, and formatting using OpenXML SDK
## Updating
diff --git a/README.md b/README.md
index 27c0067..9fccd36 100644
--- a/README.md
+++ b/README.md
@@ -19,6 +19,7 @@ Development skills for AI coding agents. Plug into your favorite AI coding tool
| `minimax-pdf` | Generate, fill, and reformat PDF documents with a token-based design system. CREATE polished PDFs from scratch (15 cover styles), FILL existing form fields, or REFORMAT documents into a new design. Print-ready output with typography and color derived from document type. |
| `pptx-generator` | Generate, edit, and read PowerPoint presentations. Create from scratch with PptxGenJS (cover, TOC, content, section divider, summary slides), edit existing PPTX via XML workflows, or extract text with markitdown. |
| `minimax-xlsx` | Open, create, read, analyze, edit, or validate Excel/spreadsheet files (.xlsx, .xlsm, .csv, .tsv). Covers creating new xlsx from scratch via XML templates, reading and analyzing with pandas, editing existing files with zero format loss, formula recalculation, validation, and professional financial formatting. |
+| `minimax-docx` | Professional DOCX document creation, editing, and formatting using OpenXML SDK (.NET). Three pipelines: create new documents from scratch, fill/edit content in existing documents, or apply template formatting with XSD validation gate-check. |
## Installation
diff --git a/README_zh.md b/README_zh.md
index 0070ba2..57902fb 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -19,6 +19,7 @@
| `minimax-pdf` | 基于 token 化设计系统生成、填写和重排 PDF 文档。支持三种模式:CREATE(从零生成,15 种封面风格)、FILL(填写现有表单字段)、REFORMAT(将已有文档重排为新设计)。排版与配色由文档类型自动推导,输出即可打印。 |
| `pptx-generator` | 生成、编辑和读取 PowerPoint 演示文稿。支持用 PptxGenJS 从零创建(封面、目录、内容、分节页、总结页),通过 XML 工作流编辑现有 PPTX,或用 markitdown 提取文本。 |
| `minimax-xlsx` | 打开、创建、读取、分析、编辑或验证 Excel/电子表格文件(.xlsx、.xlsm、.csv、.tsv)。支持通过 XML 模板从零创建 xlsx、使用 pandas 读取分析、零格式损失编辑现有文件、公式重算与验证、专业财务格式化。 |
+| `minimax-docx` | 基于 OpenXML SDK(.NET)的专业 DOCX 文档创建、编辑与排版。三条流水线:从零创建新文档、填写/编辑现有文档内容、应用模板格式并通过 XSD 验证门控检查。 |
## 安装
diff --git a/skills/minimax-docx/SKILL.md b/skills/minimax-docx/SKILL.md
new file mode 100644
index 0000000..0d99f52
--- /dev/null
+++ b/skills/minimax-docx/SKILL.md
@@ -0,0 +1,274 @@
+---
+name: minimax-docx
+license: MIT
+metadata:
+ version: "1.0.0"
+ category: document-processing
+ author: MiniMaxAI
+ sources:
+ - "ECMA-376 Office Open XML File Formats"
+ - "GB/T 9704-2012 Layout Standard for Official Documents"
+ - "IEEE / ACM / APA / MLA / Chicago / Turabian Style Guides"
+ - "Springer LNCS / Nature / HBR Document Templates"
+description: >
+ Professional DOCX document creation, editing, and formatting using OpenXML SDK (.NET).
+ Three pipelines: (A) create new documents from scratch, (B) fill/edit content in existing
+ documents, (C) apply template formatting with XSD validation gate-check.
+ MUST use this skill whenever the user wants to produce, modify, or format a Word document —
+ including when they say "write a report", "draft a proposal", "make a contract",
+ "fill in this form", "reformat to match this template", or any task whose final output
+ is a .docx file. Even if the user doesn't mention "docx" explicitly, if the task
+ implies a printable/formal document, use this skill.
+triggers:
+ - Word
+ - docx
+ - document
+ - 文档
+ - Word文档
+ - 报告
+ - 合同
+ - 公文
+ - 排版
+ - 套模板
+---
+
+# minimax-docx
+
+Create, edit, and format DOCX documents via CLI tools or direct C# scripts built on OpenXML SDK (.NET).
+
+## Setup
+
+**First time:** `bash scripts/setup.sh` (or `powershell scripts/setup.ps1` on Windows, `--minimal` to skip optional deps).
+
+**First operation in session:** `scripts/env_check.sh` — do not proceed if `NOT READY`. (Skip on subsequent operations within the same session.)
+
+## Quick Start: Direct C# Path
+
+When the task requires structural document manipulation (custom styles, complex tables, multi-section layouts, headers/footers, TOC, images), write C# directly instead of wrestling with CLI limitations. Use this scaffold:
+
+```csharp
+// File: scripts/dotnet/task.csx (or a new .cs in a Console project)
+// dotnet run --project scripts/dotnet/MiniMaxAIDocx.Cli -- run-script task.csx
+#r "nuget: DocumentFormat.OpenXml, 3.2.0"
+
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Wordprocessing;
+
+using var doc = WordprocessingDocument.Create("output.docx", WordprocessingDocumentType.Document);
+var mainPart = doc.AddMainDocumentPart();
+mainPart.Document = new Document(new Body());
+
+// --- Your logic here ---
+// Read the relevant Samples/*.cs file FIRST for tested patterns.
+// See Samples/ table in References section below.
+```
+
+**Before writing any C#, read the relevant `Samples/*.cs` file** — they contain compilable, SDK-version-verified patterns. The Samples table in the References section below maps topics to files.
+
+## CLI shorthand
+
+All CLI commands below use `$CLI` as shorthand for:
+```bash
+dotnet run --project scripts/dotnet/MiniMaxAIDocx.Cli --
+```
+
+## Pipeline routing
+
+Route by checking: does the user have an input .docx file?
+
+```
+User task
+├─ No input file → Pipeline A: CREATE
+│ signals: "write", "create", "draft", "generate", "new", "make a report/proposal/memo"
+│ → Read references/scenario_a_create.md
+│
+└─ Has input .docx
+ ├─ Replace/fill/modify content → Pipeline B: FILL-EDIT
+ │ signals: "fill in", "replace", "update", "change text", "add section", "edit"
+ │ → Read references/scenario_b_edit_content.md
+ │
+ └─ Reformat/apply style/template → Pipeline C: FORMAT-APPLY
+ signals: "reformat", "apply template", "restyle", "match this format", "套模板", "排版"
+ ├─ Template is pure style (no content) → C-1: OVERLAY (apply styles to source)
+ └─ Template has structure (cover/TOC/example sections) → C-2: BASE-REPLACE
+ (use template as base, replace example content with user content)
+ → Read references/scenario_c_apply_template.md
+```
+
+If the request spans multiple pipelines, run them sequentially (e.g., Create then Format-Apply).
+
+## Pre-processing
+
+Convert `.doc` → `.docx` if needed: `scripts/doc_to_docx.sh input.doc output_dir/`
+
+Preview before editing (avoids reading raw XML): `scripts/docx_preview.sh document.docx`
+
+Analyze structure for editing scenarios: `$CLI analyze --input document.docx`
+
+## Scenario A: Create
+
+Read `references/scenario_a_create.md`, `references/typography_guide.md`, and `references/design_principles.md` first. Pick an aesthetic recipe from `Samples/AestheticRecipeSamples.cs` that matches the document type — do not invent formatting values. For CJK, also read `references/cjk_typography.md`.
+
+**Choose your path:**
+- **Simple** (plain text, minimal formatting): use CLI — `$CLI create --type report --output out.docx --config content.json`
+- **Structural** (custom styles, multi-section, TOC, images, complex tables): write C# directly. Read the relevant `Samples/*.cs` first.
+
+CLI options: `--type` (report|letter|memo|academic), `--title`, `--author`, `--page-size` (letter|a4|legal|a3), `--margins` (standard|narrow|wide), `--header`, `--footer`, `--page-numbers`, `--toc`, `--content-json`.
+
+Then run the **validation pipeline** (below).
+
+## Scenario B: Edit / Fill
+
+Read `references/scenario_b_edit_content.md` first. Preview → analyze → edit → validate.
+
+**Choose your path:**
+- **Simple** (text replacement, placeholder fill): use CLI subcommands.
+- **Structural** (add/reorganize sections, modify styles, manipulate tables, insert images): write C# directly. Read `references/openxml_element_order.md` and the relevant `Samples/*.cs`.
+
+Available CLI edit subcommands:
+- `replace-text --find "X" --replace "Y"`
+- `fill-placeholders --data '{"key":"value"}'`
+- `fill-table --data table.json`
+- `insert-section`, `remove-section`, `update-header-footer`
+
+```bash
+$CLI edit replace-text --input in.docx --output out.docx --find "OLD" --replace "NEW"
+$CLI edit fill-placeholders --input in.docx --output out.docx --data '{"name":"John"}'
+```
+
+Then run the **validation pipeline**. Also run diff to verify minimal changes:
+```bash
+$CLI diff --before in.docx --after out.docx
+```
+
+## Scenario C: Apply Template
+
+Read `references/scenario_c_apply_template.md` first. Preview and analyze both source and template.
+
+```bash
+$CLI apply-template --input source.docx --template template.docx --output out.docx
+```
+
+For complex template operations (multi-template merge, per-section headers/footers, style merging), write C# directly — see Critical Rules below for required patterns.
+
+Run the **validation pipeline**, then the **hard gate-check**:
+```bash
+$CLI validate --input out.docx --gate-check assets/xsd/business-rules.xsd
+```
+Gate-check is a **hard requirement**. Do NOT deliver until it passes. If it fails: diagnose, fix, re-run.
+
+Also diff to verify content preservation: `$CLI diff --before source.docx --after out.docx`
+
+## Validation pipeline
+
+Run after every write operation. For Scenario C the full pipeline is **mandatory**; for A/B it is **recommended** (skip only if the operation was trivially simple).
+
+```bash
+$CLI merge-runs --input doc.docx # 1. consolidate runs
+$CLI validate --input doc.docx --xsd assets/xsd/wml-subset.xsd # 2. XSD structure
+$CLI validate --input doc.docx --business # 3. business rules
+```
+
+If XSD fails, auto-repair and retry:
+```bash
+$CLI fix-order --input doc.docx
+$CLI validate --input doc.docx --xsd assets/xsd/wml-subset.xsd
+```
+
+If XSD still fails, fall back to business rules + preview:
+```bash
+$CLI validate --input doc.docx --business
+scripts/docx_preview.sh doc.docx
+# Verify: font contamination=0, table count correct, drawing count correct, sectPr count correct
+```
+
+Final preview: `scripts/docx_preview.sh doc.docx`
+
+## Critical rules
+
+These prevent file corruption — OpenXML is strict about element ordering.
+
+**Element order** (properties always first):
+
+| Parent | Order |
+|--------|-------|
+| `w:p` | `pPr` → runs |
+| `w:r` | `rPr` → `t`/`br`/`tab` |
+| `w:tbl`| `tblPr` → `tblGrid` → `tr` |
+| `w:tr` | `trPr` → `tc` |
+| `w:tc` | `tcPr` → `p` (min 1 ``) |
+| `w:body` | block content → `sectPr` (LAST child) |
+
+**Direct format contamination:** When copying content from a source document, inline `rPr` (fonts, color) and `pPr` (borders, shading, spacing) override template styles. Always strip direct formatting — keep only `pStyle` reference and `t` text. Clean tables too (including `pPr/rPr` inside cells).
+
+**Track changes:** `` uses ``, never ``. `` uses ``, never ``.
+
+**Font size:** `w:sz` = points × 2 (12pt → `sz="24"`). Margins/spacing in DXA (1 inch = 1440, 1cm ≈ 567).
+
+**Heading styles MUST have OutlineLevel:** When defining heading styles (Heading1, ThesisH1, etc.), always include `new OutlineLevel { Val = N }` in `StyleParagraphProperties` (H1→0, H2→1, H3→2). Without this, Word sees them as plain styled text — TOC and navigation pane won't work.
+
+**Multi-template merge:** When given multiple template files (font, heading, breaks), read `references/scenario_c_apply_template.md` section "Multi-Template Merge" FIRST. Key rules:
+- Merge styles from all templates into one styles.xml. Structure (sections/breaks) comes from the breaks template.
+- Each content paragraph must appear exactly ONCE — never duplicate when inserting section breaks.
+- NEVER insert empty/blank paragraphs as padding or section separators. Output paragraph count must equal input. Use section break properties (`w:sectPr` inside `w:pPr`) and style spacing (`w:spacing` before/after) for visual separation.
+- Insert oddPage section breaks before EVERY chapter heading, not just the first. Even if a chapter has dual-column content, it MUST start with oddPage; use a second continuous break after the heading for column switching.
+- Dual-column chapters need THREE section breaks: (1) oddPage in preceding para's pPr, (2) continuous+cols=2 in the chapter HEADING's pPr, (3) continuous+cols=1 in the last body para's pPr to revert.
+- Copy `titlePg` settings from the breaks template for EACH section. Abstract and TOC sections typically need `titlePg=true`.
+
+**Multi-section headers/footers:** Templates with 10+ sections (e.g., Chinese thesis) have DIFFERENT headers/footers per section (Roman vs Arabic page numbers, different header text per zone). Rules:
+- Use C-2 Base-Replace: copy the TEMPLATE as output base, then replace body content. This preserves all sections, headers, footers, and titlePg settings automatically.
+- NEVER recreate headers/footers from scratch — copy template header/footer XML byte-for-byte.
+- NEVER add formatting (borders, alignment, font size) not present in the template header XML.
+- Non-cover sections MUST have header/footer XML files (at least empty header + page number footer).
+- See `references/scenario_c_apply_template.md` section "Multi-Section Header/Footer Transfer".
+
+## References
+
+Load as needed — don't load all at once. Pick the most relevant files for the task.
+
+**The C# samples and design references below are the project's knowledge base ("encyclopedia").** When writing OpenXML code, ALWAYS read the relevant sample file first — it contains compilable, SDK-version-verified patterns that prevent common errors. When making aesthetic decisions, read the design principles and recipe files — they encode tested, harmonious parameter sets from authoritative sources (IEEE, ACM, APA, Nature, etc.), not guesses.
+
+### Scenario guides (read first for each pipeline)
+
+| File | When |
+|------|------|
+| `references/scenario_a_create.md` | Pipeline A: creating from scratch |
+| `references/scenario_b_edit_content.md` | Pipeline B: editing existing content |
+| `references/scenario_c_apply_template.md` | Pipeline C: applying template formatting |
+
+### C# code samples (compilable, heavily commented — read when writing code)
+
+| File | Topic |
+|------|-------|
+| `Samples/DocumentCreationSamples.cs` | Document lifecycle: create, open, save, streams, doc defaults, settings, properties, page setup, multi-section |
+| `Samples/StyleSystemSamples.cs` | Styles: Normal/Heading chain, character/table/list styles, DocDefaults, latentStyles, CJK 公文, APA 7th, import, resolve inheritance |
+| `Samples/CharacterFormattingSamples.cs` | RunProperties: fonts, size, bold/italic, all underlines, color, highlight, strike, sub/super, caps, spacing, shading, border, emphasis marks |
+| `Samples/ParagraphFormattingSamples.cs` | ParagraphProperties: justification, indentation, line/paragraph spacing, keep/widow, outline level, borders, tabs, numbering, bidi, frame |
+| `Samples/TableSamples.cs` | Tables: borders, grid, cell props, margins, row height, header repeat, merge (H+V), nested, floating, three-line 三线表, zebra striping |
+| `Samples/HeaderFooterSamples.cs` | Headers/footers: page numbers, "Page X of Y", first/even/odd, logo image, table layout, 公文 "-X-", per-section |
+| `Samples/ImageSamples.cs` | Images: inline, floating, text wrapping, border, alt text, in header/table, replace, SVG fallback, dimension calc |
+| `Samples/ListAndNumberingSamples.cs` | Numbering: bullets, multi-level decimal, custom symbols, outline→headings, legal, Chinese 一/(一)/1./(1), restart/continue |
+| `Samples/FieldAndTocSamples.cs` | Fields: TOC, SimpleField vs complex field, DATE/PAGE/REF/SEQ/MERGEFIELD/IF/STYLEREF, TOC styles |
+| `Samples/FootnoteAndCommentSamples.cs` | Footnotes, endnotes, comments (4-file system), bookmarks, hyperlinks (internal + external) |
+| `Samples/TrackChangesSamples.cs` | Revisions: insertions (w:t), deletions (w:delText!), formatting changes, accept/reject all, move tracking |
+| `Samples/AestheticRecipeSamples.cs` | 13 aesthetic recipes from authoritative sources: ModernCorporate, AcademicThesis, ExecutiveBrief, ChineseGovernment (GB/T 9704), MinimalModern, IEEE Conference, ACM sigconf, APA 7th, MLA 9th, Chicago/Turabian, Springer LNCS, Nature, HBR — each with exact values from official style guides |
+
+Note: `Samples/` path is relative to `scripts/dotnet/MiniMaxAIDocx.Core/`.
+
+### Markdown references (read when you need specifications or design rules)
+
+| File | When |
+|------|------|
+| `references/openxml_element_order.md` | XML element ordering rules (prevents corruption) |
+| `references/openxml_units.md` | Unit conversion: DXA, EMU, half-points, eighth-points |
+| `references/openxml_encyclopedia_part1.md` | Detailed C# encyclopedia: document creation, styles, character & paragraph formatting |
+| `references/openxml_encyclopedia_part2.md` | Detailed C# encyclopedia: page setup, tables, headers/footers, sections, doc properties |
+| `references/openxml_encyclopedia_part3.md` | Detailed C# encyclopedia: TOC, footnotes, fields, track changes, comments, images, math, numbering, protection |
+| `references/typography_guide.md` | Font pairing, sizes, spacing, page layout, table design, color schemes |
+| `references/cjk_typography.md` | CJK fonts, 字号 sizes, RunFonts mapping, GB/T 9704 公文 standard |
+| `references/cjk_university_template_guide.md` | Chinese university thesis templates: numeric styleIds (1/2/3 vs Heading1), document zone structure (cover→abstract→TOC→body→references), font expectations, common mistakes |
+| `references/design_principles.md` | **Aesthetic foundations**: 6 design principles (white space, contrast/scale, proximity, alignment, repetition, hierarchy) — teaches WHY, not just WHAT |
+| `references/design_good_bad_examples.md` | **Good vs Bad comparisons**: 10 categories of typography mistakes with OpenXML values, ASCII mockups, and fixes |
+| `references/track_changes_guide.md` | Revision marks deep dive |
+| `references/troubleshooting.md` | **Symptom-driven fixes**: 13 common problems indexed by what you SEE (headings wrong, images missing, TOC broken, etc.) — search by symptom, find the fix |
diff --git a/skills/minimax-docx/assets/styles/academic_styles.xml b/skills/minimax-docx/assets/styles/academic_styles.xml
new file mode 100644
index 0000000..85d1d06
--- /dev/null
+++ b/skills/minimax-docx/assets/styles/academic_styles.xml
@@ -0,0 +1,250 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/assets/styles/corporate_styles.xml b/skills/minimax-docx/assets/styles/corporate_styles.xml
new file mode 100644
index 0000000..5d7e2fa
--- /dev/null
+++ b/skills/minimax-docx/assets/styles/corporate_styles.xml
@@ -0,0 +1,284 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/assets/styles/default_styles.xml b/skills/minimax-docx/assets/styles/default_styles.xml
new file mode 100644
index 0000000..6efe7f8
--- /dev/null
+++ b/skills/minimax-docx/assets/styles/default_styles.xml
@@ -0,0 +1,449 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/assets/xsd/aesthetic-rules.xsd b/skills/minimax-docx/assets/xsd/aesthetic-rules.xsd
new file mode 100644
index 0000000..e423035
--- /dev/null
+++ b/skills/minimax-docx/assets/xsd/aesthetic-rules.xsd
@@ -0,0 +1,470 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Body text font size in half-points.
+ Acceptable range: 20-28 (10pt-14pt).
+ - 10pt (20): minimum for comfortable reading
+ - 11pt (22): modern default (Calibri, Aptos)
+ - 12pt (24): traditional default (Times New Roman)
+ - 14pt (28): maximum before body text looks oversized
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Heading font size in half-points.
+ Acceptable range: 24-52 (12pt-26pt).
+ - 12pt (24): APA-style (hierarchy via bold/italic, not size)
+ - 16pt (32): typical H2/H3
+ - 20pt (40): typical H1
+ - 26pt (52): maximum before headings dominate the page
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Line spacing value for auto line-spacing rule.
+ In 240ths of single spacing: 240 = 1.0x, 480 = 2.0x.
+ Acceptable range: 240-560 (1.0x to 2.33x).
+ Common values:
+ - 240: single spacing (dense, technical)
+ - 259: Word's 1.08x default
+ - 276: 1.15x (modern corporate default)
+ - 336: 1.4x (executive/generous)
+ - 360: 1.5x (generous/minimal)
+ - 480: 2.0x (academic double spacing)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Fixed line spacing value (lineRule="exact") in DXA.
+ Acceptable range: 200-720 (10pt-36pt).
+ - 560: Chinese government standard (28pt, for 16pt body)
+ - 480: double-space equivalent for 12pt body
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Page margin in DXA. Minimum 720 (0.5 inch), maximum 4320 (3 inches).
+ Common values:
+ - 720: 0.5in (minimum printable)
+ - 1440: 1.0in (standard US)
+ - 1588: 28mm (Chinese government left margin)
+ - 1800: 1.25in (executive/premium)
+ - 2160: 1.5in (binding margin or narrow-column design)
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Vertical (top/bottom) page margin in DXA.
+ Range: 360 to 4320 (0.25in to 3in).
+ Slightly more permissive than horizontal margins because
+ header/footer areas may reduce effective vertical margin.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Paragraph spacing (before/after) in DXA.
+ Range: 0-960 (0pt-48pt).
+ Common values:
+ - 0: academic style (uses first-line indent instead)
+ - 80: 4pt (tight, used after H2/H3)
+ - 120: 6pt (moderate)
+ - 160: 8pt (standard modern spacing)
+ - 200: 10pt (generous/executive)
+ - 240: 12pt (very generous/minimal)
+ - 480: 24pt (heading before — creates section break)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Table cell padding in DXA. Minimum 28 DXA (~1.4pt).
+ Recommended: 57 DXA (~2.85pt) for comfortable spacing.
+ Maximum: 288 DXA (~14pt) — beyond this wastes space.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Border width in eighth-points.
+ Range: 2-24 (0.25pt to 3pt).
+ Common values:
+ - 4: 0.5pt (thin, standard)
+ - 6: 0.75pt (header separator in three-line tables)
+ - 8: 1.0pt (medium, good for framing borders)
+ - 12: 1.5pt (heavy, used for top/bottom in three-line tables)
+ - 24: 3.0pt (maximum before borders dominate)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Color value: 6-digit hex (RRGGBB) or "auto".
+ Examples: "000000", "1F3864", "2C3E50", "auto".
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ First-line indent in DXA. Range: 0-1440 (0in to 1.0in).
+ - 0: no indent (modern style with space-after)
+ - 480: 0.33in (compact)
+ - 640: ~0.44in (2 Chinese characters at 16pt)
+ - 720: 0.5in (standard APA/academic)
+ - 1440: 1.0in (maximum before it looks wrong)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Aesthetic run properties validator.
+ Checks font size and color format at the run level.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Aesthetic spacing validator for paragraph spacing properties.
+ Validates line spacing and before/after spacing are in range.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Aesthetic page margin validator.
+ Ensures all margins meet minimum print-safe thresholds.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Aesthetic table cell margin validator.
+ Ensures minimum padding for readability.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/assets/xsd/business-rules.xsd b/skills/minimax-docx/assets/xsd/business-rules.xsd
new file mode 100644
index 0000000..c8e29e4
--- /dev/null
+++ b/skills/minimax-docx/assets/xsd/business-rules.xsd
@@ -0,0 +1,130 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/assets/xsd/common-types.xsd b/skills/minimax-docx/assets/xsd/common-types.xsd
new file mode 100644
index 0000000..c90a487
--- /dev/null
+++ b/skills/minimax-docx/assets/xsd/common-types.xsd
@@ -0,0 +1,159 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/assets/xsd/wml-subset.xsd b/skills/minimax-docx/assets/xsd/wml-subset.xsd
new file mode 100644
index 0000000..fb2416d
--- /dev/null
+++ b/skills/minimax-docx/assets/xsd/wml-subset.xsd
@@ -0,0 +1,589 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/skills/minimax-docx/references/cjk_typography.md b/skills/minimax-docx/references/cjk_typography.md
new file mode 100644
index 0000000..e468f10
--- /dev/null
+++ b/skills/minimax-docx/references/cjk_typography.md
@@ -0,0 +1,357 @@
+# CJK Typography & Mixed-Script Guide
+
+Rules for Chinese, Japanese, and Korean text in DOCX documents.
+
+## Table of Contents
+
+1. [Font Selection](#font-selection)
+2. [Font Size Names (CJK)](#font-size-names)
+3. [RunFonts Mapping](#runfonts-mapping)
+4. [Punctuation & Line Breaking](#punctuation--line-breaking)
+5. [Paragraph Indentation](#paragraph-indentation)
+6. [Line Spacing for CJK](#line-spacing)
+7. [Chinese Government Standard (GB/T 9704)](#gbt-9704)
+8. [Mixed CJK + Latin Best Practices](#mixed-script)
+9. [OpenXML Quick Reference](#openxml-quick-reference)
+
+---
+
+## Font Selection
+
+### Recommended CJK Fonts
+
+| Language | Serif (正文) | Sans (标题) | Notes |
+|----------|-------------|-------------|-------|
+| **Simplified Chinese** | 宋体 (SimSun) | 微软雅黑 (Microsoft YaHei) | YaHei for screen, SimSun for print |
+| **Simplified Chinese** | 仿宋 (FangSong) | 黑体 (SimHei) | Government documents |
+| **Traditional Chinese** | 新細明體 (PMingLiU) | 微軟正黑體 (Microsoft JhengHei) | Taiwan standard |
+| **Japanese** | MS 明朝 (MS Mincho) | MS ゴシック (MS Gothic) | Classic pairing |
+| **Japanese** | 游明朝 (Yu Mincho) | 游ゴシック (Yu Gothic) | Modern, Windows 10+ |
+| **Korean** | 바탕 (Batang) | 맑은 고딕 (Malgun Gothic) | Standard pairing |
+
+### Government Document Fonts (公文)
+
+| Element | Font | Size |
+|---------|------|------|
+| 标题 (title) | 小标宋 (FZXiaoBiaoSong-B05S) | 二号 (22pt) |
+| 一级标题 | 黑体 (SimHei) | 三号 (16pt) |
+| 二级标题 | 楷体_GB2312 (KaiTi_GB2312) | 三号 (16pt) |
+| 三级标题 | 仿宋_GB2312 加粗 | 三号 (16pt) |
+| 正文 (body) | 仿宋_GB2312 (FangSong_GB2312) | 三号 (16pt) |
+| 附注/页码 | 宋体 (SimSun) | 四号 (14pt) |
+
+---
+
+## Font Size Names
+
+CJK uses named sizes. Map to points and `w:sz` half-point values:
+
+| 字号 | Points | `w:sz` | Common Use |
+|------|--------|--------|------------|
+| 初号 | 42pt | 84 | Display title |
+| 小初 | 36pt | 72 | Large title |
+| 一号 | 26pt | 52 | Chapter heading |
+| 小一 | 24pt | 48 | Major heading |
+| 二号 | 22pt | 44 | Document title (公文) |
+| 小二 | 18pt | 36 | Western H1 equivalent |
+| 三号 | 16pt | 32 | CJK heading / 公文 body |
+| 小三 | 15pt | 30 | Sub-heading |
+| 四号 | 14pt | 28 | CJK subheading |
+| 小四 | 12pt | 24 | Standard body (CJK) |
+| 五号 | 10.5pt | 21 | Compact CJK body |
+| 小五 | 9pt | 18 | Footnotes |
+| 六号 | 7.5pt | 15 | Fine print |
+
+---
+
+## RunFonts Mapping
+
+OpenXML uses four font slots to handle multilingual text:
+
+```xml
+
+ w:hAnsi="Calibri"
+ w:eastAsia="SimSun"
+ w:cs="Arial"
+/>
+```
+
+**Word's character classification logic:**
+
+1. Character is in CJK range → uses `w:eastAsia` font
+2. Character is in complex script range → uses `w:cs` font
+3. Character is basic Latin (ASCII) → uses `w:ascii` font
+4. Everything else → uses `w:hAnsi` font
+
+**Key**: `w:eastAsia` is the **only** way to set CJK fonts. Setting just `w:ascii` will NOT affect CJK characters. Mixed text within a single run auto-switches fonts at the character level — no need for separate runs.
+
+### Document Defaults
+
+```xml
+
+
+
+
+
+
+
+
+
+
+```
+
+`w:lang w:eastAsia` helps Word resolve ambiguous characters (e.g., punctuation shared between CJK and Latin).
+
+---
+
+## Punctuation & Line Breaking
+
+### Full-Width vs Half-Width
+
+CJK text uses full-width punctuation:
+
+| Type | CJK | Latin |
+|------|-----|-------|
+| Period | 。(U+3002) | . |
+| Comma | ,(U+FF0C) 、(U+3001) | , |
+| Colon | :(U+FF1A) | : |
+| Semicolon | ;(U+FF1B) | ; |
+| Quotes | 「」『』 or ""'' | "" '' |
+| Parentheses | ()(U+FF08/09) | () |
+
+In mixed text, use the punctuation style of the **surrounding language context**.
+
+### OpenXML Controls
+
+```xml
+
+
+
+
+
+
+```
+
+### Kinsoku Rules (禁則処理)
+
+Prevents certain characters from appearing at the start or end of a line:
+- **Cannot start a line**: `)」』】〉》。、,!?;:` and closing brackets
+- **Cannot end a line**: `(「『【〈《` and opening brackets
+
+Word applies these automatically when `w:kinsoku` is enabled.
+
+### Line Breaking
+
+- CJK characters can break between **any two characters** (no word boundaries needed)
+- Latin words within CJK text still follow word-boundary breaking
+- `w:wordWrap w:val="false"` enables CJK-style breaking (break anywhere)
+
+---
+
+## Paragraph Indentation
+
+### Chinese Standard: 2-Character Indent
+
+Chinese body text conventionally uses a 2-character first-line indent:
+
+```xml
+
+```
+
+Preferred over `w:firstLine` with fixed DXA because `firstLineChars` scales with font size.
+
+| Indent | Value |
+|--------|-------|
+| 1 character | `w:firstLineChars="100"` |
+| 2 characters | `w:firstLineChars="200"` |
+| 3 characters | `w:firstLineChars="300"` |
+
+---
+
+## Line Spacing
+
+- CJK characters are taller than Latin characters at the same point size
+- Default `1.0` line spacing may feel cramped with CJK text
+- Recommended: `1.15–1.5` for mixed CJK+Latin, `1.0` with fixed 28pt for 公文
+
+### Auto Spacing
+
+```xml
+
+
+
+
+```
+
+Adds ~¼ em spacing between CJK and non-CJK characters automatically. **Recommended: always enable.**
+
+---
+
+## GB/T 9704
+
+Chinese government document standard (党政机关公文格式). These are **strict requirements**, not suggestions.
+
+### Page Setup
+
+| Parameter | Value | OpenXML |
+|-----------|-------|---------|
+| Page size | A4 (210×297mm) | Width=11906, Height=16838 |
+| Top margin | 37mm | 2098 DXA |
+| Bottom margin | 35mm | 1984 DXA |
+| Left margin | 28mm | 1588 DXA |
+| Right margin | 26mm | 1474 DXA |
+| Characters/line | 28 | |
+| Lines/page | 22 | |
+| Line spacing | Fixed 28pt | `line="560"` lineRule="exact" |
+
+### Document Structure
+
+```
+┌─────────────────────────────────┐
+│ 发文机关标志 (红头) │ ← 小标宋 or 红色大字
+│ ══════════════════ (红线) │ ← Red #FF0000, 2pt
+├─────────────────────────────────┤
+│ 发文字号: X机发〔2025〕X号 │ ← 仿宋 三号, centered
+│ │
+│ 标题 (Title) │ ← 小标宋 二号, centered
+│ │ 可分多行,回行居中
+│ 主送机关: │ ← 仿宋 三号
+│ │
+│ 正文 (Body)... │ ← 仿宋_GB2312 三号
+│ 一、一级标题 │ ← 黑体 三号
+│ (一)二级标题 │ ← 楷体 三号
+│ 1. 三级标题 │ ← 仿宋 三号 加粗
+│ (1) 四级标题 │ ← 仿宋 三号
+│ │
+│ 附件: 1. xxx │ ← 仿宋 三号
+│ │
+│ 发文机关署名 │ ← 仿宋 三号
+│ 成文日期 │ ← 仿宋 三号, 小写中文数字
+├─────────────────────────────────┤
+│ ══════════════════ (版记线) │
+│ 抄送: xxx │ ← 仿宋 四号
+│ 印发机关及日期 │ ← 仿宋 四号
+└─────────────────────────────────┘
+```
+
+### Numbering System
+
+```
+一、 ← 黑体 (SimHei), no indentation
+(一) ← 楷体 (KaiTi), indented 2 chars
+1. ← 仿宋加粗 (FangSong Bold), indented 2 chars
+(1) ← 仿宋 (FangSong), indented 2 chars
+```
+
+### Colors
+
+| Element | Color | Requirement |
+|---------|-------|-------------|
+| All body text | Black #000000 | Mandatory |
+| 红头 (agency name) | Red #FF0000 | Mandatory |
+| 红线 (separator) | Red #FF0000 | Mandatory |
+| 公章 (official seal) | Red | Mandatory |
+
+### Page Numbers
+
+- Position: bottom center
+- Format: `-X-` (dash-number-dash)
+- Font: 宋体 四号 (SimSun 14pt, `sz="28"`)
+- No page number on cover page if present
+
+---
+
+## Mixed Script
+
+### Font Size Harmony
+
+CJK characters appear larger than Latin characters at the same point size. Compensation:
+
+- If body is Calibri 11pt, pair with CJK at 11pt (same size — CJK looks slightly larger but acceptable)
+- If precise visual match needed, CJK can be set 0.5–1pt smaller
+- In practice, same point size is standard — don't over-optimize
+
+### Bold and Italic
+
+- **Chinese/Japanese have no true italic.** Word synthesizes a slant which looks poor
+- Use **bold** for emphasis in CJK text
+- Use 着重号 (emphasis dots) for traditional emphasis: `` on RunProperties
+
+---
+
+## OpenXML Quick Reference
+
+### Set EastAsia Font (C#)
+
+```csharp
+new Run(
+ new RunProperties(
+ new RunFonts { EastAsia = "SimSun", Ascii = "Calibri", HighAnsi = "Calibri" },
+ new FontSize { Val = "32" } // 三号 = 16pt = sz 32
+ ),
+ new Text("这是正文内容")
+);
+```
+
+### Document Defaults (C#)
+
+```csharp
+new DocDefaults(new RunPropertiesDefault(new RunPropertiesBaseStyle(
+ new RunFonts {
+ Ascii = "Calibri", HighAnsi = "Calibri",
+ EastAsia = "Microsoft YaHei"
+ },
+ new Languages { Val = "en-US", EastAsia = "zh-CN" }
+)));
+```
+
+### 公文 Style Definitions (C#)
+
+```csharp
+// Title style — 小标宋 二号 centered
+new Style(
+ new StyleName { Val = "GongWen Title" },
+ new BasedOn { Val = "Normal" },
+ new StyleRunProperties(
+ new RunFonts { EastAsia = "FZXiaoBiaoSong-B05S" },
+ new FontSize { Val = "44" }, // 二号 = 22pt
+ new Bold()
+ ),
+ new StyleParagraphProperties(
+ new Justification { Val = JustificationValues.Center },
+ new SpacingBetweenLines { Line = "560", LineRule = LineSpacingRuleValues.Exact }
+ )
+) { Type = StyleValues.Paragraph, StyleId = "GongWenTitle" };
+
+// Body style — 仿宋_GB2312 三号
+new Style(
+ new StyleName { Val = "GongWen Body" },
+ new StyleRunProperties(
+ new RunFonts { EastAsia = "FangSong_GB2312", Ascii = "FangSong_GB2312" },
+ new FontSize { Val = "32" } // 三号 = 16pt
+ ),
+ new StyleParagraphProperties(
+ new SpacingBetweenLines { Line = "560", LineRule = LineSpacingRuleValues.Exact }
+ )
+) { Type = StyleValues.Paragraph, StyleId = "GongWenBody" };
+```
+
+### Emphasis Dots (着重号)
+
+```csharp
+new RunProperties(new Emphasis { Val = EmphasisMarkValues.Dot });
+```
+
+### East Asian Text Layout
+
+```xml
+
+
+
+
+
+
+
+
+```
diff --git a/skills/minimax-docx/references/cjk_university_template_guide.md b/skills/minimax-docx/references/cjk_university_template_guide.md
new file mode 100644
index 0000000..da4cfb0
--- /dev/null
+++ b/skills/minimax-docx/references/cjk_university_template_guide.md
@@ -0,0 +1,184 @@
+# Chinese University Thesis Template Guide (中国高校论文模板指南)
+
+## Why This Guide Exists
+
+Chinese university thesis templates (.docx) have structural patterns that differ significantly
+from Western templates. Agents that assume Western conventions (Heading1/Heading2/Normal) will
+fail repeatedly. This guide documents the ACTUAL patterns found in Chinese templates.
+
+## Common StyleId Patterns
+
+### Pattern A: Numeric IDs (most common in Chinese Word templates)
+
+| Style Purpose | styleId | w:name | w:basedOn |
+|--------------|---------|--------|-----------|
+| Normal body | `a` | "Normal" | — |
+| Default paragraph font | `a0` | "Default Paragraph Font" | — |
+| Heading 1 (章标题) | `1` | "heading 1" | `a` |
+| Heading 2 (节标题) | `2` | "heading 2" | `a` |
+| Heading 3 (小节标题) | `3` | "heading 3" | `a` |
+| TOC 1 | `11` | "toc 1" | `a` |
+| TOC 2 | `21` | "toc 2" | `a` |
+| TOC 3 | `31` | "toc 3" | `a` |
+| Header | `a3` | "header" | `a` |
+| Footer | `a4` | "footer" | `a` |
+| Table of Contents heading | `10` | "TOC Heading" | `1` |
+
+### Pattern B: English IDs (less common, usually from international templates)
+Standard Heading1/Heading2/Heading3/Normal — these follow the Western pattern.
+
+### Pattern C: Mixed (some Chinese, some English)
+Some templates define custom styles with Chinese names:
+| Style Purpose | styleId | w:name |
+|--------------|---------|--------|
+| 论文标题 | `lunwenbiaoti` | "论文标题" |
+| 章标题 | `zhangbiaoti` | "章标题" |
+| 正文 | `zhengwen` | "正文" |
+
+### How to Identify Which Pattern
+
+```bash
+# Extract all styleIds from the template
+$CLI analyze --input template.docx --styles-only
+
+# Or manually:
+# unzip template.docx word/styles.xml
+# Search for w:styleId= in the extracted file
+```
+
+Look at the first few styleIds. If you see `1`, `2`, `3`, `a`, `a0` → Pattern A.
+If you see `Heading1`, `Normal` → Pattern B.
+
+## Standard Thesis Structure
+
+Chinese university theses follow a highly standardized structure:
+
+```
+┌─────────────────────────────────────┐
+│ 封面 (Cover Page) │ ← Usually 1-2 pages
+│ - 校名、校徽 │
+│ - 论文题目 (title) │
+│ - 作者、导师、院系、日期 │
+├─────────────────────────────────────┤
+│ 学术诚信承诺书 / 独创性声明 │ ← 1 page
+│ (Academic Integrity Declaration) │
+├─────────────────────────────────────┤
+│ 中文摘要 (Chinese Abstract) │ ← 1-2 pages
+│ - "摘 要" heading │
+│ - Abstract body │
+│ - "关键词:" line │
+├─────────────────────────────────────┤
+│ 英文摘要 (English Abstract) │ ← 1-2 pages
+│ - "ABSTRACT" heading │
+│ - Abstract body │
+│ - "Keywords:" line │
+├─────────────────────────────────────┤
+│ 目录 (Table of Contents) │ ← 1-3 pages
+│ - Often inside SDT block │
+│ - Static example entries │
+│ - TOC field code │
+├─────────────────────────────────────┤
+│ 正文 (Body) │ ← Main content
+│ 第1章 绪论 │
+│ 1.1 研究背景 │
+│ 1.2 研究目的和意义 │
+│ 第2章 文献综述 │
+│ ... │
+│ 第N章 结论与展望 │
+├─────────────────────────────────────┤
+│ 参考文献 (References) │ ← Styled differently
+├─────────────────────────────────────┤
+│ 致谢 (Acknowledgments) │ ← Optional
+├─────────────────────────────────────┤
+│ 附录 (Appendices) │ ← Optional
+└─────────────────────────────────────┘
+```
+
+## Identifying Zone Boundaries in Templates
+
+Templates contain EXAMPLE content that must be replaced. Here's how to find the zones:
+
+### Zone A (Front matter) — KEEP from template
+- Starts at: paragraph 0
+- Ends at: the paragraph BEFORE the first chapter heading
+- Contains: cover, declaration, abstracts, TOC
+- How to detect end: search for first paragraph with style `1` (or Heading1) containing "第1章" or "绪论"
+
+### Zone B (Body content) — REPLACE with user content
+- Starts at: first chapter heading ("第1章...")
+- Ends at: "参考文献" heading (inclusive) or last body paragraph before acknowledgments
+- How to detect:
+ ```python
+ for i, el in enumerate(body_elements):
+ text = get_text(el)
+ style = get_style(el)
+ if style in ('1', 'Heading1') and ('第1章' in text or '绪论' in text):
+ zone_b_start = i
+ if '参考文献' in text:
+ zone_b_end = i
+ ```
+
+### Zone C (Back matter) — KEEP from template (or remove)
+- Starts after: 参考文献
+- Contains: 致谢, 附录, final sectPr
+
+## Font Expectations in Chinese Thesis Templates
+
+| Element | Font | Size (字号) | Size (pt) | w:sz |
+|---------|------|------------|-----------|------|
+| 论文标题 | 华文中宋 or 黑体 | 二号 or 小二 | 22pt or 18pt | 44 or 36 |
+| 章标题 (H1) | 黑体 | 三号 | 16pt | 32 |
+| 节标题 (H2) | 黑体 | 四号 | 14pt | 28 |
+| 小节标题 (H3) | 黑体 | 小四 | 12pt | 24 |
+| 正文 | 宋体 | 小四 | 12pt | 24 |
+| 页眉 | 宋体 | 五号 | 10.5pt | 21 |
+| 页脚/页码 | 宋体 | 五号 | 10.5pt | 21 |
+| 表格内容 | 宋体 | 五号 | 10.5pt | 21 |
+| 参考文献条目 | 宋体 | 五号 | 10.5pt | 21 |
+
+## RunFonts for CJK Body Text
+
+```xml
+
+```
+
+For headings:
+```xml
+
+```
+
+IMPORTANT: When cleaning direct formatting, ALWAYS preserve w:eastAsia.
+Removing it causes Chinese text to fall back to the wrong font.
+
+## Common Mistakes with Chinese Templates
+
+1. **Searching for `Heading1`** — Chinese templates use `1`, not `Heading1`
+2. **Clearing all rFonts** — Must keep eastAsia font declarations
+3. **Assuming "第1章" is the first paragraph** — It's typically paragraph 100+ after cover/abstract/TOC
+4. **Ignoring SDT blocks in TOC** — The TOC is wrapped in an SDT, not just field codes
+5. **Wrong line spacing** — Chinese theses typically use fixed 20pt (line="400") or 22pt (line="440"), not the 28pt used in government documents
+6. **Missing section breaks** — Each zone (abstract, TOC, body) usually has its own sectPr for different headers/footers
+
+## Style Mapping Quick Reference
+
+When source document uses Western IDs and template uses Chinese numeric IDs:
+
+```json
+{
+ "Heading1": "1",
+ "Heading2": "2",
+ "Heading3": "3",
+ "Heading4": "3",
+ "Normal": "a",
+ "BodyText": "a",
+ "ListParagraph": "a",
+ "Caption": "a",
+ "TOC1": "11",
+ "TOC2": "21",
+ "TOC3": "31"
+}
+```
+
+When source uses Chinese numeric IDs and template uses Western IDs — reverse the mapping.
diff --git a/skills/minimax-docx/references/comments_guide.md b/skills/minimax-docx/references/comments_guide.md
new file mode 100644
index 0000000..fa12493
--- /dev/null
+++ b/skills/minimax-docx/references/comments_guide.md
@@ -0,0 +1,191 @@
+# Comments System Guide (4-File Architecture)
+
+## Overview
+
+Word comments require coordination across **four XML files** plus references in `document.xml`, `[Content_Types].xml`, and `document.xml.rels`.
+
+---
+
+## The Four Comment Files
+
+### 1. `word/comments.xml` — Main Comment Content
+
+Contains the actual comment text:
+
+```xml
+
+
+
+
+
+
+
+
+
+
+ This needs clarification.
+
+
+
+
+```
+
+Key attributes: `w:id` (unique integer), `w:author`, `w:date` (ISO 8601), `w:initials`.
+
+### 2. `word/commentsExtended.xml` — W15 Extensions
+
+Links comments to paragraphs and tracks resolved status:
+
+```xml
+
+
+
+
+```
+
+- `w15:paraId` — matches the `w14:paraId` of the comment's paragraph in `comments.xml`
+- `w15:done` — `"0"` = open, `"1"` = resolved
+
+### 3. `word/commentsIds.xml` — Persistent ID Mapping
+
+Provides durable IDs that survive copy/paste across documents:
+
+```xml
+
+
+
+
+```
+
+- `w16cid:paraId` — same as `w15:paraId`
+- `w16cid:durableId` — globally unique identifier (8-digit hex)
+
+### 4. `word/commentsExtensible.xml` — W16 Extensions
+
+Modern comment extensions (used in newer Word versions):
+
+```xml
+
+
+
+
+```
+
+---
+
+## Document.xml References
+
+Comments are anchored in document content using three elements:
+
+```xml
+
+
+ This text has a comment.
+
+
+
+
+
+
+```
+
+- `w:commentRangeStart` — marks where the commented text begins
+- `w:commentRangeEnd` — marks where the commented text ends
+- `w:commentReference` — the visible comment marker (superscript number), placed in a run after the range end
+
+The `w:id` on all three must match the `w:id` in `comments.xml`.
+
+---
+
+## Content Types Registration
+
+Add to `[Content_Types].xml`:
+
+```xml
+
+
+
+
+```
+
+---
+
+## Relationship Registration
+
+Add to `word/_rels/document.xml.rels`:
+
+```xml
+
+
+
+
+```
+
+---
+
+## Step-by-Step: Adding a New Comment
+
+1. **Choose a unique comment ID** (scan existing `w:id` values, use max + 1)
+2. **Generate a paraId** (8-character hex, e.g., `"1A2B3C4D"`) and durableId (8-digit hex)
+3. **Add to `comments.xml`**: Create `w:comment` element with content
+4. **Add to `commentsExtended.xml`**: Create `w15:commentEx` with `paraId`, `done="0"`
+5. **Add to `commentsIds.xml`**: Create `w16cid:commentId` with `paraId` and `durableId`
+6. **Add to `commentsExtensible.xml`**: Create `w16cex:commentExtensible` with `durableId` and `dateUtc`
+7. **Add to `document.xml`**: Insert `w:commentRangeStart`, `w:commentRangeEnd`, and `w:commentReference` around target text
+8. **Verify `[Content_Types].xml`** and `document.xml.rels` have entries for all 4 files
+
+---
+
+## Step-by-Step: Adding a Reply
+
+Replies are comments whose paragraph's `w14:paraId` links to a parent comment:
+
+1. Create a new `w:comment` in `comments.xml` with a new `w:id`
+2. In `commentsExtended.xml`, add `w15:commentEx` with:
+ - `w15:paraId` = new paragraph ID
+ - `w15:paraIdParent` = the `paraId` of the comment being replied to
+ - `w15:done="0"`
+3. Add entries in `commentsIds.xml` and `commentsExtensible.xml`
+4. In `document.xml`, the reply does NOT need its own range markers — it shares the parent's range
+
+```xml
+
+
+```
+
+---
+
+## Step-by-Step: Resolving a Comment
+
+Set `w15:done="1"` on the comment's `w15:commentEx` entry:
+
+```xml
+
+
+
+
+
+```
+
+This marks the comment (and all its replies) as resolved. The comment remains visible but appears grayed out in Word.
+
+---
+
+## Minimum Viable Comment
+
+At minimum, a working comment requires:
+1. `comments.xml` with the `w:comment` element
+2. `document.xml` with range markers and reference
+3. Relationship in `document.xml.rels`
+4. Content type in `[Content_Types].xml`
+
+The extended files (`commentsExtended`, `commentsIds`, `commentsExtensible`) are optional but recommended for full compatibility with modern Word.
diff --git a/skills/minimax-docx/references/design_good_bad_examples.md b/skills/minimax-docx/references/design_good_bad_examples.md
new file mode 100644
index 0000000..82b7c50
--- /dev/null
+++ b/skills/minimax-docx/references/design_good_bad_examples.md
@@ -0,0 +1,829 @@
+# GOOD vs BAD Document Design — Concrete OpenXML Examples
+
+A side-by-side reference showing common design mistakes and their fixes, with exact OpenXML parameter values. Use this to develop an intuitive sense of what makes a document look professional versus amateur.
+
+Format: Each comparison shows the **BAD** version first (the mistake), then the **GOOD** version (the fix), with OpenXML markup and a short explanation.
+
+---
+
+## 1. Font Size Disasters
+
+### 1a. No Hierarchy — Everything the Same Size
+
+**BAD: Body=12pt, H1=12pt bold**
+```
+┌──────────────────────────────────┐
+│ INTRODUCTION │ ← 12pt bold... same visual weight
+│ This is the body text of the │ ← 12pt regular
+│ report. It discusses findings │
+│ from the quarterly review. │
+│ METHODOLOGY │ ← Where does the section start?
+│ We collected data from three │
+│ sources across the enterprise. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+
+```
+
+**GOOD: Modular scale — body=11pt, H3=13pt, H2=16pt, H1=20pt**
+```
+┌──────────────────────────────────┐
+│ │
+│ Introduction │ ← 20pt, clearly a title
+│ │
+│ This is the body text of the │ ← 11pt, comfortable reading size
+│ report. It discusses findings │
+│ from the quarterly review. │
+│ │
+│ Methodology │ ← 20pt, section break is obvious
+│ │
+│ We collected data from three │
+│ sources across the enterprise. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+
+
+
+
+
+```
+**Why better:** A clear size progression (ratio ~1.25x per step) lets readers instantly identify structure without reading a word.
+
+---
+
+### 1b. Too Much Contrast — Children's Book Look
+
+**BAD: H1=28pt with body=10pt (ratio 2.8x)**
+```
+┌──────────────────────────────────┐
+│ │
+│ QUARTERLY REPORT │ ← 28pt, dominates the page
+│ │
+│ This is body text set very small │ ← 10pt, straining to read
+│ and the contrast with the title │
+│ makes it feel like a poster. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+```
+
+**GOOD: H1=20pt with body=11pt (ratio ~1.8x)**
+```xml
+
+
+```
+**Why better:** A heading-to-body ratio between 1.5x and 2.0x reads as "structured" rather than "shouting."
+
+---
+
+## 2. Spacing Crimes
+
+### 2a. Wall of Text — No Paragraph or Line Spacing
+
+**BAD: Single line spacing, 0pt between paragraphs**
+```
+┌──────────────────────────────────┐
+│The findings indicate a strong │
+│correlation between training hours│
+│and performance metrics. │
+│Further analysis revealed that │ ← No gap — where does the new
+│departments with higher budgets │ paragraph start?
+│achieved better outcomes in all │
+│measured categories. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+
+```
+
+**GOOD: 1.15x line spacing, 8pt after each paragraph**
+```
+┌──────────────────────────────────┐
+│The findings indicate a strong │
+│correlation between training │ ← Slightly more air between lines
+│hours and performance metrics. │
+│ │ ← 8pt gap signals new paragraph
+│Further analysis revealed that │
+│departments with higher budgets │
+│achieved better outcomes in all │
+│measured categories. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+
+```
+**Why better:** Line spacing gives each line room to breathe; paragraph spacing separates ideas without wasting a full blank line.
+
+---
+
+### 2b. Floating Headings — Same Space Above and Below
+
+**BAD: 12pt before and 12pt after heading**
+```
+┌──────────────────────────────────┐
+│ ...end of previous section. │
+│ │ ← 12pt gap
+│ Section Two │ ← Heading floats in the middle
+│ │ ← 12pt gap
+│ Start of section two content. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+```
+
+**GOOD: 24pt before, 8pt after heading**
+```
+┌──────────────────────────────────┐
+│ ...end of previous section. │
+│ │
+│ │ ← 24pt gap — clear section break
+│ Section Two │ ← Heading is close to its content
+│ │ ← 8pt gap
+│ Start of section two content. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+```
+**Why better:** Proximity principle: a heading belongs to the text that follows it, so more space above and less space below anchors it to its content.
+
+---
+
+### 2c. Wasteful Gaps — Huge Spacing Everywhere
+
+**BAD: 24pt after every paragraph, including body text**
+```
+┌──────────────────────────────────┐
+│ First paragraph of text here. │
+│ │
+│ │ ← 24pt gap after every paragraph
+│ │
+│ Second paragraph of text here. │
+│ │
+│ │
+│ │
+│ Third paragraph. │ ← Document looks mostly white space
+└──────────────────────────────────┘
+```
+```xml
+
+```
+
+**GOOD: Proportional spacing — body=8pt, H2=6pt after, H1=10pt after**
+```xml
+
+
+
+
+
+
+```
+**Why better:** Spacing should vary by element role, creating a visual rhythm rather than uniform gaps.
+
+---
+
+## 3. Margin Mistakes
+
+### 3a. Cramped Margins — Text Running to the Edge
+
+**BAD: 0.5in margins all around**
+```
+┌────────────────────────────────────────────────┐
+│Text starts almost at the paper edge and runs │
+│all the way across making extremely long lines │
+│that are hard to track from end back to start. │
+│The eye loses its place on every line return. │
+└────────────────────────────────────────────────┘
+```
+```xml
+
+
+```
+
+**GOOD: 1in margins (standard)**
+```xml
+
+
+```
+**Why better:** Optimal line length is 60-75 characters. At 11pt Calibri, 6.5in width achieves roughly 70 characters per line.
+
+---
+
+### 3b. Over-Padded Margins — Looks Like the Content is Hiding
+
+**BAD: 2in margins on a short document**
+```xml
+
+
+```
+
+**GOOD: 1in standard, or 1.25in for formal documents**
+```xml
+
+
+
+
+
+```
+**Why better:** Margins should frame the content, not overwhelm it. 1-1.25in works for virtually all business and academic documents.
+
+---
+
+## 4. Table Ugliness
+
+### 4a. Prison Grid — Full Borders on Every Cell
+
+**BAD: Every cell with 1pt borders on all four sides**
+```
+┌───────┬───────┬───────┬───────┐
+│ Name │ Dept │ Score │ Grade │
+├───────┼───────┼───────┼───────┤
+│ Alice │ Eng │ 92 │ A │
+├───────┼───────┼───────┼───────┤
+│ Bob │ Sales │ 85 │ B │
+├───────┼───────┼───────┼───────┤
+│ Carol │ Eng │ 78 │ C+ │
+└───────┴───────┴───────┴───────┘
+```
+```xml
+
+
+
+
+
+
+```
+
+**GOOD: Three-line table (三线表) — top thick, header-bottom medium, table-bottom thick**
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ← 1.5pt top border
+ Name Dept Score Grade
+────────────────────────────────── ← 0.75pt header separator
+ Alice Eng 92 A
+ Bob Sales 85 B
+ Carol Eng 78 C+
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ← 1.5pt bottom border
+```
+```xml
+
+
+
+
+
+
+
+
+
+
+
+```
+**Why better:** Removing inner borders lets the eye scan data freely. Three lines provide structure without visual clutter.
+
+---
+
+### 4b. Text Touching Borders — No Cell Padding
+
+**BAD: Zero cell margins**
+```
+┌──────────┬──────────┐
+│Name │Department│ ← Text cramped against borders
+├──────────┼──────────┤
+│Alice │Engineering│
+└──────────┴──────────┘
+```
+```xml
+
+
+
+
+
+
+```
+
+**GOOD: 0.08in vertical, 0.12in horizontal padding**
+```xml
+
+
+
+
+
+
+```
+**Why better:** Padding gives text breathing room inside cells, making every value easier to read.
+
+---
+
+### 4c. Invisible Headers — Header Row Same Style as Data
+
+**BAD: Header row indistinguishable from data**
+```xml
+
+
+```
+
+**GOOD: Bold header text, subtle background fill, bottom border**
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+**Why better:** Distinct header styling lets readers instantly locate column meanings, especially in long tables that span pages. The `w:tblHeader` element ensures the header row repeats on every page.
+
+---
+
+## 5. Font Pairing Failures
+
+### 5a. Visual Chaos — Too Many Fonts
+
+**BAD: 4+ fonts in one document**
+```xml
+
+
+
+
+
+
+
+
+```
+
+**GOOD: One font family with weight variation, or two complementary families**
+```xml
+
+
+
+
+
+
+
+
+```
+**Why better:** Limiting to one or two font families creates visual coherence. Vary by size and weight, not by font.
+
+---
+
+### 5b. Mismatched Personality — Comic Sans Meets Times New Roman
+
+**BAD:**
+```xml
+
+
+```
+
+**GOOD: Fonts with compatible character**
+```xml
+
+
+```
+**Why better:** Paired fonts should share a similar level of formality and geometric character. Comic Sans is playful/informal; Times New Roman is formal/traditional. They clash.
+
+---
+
+### 5c. Everything Bold — Nothing Stands Out
+
+**BAD: Bold on body, headings, captions, everything**
+```xml
+
+
+
+```
+
+**GOOD: Bold reserved for headings and key terms only**
+```xml
+
+
+
+
+
+```
+**Why better:** When everything is emphasized, nothing is emphasized. Bold should be a signal, not a default.
+
+---
+
+## 6. Color Abuse
+
+### 6a. Rainbow Headings
+
+**BAD: Each heading level a different bright color**
+```xml
+
+
+
+```
+
+**GOOD: Single accent color for headings, black or dark gray for body**
+```xml
+
+
+
+
+
+
+```
+**Why better:** A single accent color establishes brand consistency. Multiple bright colors compete for attention and look unprofessional.
+
+---
+
+### 6b. Low Contrast — Light Gray on White
+
+**BAD: #CCCCCC text on white background**
+```xml
+
+
+```
+
+**GOOD: #333333 text on white**
+```xml
+
+
+```
+**Why better:** Sufficient contrast is not just an accessibility requirement; it makes text physically easier to read for everyone, especially in printed documents.
+
+---
+
+### 6c. Bright Body Text
+
+**BAD: Body text in a saturated color**
+```xml
+
+```
+
+**GOOD: Color reserved for headings and inline accents only**
+```xml
+
+
+
+
+```
+**Why better:** Colored body text causes eye fatigue over long reading. Reserve color for elements that need to attract attention (headings, links, warnings).
+
+---
+
+## 7. List Formatting Issues
+
+### 7a. Bullet at the Margin — No Indent
+
+**BAD: List items start at the left margin**
+```
+┌──────────────────────────────────┐
+│Here is a paragraph of text. │
+│• First item │ ← Bullet at margin, no indent
+│• Second item │
+│• Third item │
+│Next paragraph continues here. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+```
+
+**GOOD: 0.25in left indent with hanging indent for the bullet**
+```
+┌──────────────────────────────────┐
+│Here is a paragraph of text. │
+│ • First item │ ← Indented, clearly a list
+│ • Second item │
+│ • Third item │
+│Next paragraph continues here. │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+
+
+
+
+```
+For nested lists, increment by 360 twips per level:
+```xml
+
+
+
+
+```
+**Why better:** Indentation visually separates lists from body text and makes nesting levels clear.
+
+---
+
+### 7b. List Items with Full Paragraph Spacing
+
+**BAD: List items have the same 8-10pt spacing as body paragraphs**
+```
+┌──────────────────────────────────┐
+│ • First item │
+│ │ ← 10pt gap — looks like separate
+│ • Second item │ paragraphs, not a list
+│ │
+│ • Third item │
+└──────────────────────────────────┘
+```
+```xml
+
+```
+
+**GOOD: Tight spacing between list items (2-4pt)**
+```
+┌──────────────────────────────────┐
+│ • First item │
+│ • Second item │ ← 2pt gap — cohesive list
+│ • Third item │
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+```
+**Why better:** Tight spacing groups list items as a single unit, matching how readers expect a list to behave.
+
+---
+
+## 8. Header/Footer Problems
+
+### 8a. Header Text Too Large — Competes with Body
+
+**BAD: Header in 12pt, same as body**
+```
+┌──────────────────────────────────┐
+│ Quarterly Report - Q3 2025 │ ← 12pt header, same as body
+│──────────────────────────────────│
+│ Introduction │
+│ This is the body text... │ ← 12pt body — header distracts
+└──────────────────────────────────┘
+```
+```xml
+
+
+```
+
+**GOOD: Header in 9pt, gray color, subtle**
+```
+┌──────────────────────────────────┐
+│ Quarterly Report - Q3 2025 │ ← 9pt, gray — present but quiet
+│──────────────────────────────────│
+│ Introduction │
+│ This is the body text... │ ← Body stands out as primary
+└──────────────────────────────────┘
+```
+```xml
+
+
+
+
+
+
+
+
+
+
+```
+**Why better:** Headers are reference information, not primary content. They should be legible but visually subordinate.
+
+---
+
+### 8b. No Page Numbers on a Long Document
+
+**BAD: 20-page document with no page numbers**
+```xml
+
+```
+
+**GOOD: Page numbers in footer, right-aligned or centered**
+```xml
+
+
+
+
+
+
+
+
+
+
+
+ PAGE
+
+
+
+
+
+ 1
+
+
+
+
+
+```
+**Why better:** Page numbers are essential for navigation in any document over ~3 pages. Readers need to reference specific pages, and printed documents need an ordering mechanism.
+
+---
+
+## 9. CJK-Specific Mistakes
+
+### 9a. Using Italic for Chinese Emphasis
+
+**BAD: Italic applied to Chinese text**
+```xml
+
+
+
+
+
+```
+CJK glyphs have no true italic form. The renderer applies a synthetic slant that looks broken and ugly — characters appear to lean awkwardly.
+
+**GOOD: Use bold or emphasis dots (着重号) for Chinese emphasis**
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+**Why better:** Chinese typography has its own emphasis traditions. Bold and emphasis dots are native CJK conventions; italic is a Latin-script concept that does not translate.
+
+---
+
+### 9b. Latin Font for Chinese Characters
+
+**BAD: Only ASCII font set, no EastAsia font specified**
+```xml
+
+
+
+
+
+```
+
+**GOOD: Explicit EastAsia font alongside ASCII font**
+```xml
+
+
+
+
+```
+For formal/academic Chinese documents:
+```xml
+
+
+
+
+```
+**Why better:** Setting `w:eastAsia` ensures Chinese characters render in a font designed for CJK glyphs, with correct stroke widths, spacing, and metrics.
+
+---
+
+### 9c. English Line Spacing for Dense CJK Text
+
+**BAD: 1.15x line spacing for Chinese body text**
+```xml
+
+```
+CJK characters are taller and denser than Latin letters. At 1.15x, lines of Chinese text feel cramped and hard to read.
+
+**GOOD: 1.5x line spacing or fixed 28pt for CJK body at 12pt (小四)**
+```xml
+
+
+
+
+
+```
+For 公文 (government documents) at 三号/16pt body:
+```xml
+
+```
+**Why better:** CJK characters occupy a full em square with no ascenders/descenders providing natural gaps. Extra line spacing compensates, improving readability of dense text blocks.
+
+---
+
+## 10. Overall Document Feel
+
+### Student Homework vs Professional Document
+
+**BAD: "Student homework" — every setting is Word's default, no intentional choices**
+```xml
+
+
+
+
+
+
+
+
+```
+
+**GOOD: Intentional design at every level**
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+**Why better:** Professional documents result from deliberate, consistent choices across all design dimensions. Each element reinforces the same visual language. The reader may not consciously notice good typography, but they feel the difference in credibility and readability.
+
+---
+
+## Quick Reference: Safe Defaults
+
+A cheat sheet of values that produce a professional result for most Western business documents:
+
+| Element | Value | OpenXML |
+|---------|-------|---------|
+| Body font | Calibri 11pt | `w:sz="22"` |
+| H1 | Calibri Light 20pt | `w:sz="40"` |
+| H2 | Calibri Light 16pt | `w:sz="32"` |
+| H3 | Calibri 13pt bold | `w:sz="26"`, `w:b` |
+| Body color | #333333 | `w:color="333333"` |
+| Heading color | #1F4E79 | `w:color="1F4E79"` |
+| Line spacing | 1.15x | `w:line="276" w:lineRule="auto"` |
+| Para spacing after | 8pt | `w:after="160"` |
+| H1 spacing | 24pt before, 10pt after | `w:before="480" w:after="200"` |
+| H2 spacing | 16pt before, 6pt after | `w:before="320" w:after="120"` |
+| Margins | 1in all around | `w:pgMar` all `"1440"` |
+| Table cell padding | 0.08in / 0.12in | `w:w="115"` / `w:w="173"` |
+| Header/footer size | 9pt gray | `w:sz="18" w:color="808080"` |
+| List indent | 0.25in per level | `w:left="360" w:hanging="360"` |
+| List item spacing | 2pt after | `w:after="40"` |
+
+For CJK documents, adjust: body font to SimSun/YaHei, line spacing to 1.5x (`w:line="360"`), and set `w:eastAsia` on all `w:rFonts`.
diff --git a/skills/minimax-docx/references/design_principles.md b/skills/minimax-docx/references/design_principles.md
new file mode 100644
index 0000000..6d81dd3
--- /dev/null
+++ b/skills/minimax-docx/references/design_principles.md
@@ -0,0 +1,819 @@
+# Design Principles for Document Typography
+
+WHY certain typographic choices look good -- the perceptual and psychological
+reasons behind professional document design. Use this to make judgment calls
+when exact specs are not provided.
+
+## Table of Contents
+
+1. [White Space & Breathing Room](#1-white-space--breathing-room)
+2. [Contrast & Scale](#2-contrast--scale)
+3. [Proximity & Grouping](#3-proximity--grouping)
+4. [Alignment & Grid](#4-alignment--grid)
+5. [Repetition & Consistency](#5-repetition--consistency)
+6. [Visual Hierarchy & Flow](#6-visual-hierarchy--flow)
+
+---
+
+## 1. White Space & Breathing Room
+
+### Why It Works
+
+The human eye does not read continuously. It jumps in saccades, fixating on
+small clusters of words. White space provides landing zones for these fixations
+and gives the reader's peripheral vision a "frame" that makes each text block
+feel manageable. When a page is packed to the edges, every glance returns more
+text than working memory can buffer, triggering fatigue and avoidance.
+
+Research on content density consistently shows:
+
+- **60-70% content coverage** feels comfortable and professional.
+- **80%+** starts to feel dense and bureaucratic.
+- **90%+** feels oppressive -- the reader unconsciously rushes or skips.
+- **Below 50%** feels wasteful or pretentious (unless intentional, like poetry).
+
+Wider margins also carry cultural signals. Academic and luxury documents use
+generous margins (1.25-1.5 inches). Internal memos and drafts use narrower
+margins (0.75-1.0 inches). The margin width tells the reader how much care
+went into the document before they read a single word.
+
+Line spacing has a direct physiological basis: the eye must track back to the
+start of the next line after each line break. If lines are too close, the eye
+"slips" to the wrong line. If too far apart, the eye loses its sense of
+continuity. The sweet spot is 120-145% of the font size.
+
+**Rule of thumb: when in doubt, add more space, not less.**
+
+### Good Example
+
+```
+Margins: 1 inch (1440 twips) all sides for business documents.
+Line spacing: 1.15 (276 twips at 240 twips-per-line = 115%).
+Paragraph spacing after: 8pt (160 twips) between body paragraphs.
+```
+
+```xml
+
+
+
+
+
+
+
+```
+
+This produces a page where content occupies roughly 65% of the area. The
+reader sees clear top/bottom breathing room, and paragraphs are distinct
+without feeling disconnected.
+
+```
+ Page layout (good):
+ +----------------------------------+
+ | 1" margin |
+ | +------------------------+ |
+ | | Heading | |
+ | | | |
+ | | Body text here with | |
+ | | comfortable spacing | |
+ | | between lines. | |
+ | | | | <- visible gap between paragraphs
+ | | Another paragraph of | |
+ | | body text follows. | |
+ | | | |
+ | +------------------------+ |
+ | 1" margin |
+ +----------------------------------+
+```
+
+### Bad Example
+
+```xml
+
+
+
+
+
+
+
+```
+
+This fills ~85% of the page. Text runs edge-to-edge with no visual rest stops.
+The reader sees a wall of text.
+
+```
+ Page layout (bad):
+ +----------------------------------+
+ | Heading |
+ | Body text crammed right up to |
+ | the margins with no spacing |
+ | between lines or paragraphs. |
+ | Another paragraph starts here |
+ | and the reader cannot tell where |
+ | one idea ends and another begins |
+ | because everything blurs into a |
+ | single dense block of text. |
+ +----------------------------------+
+```
+
+### Quick Test
+
+1. Zoom out to 50% in your document viewer. If you cannot see clear "channels"
+ of white between text blocks, the spacing is too tight.
+2. Print a test page. Hold it at arm's length. The text area should look like
+ a rectangle floating in white, not filling the page.
+3. Check: is the line spacing value at least 264 (`w:line` for 1.1x) for body
+ text? If it is 240 (single), it is too tight for anything over 10pt.
+
+---
+
+## 2. Contrast & Scale
+
+### Why It Works
+
+The brain processes visual hierarchy through relative difference, not absolute
+size. A 20pt heading above 11pt body text creates a clear "this is important"
+signal. But if every heading is 20pt and every sub-heading is 19pt, the brain
+cannot distinguish them -- they merge into the same level.
+
+The key insight is **modular scale**: font sizes that grow by a consistent
+ratio. This mirrors natural proportions and feels harmonious for the same
+reason musical intervals do.
+
+Common scales and their character:
+
+| Ratio | Name | Character | Example progression (from 11pt) |
+|-------|----------------|---------------------------------|---------------------------------|
+| 1.200 | Minor third | Subtle, refined | 11 → 13.2 → 15.8 → 19.0 |
+| 1.250 | Major third | Balanced, professional | 11 → 13.75 → 17.2 → 21.5 |
+| 1.333 | Perfect fourth | Strong, authoritative | 11 → 14.7 → 19.5 → 26.0 |
+| 1.414 | Augmented 4th | Dramatic, presentation-style | 11 → 15.6 → 22.0 → 31.1 |
+
+For most business documents, 1.25 (major third) works best:
+
+```
+Body = 11pt (w:sz="22")
+H3 = 13pt (w:sz="26") -- 11 * 1.25 ≈ 13.75, round to 13
+H2 = 16pt (w:sz="32") -- 13 * 1.25 ≈ 16.25, round to 16
+H1 = 20pt (w:sz="40") -- 16 * 1.25 = 20
+```
+
+Beyond size, **weight contrast** creates hierarchy without consuming vertical
+space. Regular (400) vs Bold (700) is visible at any size. Semi-bold (600) vs
+Regular is subtle and best avoided unless you also vary size or color.
+
+**Color contrast** adds a third dimension. Dark blue headings (#1F3864) against
+softer dark gray body text (#333333) signals "heading" without needing a huge
+size jump. Pure black (#000000) body text is harsher than necessary on white
+backgrounds -- #333333 or #2D2D2D reduces glare without losing legibility.
+
+### Good Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+```
+ Visual hierarchy (good):
+
+ [████████████████████] <- H1: 20pt bold navy (clearly dominant)
+ (generous space)
+ [██████████████] <- H2: 16pt bold navy (distinct step down)
+ (moderate space)
+ [████████████] <- H3: 13pt bold navy (smaller but still bold)
+ [░░░░░░░░░░░░░░░░░░░░░░] <- Body: 11pt regular gray
+ [░░░░░░░░░░░░░░░░░░░░░░]
+ [░░░░░░░░░░░░░░░░░░░░░░]
+```
+
+Each level is visually distinct from its neighbors. You can identify the
+hierarchy even in peripheral vision.
+
+### Bad Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+Problems:
+- H3 (12pt bold) and body (12pt regular) differ only by weight -- too subtle.
+- H1 (14pt) to H2 (13pt) is a 1pt step -- invisible at reading distance.
+- Everything is pure black so color provides no differentiating signal.
+- The ratio between levels is ~1.07, far too flat.
+
+### Quick Test
+
+1. **The squint test**: blur your eyes or step back from the screen. Can you
+ count the number of heading levels? If two levels merge, their contrast
+ is insufficient.
+2. **Ratio check**: divide each heading size by the next smaller size. If any
+ ratio is below 1.15, the levels will look too similar.
+3. **Color check**: do headings look distinct from body text when you glance
+ at the page? If everything is the same color, you are relying solely on
+ size/weight, which limits your hierarchy to ~3 effective levels.
+
+---
+
+## 3. Proximity & Grouping
+
+### Why It Works
+
+The Gestalt principle of proximity: items that are close together are perceived
+as belonging to the same group. In document typography, this means a heading
+must be **closer to the content it introduces** than to the content above it.
+
+If a heading sits equidistant between two paragraphs, it looks orphaned -- the
+reader's eye does not know if it belongs to the text above or below. The fix
+is asymmetric spacing: **large space before the heading, small space after**.
+
+The recommended ratio is 2:1 or 3:1 (space-before : space-after).
+
+This same principle applies to:
+- **List items**: spacing between items should be less than spacing between
+ paragraphs. Items in a list are a group and should visually cluster.
+- **Captions**: a figure caption should be close to its figure, not floating
+ in the middle between the figure and the next paragraph.
+- **Table titles**: the title sits close above the table, with more space
+ separating the title from preceding text.
+
+### Good Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+```
+ Proximity (good):
+
+ ...end of previous section text.
+ <- 18pt gap (w:before="360")
+ ## Section Heading
+ <- 6pt gap (w:after="120")
+ First paragraph of new section
+ continues here with content.
+ <- 8pt gap (w:after="160")
+ Second paragraph follows.
+
+ The heading clearly "belongs to" the text below it.
+```
+
+```
+ List grouping (good):
+
+ Consider these factors:
+ - First item <- 2pt gap between items
+ - Second item <- items cluster as a group
+ - Third item
+ <- 8pt gap after list
+ The next paragraph starts here.
+```
+
+### Bad Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+```
+
+```
+ Proximity (bad):
+
+ ...end of previous section text.
+ <- 12pt gap
+ ## Section Heading
+ <- 12pt gap (same!)
+ First paragraph of new section.
+
+ The heading floats between sections. It is unclear what it belongs to.
+```
+
+```
+ List grouping (bad):
+
+ Consider these factors:
+ <- 10pt gap
+ - First item
+ <- 10pt gap (same as paragraphs)
+ - Second item
+ <- 10pt gap
+ - Third item
+ <- 10pt gap
+ Next paragraph.
+
+ The list does not feel like a group. Each item looks like a
+ separate paragraph that happens to have a bullet.
+```
+
+### Quick Test
+
+1. **Cover test**: cover the heading text. Looking only at the whitespace,
+ can you tell which block of text the heading belongs to? If the gaps above
+ and below are equal, the answer is "no."
+2. **Number check**: `w:before` on headings should be at least 2x `w:after`.
+ Common good values: before=360 / after=120, or before=240 / after=80.
+3. **List check**: `w:after` on list items should be less than half of
+ `w:after` on body paragraphs. If body uses 160, list items should use
+ 40-60.
+
+---
+
+## 4. Alignment & Grid
+
+### Why It Works
+
+Alignment creates invisible lines that the eye follows down the page. When
+elements share the same left edge, the reader perceives order and intention.
+When elements are slightly misaligned (off by a few twips), the page looks
+sloppy even if the reader cannot consciously identify why.
+
+**Left-align vs Justify:**
+
+- **Left-aligned** (ragged right) is best for English and other Latin-script
+ languages. The uneven right edge actually helps reading because each line
+ has a unique silhouette, making it easier for the eye to find the next line.
+ Justified text forces uneven word spacing that creates distracting "rivers"
+ of white running vertically through paragraphs.
+
+- **Justified** is best for CJK text. Chinese, Japanese, and Korean characters
+ are monospaced by design -- each occupies the same cell in an invisible grid.
+ Justification preserves this grid perfectly. Ragged right in CJK text breaks
+ the grid and looks untidy.
+
+**Indentation rule:** Use first-line indent OR paragraph spacing to separate
+paragraphs -- never both. They serve the same purpose (marking paragraph
+boundaries). Using both wastes space and creates visual stutter.
+
+- Western convention: paragraph spacing (no indent) is more modern.
+- CJK convention: first-line indent of 2 characters is standard.
+- Academic convention: first-line indent of 0.5 inch is traditional.
+
+### Good Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+```
+ English paragraph separation (good -- spacing, no indent):
+
+ This is the first paragraph with some text
+ that wraps to a second line naturally.
+
+ This is the second paragraph. The gap above
+ clearly marks the boundary.
+
+
+ CJK paragraph separation (good -- indent, no spacing):
+
+ 第一段正文内容从这里开始,使用两个字符
+ 的首行缩进来标记段落边界。
+ 第二段紧跟其后,没有段间距,但首行缩进
+ 清晰地标识了新段落的开始。
+```
+
+### Bad Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+Problems:
+- Justified English text with narrow columns creates uneven word gaps.
+- Using both first-line indent AND paragraph spacing is redundant.
+- Left-aligned CJK breaks the character grid that CJK readers expect.
+- CJK with spacing-based separation looks like translated western layout.
+
+### Quick Test
+
+1. **River test**: in justified English text, squint and look for vertical
+ white streaks running through the paragraph. If you see them, switch to
+ left-align or increase the column width.
+2. **Double signal check**: does the document use BOTH first-line indent AND
+ paragraph spacing? If yes, remove one. Choose indent for CJK/academic,
+ spacing for modern western.
+3. **Tab alignment**: if you use tabs for columns, do all tab stops across
+ the document use the same positions? Inconsistent tab stops create jagged
+ invisible grid lines.
+
+---
+
+## 5. Repetition & Consistency
+
+### Why It Works
+
+Consistency is a trust signal. When a reader sees that every H2 looks the same,
+every table follows the same pattern, and every page number sits in the same
+spot, they unconsciously trust that the document was crafted with care. A single
+inconsistency -- one H2 that is 15pt instead of 14pt, one table with different
+borders -- breaks that trust and makes the reader question the content.
+
+Consistency also reduces cognitive load. Once the reader learns "bold dark blue
+= section heading," they stop spending mental effort on identifying structure
+and focus entirely on content. Every inconsistency forces them to re-evaluate:
+"Is this a different kind of heading, or did someone just forget to apply the
+style?"
+
+The implementation rule is simple: **use named styles, not direct formatting.**
+If you define Heading2 as a style and apply it everywhere, consistency is
+automatic. If you manually set font size, bold, and color on each heading
+individually, inconsistency is inevitable.
+
+### Good Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Market Analysis
+
+```
+
+When using a table style, define it once and reference it for every table:
+
+```xml
+
+
+
+
+
+```
+
+### Bad Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+ Market Analysis
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Financial Overview
+
+
+```
+
+Problems:
+- No style references -- everything is direct formatting.
+- Second H2 has different size (30 vs 32), color, and spacing.
+- If there are 20 headings, each could drift slightly differently.
+- Changing the design later means editing every heading individually.
+
+### Quick Test
+
+1. **Style audit**: does every paragraph reference a `w:pStyle`? If you find
+ paragraphs with only direct formatting and no style, that is a consistency
+ risk.
+2. **Search for variance**: search the XML for all `w:sz` values used with
+ `w:b` (bold). If you find three different sizes for what should be the same
+ heading level, there is an inconsistency.
+3. **Table check**: do all tables in the document reference the same
+ `w:tblStyle`? If some tables have manual border definitions while others
+ use a style, the document will look patchy.
+4. **Page numbers**: check that header/footer content is defined in the
+ default section properties and inherited by all sections, not redefined
+ inconsistently in each section.
+
+---
+
+## 6. Visual Hierarchy & Flow
+
+### Why It Works
+
+A well-designed document guides the reader's eye in a predictable path:
+title at the top, subtitle below it, section headings as signposts, body text
+as the main content, footnotes and captions as supporting details. This flow
+mirrors reading priority -- the most important information is the most visually
+prominent.
+
+Each level in the hierarchy must be **distinguishable from its adjacent
+levels**. It is not enough for H1 to differ from body text; H1 must also
+clearly differ from H2, and H2 from H3. If any two adjacent levels are too
+similar, the hierarchy collapses at that point.
+
+Effective hierarchy uses **multiple simultaneous signals**:
+
+| Level | Size | Weight | Color | Spacing above |
+|----------|-------|---------|---------|---------------|
+| Title | 26pt | Bold | #1F3864 | 0 (top) |
+| Subtitle | 15pt | Regular | #4472C4 | 4pt |
+| H1 | 20pt | Bold | #1F3864 | 24pt |
+| H2 | 16pt | Bold | #1F3864 | 18pt |
+| H3 | 13pt | Bold | #1F3864 | 12pt |
+| Body | 11pt | Regular | #333333 | 0pt |
+| Caption | 9pt | Italic | #666666 | 4pt |
+| Footnote | 9pt | Regular | #666666 | 0pt |
+
+Notice how each level differs from its neighbors on at least two dimensions
+(size + weight, or size + color, or weight + style). Single-dimension
+differences are fragile and can be missed.
+
+**Section breaks** create rhythm in long documents. A page break before each
+major section (H1) gives the reader a mental reset. Within sections, consistent
+heading + body patterns create a predictable cadence that makes long documents
+less intimidating.
+
+### Good Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+```
+ Visual flow (good):
+
+ +----------------------------------+
+ | |
+ | ANNUAL REPORT 2025 | <- Title: 26pt bold navy centered
+ | Acme Corporation | <- Subtitle: 15pt regular blue
+ | |
+ | |
+ +----------------------------------+
+
+ +----------------------------------+
+ | |
+ | 1. Executive Summary | <- H1: 20pt bold navy (page break)
+ | |
+ | Body text introducing the | <- Body: 11pt regular gray
+ | main findings of the year. |
+ | |
+ | 1.1 Revenue Highlights | <- H2: 16pt bold navy
+ | |
+ | Revenue grew by 23% year | <- Body
+ | over year, driven by... |
+ | |
+ | Figure 1: Revenue Growth | <- Caption: 9pt italic gray
+ | |
+ +----------------------------------+
+
+ Each level is immediately identifiable. The eye flows naturally
+ from title -> heading -> body -> caption.
+```
+
+### Bad Example
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+Problems:
+- H1 at 14pt is too close to body at 11pt (ratio 1.27 -- acceptable in
+ isolation but with black color matching body, the hierarchy is weak).
+- Caption is indistinguishable from body text.
+- No page breaks means major sections bleed into each other with no
+ visual rhythm.
+- Everything is black, so color provides zero hierarchy signal.
+
+### Quick Test
+
+1. **The squint test**: blur your eyes while looking at a full page. You
+ should see 3-4 distinct "weight levels" of gray. If the page looks like
+ one uniform shade, the hierarchy is too flat.
+2. **The scan test**: flip through pages quickly. Can you identify section
+ boundaries in under one second per page? If yes, the visual hierarchy is
+ working. If pages blur together, you need stronger differentiation at H1.
+3. **Adjacent level test**: for each heading level, check that it differs
+ from the next level on at least 2 of: size, weight, color, style (italic).
+ Single-dimension differences get lost.
+4. **Rhythm test**: in a document over 10 pages, do major sections (H1) start
+ on new pages? If not, long documents will feel like an undifferentiated
+ stream. Add `w:pageBreakBefore` to Heading1.
+
+---
+
+## Summary: Decision Checklist
+
+When you are unsure about a typographic choice, run through these checks:
+
+| Principle | Question | If No... |
+|-----------|----------|----------|
+| White Space | Does the page have at least 30% white space? | Increase margins or spacing |
+| Contrast | Can I count heading levels by squinting? | Increase size ratios (target 1.25x) |
+| Proximity | Does each heading clearly belong to text below it? | Make space-before > space-after (2:1) |
+| Alignment | Is English left-aligned and CJK justified? | Switch alignment mode |
+| Repetition | Do all same-level elements use the same style? | Replace direct formatting with styles |
+| Hierarchy | Can I see the document structure at arm's length? | Add more differentiation signals |
+
+**When two principles conflict, prioritize in this order:**
+
+1. **Readability** (white space, line spacing) -- always wins
+2. **Hierarchy** (contrast, scale) -- readers must find what they need
+3. **Consistency** (repetition) -- builds trust
+4. **Aesthetics** (alignment, grouping) -- the finishing touch
diff --git a/skills/minimax-docx/references/openxml_element_order.md b/skills/minimax-docx/references/openxml_element_order.md
new file mode 100644
index 0000000..a84b5a2
--- /dev/null
+++ b/skills/minimax-docx/references/openxml_element_order.md
@@ -0,0 +1,308 @@
+# OpenXML Child Element Ordering Rules
+
+Element ordering in OpenXML is defined by the XSD schema. Incorrect ordering produces invalid documents that Word may refuse to open or silently repair (potentially losing data).
+
+> **Key rule**: Properties elements (`*Pr`) must always be the **first child** of their parent.
+
+---
+
+## w:document
+
+```
+Children in order:
+1. w:background [0..1] — page background color/fill
+2. w:body [0..1] — document content container
+```
+
+---
+
+## w:body
+
+```
+Children in order (repeating group):
+1. w:p [0..*] — paragraph
+2. w:tbl [0..*] — table
+3. w:sdt [0..*] — structured document tag (content control)
+4. w:sectPr [0..1] — LAST child: final section properties
+```
+
+Note: `w:p`, `w:tbl`, and `w:sdt` are interleaved in document order. The only strict rule is that `w:sectPr` must be the **last child** of `w:body`.
+
+---
+
+## w:p (Paragraph)
+
+```
+Children in order:
+1. w:pPr [0..1] — paragraph properties (MUST be first)
+
+Then any mix of (interleaved in document order):
+- w:r [0..*] — run
+- w:hyperlink [0..*] — hyperlink wrapper
+- w:ins [0..*] — tracked insertion
+- w:del [0..*] — tracked deletion
+- w:bookmarkStart [0..*] — bookmark anchor start
+- w:bookmarkEnd [0..*] — bookmark anchor end
+- w:commentRangeStart [0..*] — comment range start
+- w:commentRangeEnd [0..*] — comment range end
+- w:proofErr [0..*] — proofing error marker
+- w:fldSimple [0..*] — simple field
+- w:sdt [0..*] — inline content control
+- w:smartTag [0..*] — smart tag
+```
+
+**Practical note**: After `w:pPr`, the remaining children appear in document reading order. Runs, hyperlinks, bookmarks, and comment ranges intermix freely based on their position in the text.
+
+---
+
+## w:pPr (Paragraph Properties)
+
+```
+Children in order:
+1. w:pStyle [0..1] — paragraph style reference
+2. w:keepNext [0..1] — keep with next paragraph
+3. w:keepLines [0..1] — keep lines together
+4. w:pageBreakBefore [0..1] — page break before paragraph
+5. w:framePr [0..1] — text frame properties
+6. w:widowControl [0..1] — widow/orphan control
+7. w:numPr [0..1] — numbering properties
+8. w:suppressLineNumbers [0..1]
+9. w:pBdr [0..1] — paragraph borders
+10. w:shd [0..1] — shading
+11. w:tabs [0..1] — tab stops
+12. w:suppressAutoHyphens [0..1]
+13. w:kinsoku [0..1] — CJK kinsoku settings
+14. w:wordWrap [0..1]
+15. w:overflowPunct [0..1]
+16. w:topLinePunct [0..1]
+17. w:autoSpaceDE [0..1]
+18. w:autoSpaceDN [0..1]
+19. w:bidi [0..1] — right-to-left paragraph
+20. w:adjustRightInd [0..1]
+21. w:snapToGrid [0..1]
+22. w:spacing [0..1] — line and paragraph spacing
+23. w:ind [0..1] — indentation
+24. w:contextualSpacing [0..1]
+25. w:mirrorIndents [0..1]
+26. w:suppressOverlap [0..1]
+27. w:jc [0..1] — justification (left/center/right/both)
+28. w:textDirection [0..1]
+29. w:textAlignment [0..1]
+30. w:outlineLvl [0..1] — outline level
+31. w:divId [0..1]
+32. w:rPr [0..1] — run properties for paragraph mark
+33. w:sectPr [0..1] — section break (section ends at this paragraph)
+34. w:pPrChange [0..1] — tracked paragraph property change
+```
+
+---
+
+## w:r (Run)
+
+```
+Children in order:
+1. w:rPr [0..1] — run properties (MUST be first)
+
+Then any of (one per run, typically):
+- w:t [0..*] — text content
+- w:br [0..*] — break (line, page, column)
+- w:tab [0..*] — tab character
+- w:cr [0..*] — carriage return
+- w:sym [0..*] — symbol character
+- w:drawing [0..*] — DrawingML object (images)
+- w:pict [0..*] — VML picture (legacy)
+- w:fldChar [0..*] — complex field character
+- w:instrText [0..*] — field instruction text
+- w:delText [0..*] — deleted text (inside w:del)
+- w:footnoteReference [0..*]
+- w:endnoteReference [0..*]
+- w:commentReference [0..*]
+- w:lastRenderedPageBreak [0..*]
+```
+
+---
+
+## w:rPr (Run Properties)
+
+```
+Children in order:
+1. w:rStyle [0..1] — character style reference
+2. w:rFonts [0..1] — font specification
+3. w:b [0..1] — bold
+4. w:bCs [0..1] — complex script bold
+5. w:i [0..1] — italic
+6. w:iCs [0..1] — complex script italic
+7. w:caps [0..1] — all capitals
+8. w:smallCaps [0..1] — small capitals
+9. w:strike [0..1] — strikethrough
+10. w:dstrike [0..1] — double strikethrough
+11. w:outline [0..1]
+12. w:shadow [0..1]
+13. w:emboss [0..1]
+14. w:imprint [0..1]
+15. w:noProof [0..1] — suppress proofing
+16. w:snapToGrid [0..1]
+17. w:vanish [0..1] — hidden text
+18. w:color [0..1] — text color
+19. w:spacing [0..1] — character spacing
+20. w:w [0..1] — character width scaling
+21. w:kern [0..1] — font kerning
+22. w:position [0..1] — vertical position (raise/lower)
+23. w:sz [0..1] — font size (half-points)
+24. w:szCs [0..1] — complex script font size
+25. w:highlight [0..1] — text highlight color
+26. w:u [0..1] — underline
+27. w:effect [0..1] — text effect (animated)
+28. w:bdr [0..1] — run border
+29. w:shd [0..1] — run shading
+30. w:vertAlign [0..1] — superscript/subscript
+31. w:rtl [0..1] — right-to-left
+32. w:cs [0..1] — complex script
+33. w:lang [0..1] — language
+34. w:rPrChange [0..1] — tracked run property change
+```
+
+---
+
+## w:tbl (Table)
+
+```
+Children in order:
+1. w:tblPr [1..1] — table properties (REQUIRED, must be first)
+2. w:tblGrid [1..1] — column width definitions (REQUIRED)
+3. w:tr [1..*] — table row(s)
+```
+
+---
+
+## w:tblPr (Table Properties)
+
+```
+Children in order:
+1. w:tblStyle [0..1] — table style reference
+2. w:tblpPr [0..1] — table positioning
+3. w:tblOverlap [0..1]
+4. w:bidiVisual [0..1] — right-to-left table
+5. w:tblStyleRowBandSize [0..1]
+6. w:tblStyleColBandSize [0..1]
+7. w:tblW [0..1] — preferred table width
+8. w:jc [0..1] — table alignment
+9. w:tblCellSpacing [0..1]
+10. w:tblInd [0..1] — table indent from margin
+11. w:tblBorders [0..1] — table borders
+12. w:shd [0..1] — table shading
+13. w:tblLayout [0..1] — fixed or autofit
+14. w:tblCellMar [0..1] — default cell margins
+15. w:tblLook [0..1] — conditional formatting flags
+16. w:tblCaption [0..1] — accessibility caption
+17. w:tblDescription [0..1] — accessibility description
+18. w:tblPrChange [0..1] — tracked table property change
+```
+
+---
+
+## w:tr (Table Row)
+
+```
+Children in order:
+1. w:trPr [0..1] — row properties (must be first)
+2. w:tc [1..*] — table cell(s)
+```
+
+---
+
+## w:trPr (Table Row Properties)
+
+```
+Children in order:
+1. w:cnfStyle [0..1] — conditional formatting
+2. w:divId [0..1]
+3. w:gridBefore [0..1] — grid columns before first cell
+4. w:gridAfter [0..1] — grid columns after last cell
+5. w:wBefore [0..1]
+6. w:wAfter [0..1]
+7. w:cantSplit [0..1] — don't split row across pages
+8. w:trHeight [0..1] — row height
+9. w:tblHeader [0..1] — repeat as header row
+10. w:tblCellSpacing [0..1]
+11. w:jc [0..1] — row alignment
+12. w:hidden [0..1]
+13. w:ins [0..1] — tracked row insertion
+14. w:del [0..1] — tracked row deletion
+15. w:trPrChange [0..1] — tracked row property change
+```
+
+---
+
+## w:tc (Table Cell)
+
+```
+Children in order:
+1. w:tcPr [0..1] — cell properties (must be first)
+2. w:p [1..*] — paragraph(s) — at least one required
+3. w:tbl [0..*] — nested table(s)
+```
+
+---
+
+## w:tcPr (Table Cell Properties)
+
+```
+Children in order:
+1. w:cnfStyle [0..1]
+2. w:tcW [0..1] — cell width
+3. w:gridSpan [0..1] — horizontal merge (column span)
+4. w:hMerge [0..1] — legacy horizontal merge
+5. w:vMerge [0..1] — vertical merge
+6. w:tcBorders [0..1] — cell borders
+7. w:shd [0..1] — cell shading
+8. w:noWrap [0..1]
+9. w:tcMar [0..1] — cell margins
+10. w:textDirection [0..1]
+11. w:tcFitText [0..1]
+12. w:vAlign [0..1] — vertical alignment
+13. w:hideMark [0..1]
+14. w:tcPrChange [0..1] — tracked cell property change
+```
+
+---
+
+## w:sectPr (Section Properties)
+
+```
+Children in order:
+1. w:headerReference [0..*] — header references (type: default/first/even)
+2. w:footerReference [0..*] — footer references
+3. w:endnotePr [0..1]
+4. w:footnotePr [0..1]
+5. w:type [0..1] — section break type (nextPage/continuous/evenPage/oddPage)
+6. w:pgSz [0..1] — page size
+7. w:pgMar [0..1] — page margins
+8. w:paperSrc [0..1]
+9. w:pgBorders [0..1] — page borders
+10. w:lnNumType [0..1] — line numbering
+11. w:pgNumType [0..1] — page numbering
+12. w:cols [0..1] — column definitions
+13. w:formProt [0..1]
+14. w:vAlign [0..1] — vertical alignment of page
+15. w:noEndnote [0..1]
+16. w:titlePg [0..1] — different first page header/footer
+17. w:textDirection [0..1]
+18. w:bidi [0..1]
+19. w:rtlGutter [0..1]
+20. w:docGrid [0..1] — document grid
+21. w:sectPrChange [0..1] — tracked section property change
+```
+
+---
+
+## w:hdr (Header) / w:ftr (Footer)
+
+```
+Children (same structure as w:body content):
+1. w:p [0..*] — paragraph(s)
+2. w:tbl [0..*] — table(s)
+3. w:sdt [0..*] — content controls
+```
+
+Headers and footers are essentially mini-documents. They follow the same content model as `w:body` but without a final `w:sectPr`.
diff --git a/skills/minimax-docx/references/openxml_encyclopedia_part1.md b/skills/minimax-docx/references/openxml_encyclopedia_part1.md
new file mode 100644
index 0000000..177182f
--- /dev/null
+++ b/skills/minimax-docx/references/openxml_encyclopedia_part1.md
@@ -0,0 +1,4061 @@
+# OpenXML SDK 3.x Complete Reference Encyclopedia
+
+**Target:** DocumentFormat.OpenXml 3.x / .NET 8+ / C# 12
+**Last Updated:** 2026-03-22
+
+This document serves as an exhaustive reference for building DOCX files with the OpenXML SDK. Every code block is ready to copy-paste.
+
+---
+
+## Namespace Aliases Used Throughout
+
+```csharp
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Wordprocessing;
+```
+
+---
+
+## Table of Contents
+
+1. [Document Creation Skeleton](#1-document-creation-skeleton)
+2. [Style System Deep Dive](#2-style-system-deep-dive)
+3. [Character Formatting (RunProperties)](#3-character-formatting-runproperties--exhaustive)
+4. [Paragraph Formatting (ParagraphProperties)](#4-paragraph-formatting-paragraphproperties--exhaustive)
+
+---
+
+## 1. Document Creation Skeleton
+
+### 1.1 Complete Flow: Create to Save
+
+```csharp
+// =============================================================================
+// DOCUMENT CREATION SKELETON
+// =============================================================================
+// This is the minimal complete flow for creating a valid DOCX from scratch.
+// Follow these steps in order: Create -> AddParts -> AddContent -> Save.
+//
+// Key insight: WordprocessingDocument.Create() adds MainDocumentPart automatically,
+// but all other parts (Styles, Settings, Numbering, Theme) must be added manually.
+
+// --- STEP 1: CREATE THE PACKAGE ---
+// The file path can be absolute or relative. WordprocessingDocumentType.Document
+// is the standard choice for .docx files (vs. Template, MacroEnabled, etc.)
+string outputPath = "C:\\Docs\\MyDocument.docx";
+
+using var doc = WordprocessingDocument.Create(
+ outputPath, // File path
+ WordprocessingDocumentType.Document, // Document type enum
+ new DocumentOptions // Optional: AutoSave, etc.
+ {
+ AutoSave = false // true = flush changes automatically
+ });
+
+// --- STEP 2: GET OR CREATE THE MAIN DOCUMENT PART ---
+// When you call Create(), MainDocumentPart is automatically created and linked.
+// You access it via .MainDocumentPart (not .AddMainDocumentPart, which would add
+// a SECOND main part — illegal). For a fresh document, just use .MainDocumentPart.
+var mainPart = doc.MainDocumentPart!;
+var body = mainPart.Document.Body!; // Body is created automatically with the part
+
+// --- STEP 3: ADD ADDITIONAL PARTS ---
+// These are OPTIONAL but recommended for a complete document:
+// - StyleDefinitionsPart: required for styles
+// - NumberingDefinitionsPart: required for bullets/numbers
+// - DocumentSettingsPart: zoom, proof state, tab stops, compatibility
+// - ThemePart: color/theme information
+// Parts are created fresh and linked via relationships.
+
+// Example: Add styles part (covered in Section 2)
+var stylesPart = mainPart.AddNewPart();
+stylesPart.Styles = new Styles();
+stylesPart.Styles.Save();
+
+// Example: Add settings part (covered in 1.4)
+var settingsPart = mainPart.AddNewPart();
+settingsPart.Settings = new Settings();
+settingsPart.Settings.Save();
+
+// --- STEP 4: ADD CONTENT TO BODY ---
+// Body accepts: Paragraph (w:p), Table (w:tbl), Structured Document Tag (w:sdt)
+// Content is added in document order (no need for explicit index).
+// IMPORTANT: SectionProperties (w:sectPr) MUST be the last child of body.
+body.Append(new Paragraph(
+ new Run(new Text("Hello, World!"))));
+
+// --- STEP 5: SET SECTION PROPERTIES (PAGE LAYOUT) ---
+// sectPr defines page size, margins, headers/footers, columns, etc.
+// It must be the last child of body. If missing, Word uses defaults (Letter/A4, 1" margins).
+var sectPr = new SectionProperties();
+
+// Page Size: Width/Height in DXA (1 inch = 1440 DXA)
+// Letter: 12240 x 15840 DXA (8.5" x 11")
+// A4: 11906 x 16838 DXA (210mm x 297mm)
+sectPr.Append(new PageSize
+{
+ Width = 12240u, // 8.5 inches
+ Height = 15840u // 11 inches
+});
+
+// Page Margins: all four margins in DXA
+// Note: Top+Bottom margins + HeaderDistance = distance from page edge to text
+sectPr.Append(new PageMargin
+{
+ Top = 1440, // 1 inch
+ Bottom = 1440, // 1 inch
+ Left = 1440u, // 1 inch (uint required)
+ Right = 1440u, // 1 inch
+ Header = 720u, // 0.5 inch from page edge to header
+ Footer = 720u // 0.5 inch from page edge to footer
+});
+
+// Attach sectPr to body (must be last)
+body.Append(sectPr);
+
+// --- STEP 6: SAVE ---
+// Because we use `using`, Dispose() is called automatically when the block exits.
+// Dispose() saves the file. If you forget `using`, call doc.Save() explicitly.
+```
+
+### 1.2 Opening an Existing Document
+
+```csharp
+// =============================================================================
+// OPENING EXISTING DOCUMENTS
+// =============================================================================
+// Open() has multiple overloads:
+// 1. Open(string path, bool isEditable, AutoSave)
+// 2. Open(Stream, bool isEditable, AutoSave)
+// 3. Open(string path, bool isEditable, OpenSettings)
+//
+// isEditable=true means open for read/write. false = read-only.
+// isEditable=false is faster (shared locks avoided) but throws if file is read-only.
+
+// --- OPEN FOR EDITING (READ/WRITE) ---
+string inputPath = "C:\\Docs\\Existing.docx";
+using var editDoc = WordprocessingDocument.Open(
+ inputPath,
+ isEditable: true, // Required for modification
+ new OpenSettings
+ {
+ AutoSave = true // Automatically save on Dispose
+ });
+
+var body = editDoc.MainDocumentPart!.Document.Body!;
+// ... make changes ...
+// No explicit Save() needed if AutoSave = true
+
+// --- OPEN AS READ-ONLY (FASTER) ---
+using var readOnlyDoc = WordprocessingDocument.Open(
+ inputPath,
+ isEditable: false, // Read-only mode
+ new OpenSettings
+ {
+ // MarkupDeclarationProcess options
+ });
+
+// --- OPEN FROM STREAM ---
+byte[] fileBytes = File.ReadAllBytes(inputPath);
+using var streamDoc = WordprocessingDocument.Open(
+ new MemoryStream(fileBytes),
+ isEditable: true,
+ new OpenSettings { AutoSave = false });
+
+// After editing, you MUST copy the stream back to file if AutoSave=false:
+// streamDoc.MainDocumentPart.Document.Save();
+// File.WriteAllBytes(outputPath, streamStream.ToArray());
+
+// --- OPEN FROM HTTP RESPONSE (WEB SCENARIO) ---
+using var httpClient = new HttpClient();
+var response = await httpClient.GetAsync("https://example.com/document.docx");
+using var webStream = await response.Content.ReadAsStreamAsync();
+using var webDoc = WordprocessingDocument.Open(webStream, isEditable: true);
+```
+
+### 1.3 Stream-Based Creation (MemoryStream for Web)
+
+```csharp
+// =============================================================================
+// STREAM-BASED DOCUMENT CREATION
+// =============================================================================
+// Use MemoryStream when you want to:
+// 1. Generate a document in memory before sending to a client
+// 2. Avoid touching the filesystem (ASP.NET Core scenarios)
+// 3. Return a document from an API endpoint
+//
+// CRITICAL: The stream MUST be seekable when you call .Open().
+// After WordprocessingDocument.Create(), the stream position is at the beginning.
+// If you write to the stream BEFORE creating the document, seek to 0 first.
+
+// --- CREATE IN MEMORY ---
+MemoryStream memStream = new MemoryStream();
+
+// Create directly on a stream (no file path involved)
+using (var doc = WordprocessingDocument.Create(
+ memStream,
+ WordprocessingDocumentType.Document,
+ new DocumentOptions { AutoSave = false }))
+{
+ var mainPart = doc.MainDocumentPart!;
+ mainPart.Document = new Document(new Body());
+ mainPart.Document.Body!.Append(new Paragraph(
+ new Run(new Text("Generated in memory"))));
+ mainPart.Document.Save(); // Save to the underlying stream
+}
+// At this point, memStream contains the complete DOCX
+
+// --- SEND TO HTTP RESPONSE (ASP.NET Core) ---
+// In an API controller:
+[HttpGet("download")]
+public async Task DownloadDocument()
+{
+ var memStream = new MemoryStream();
+
+ using (var doc = WordprocessingDocument.Create(
+ memStream,
+ WordprocessingDocumentType.Document))
+ {
+ var mainPart = doc.MainDocumentPart!;
+ mainPart.Document = new Document(new Body());
+ mainPart.Document.Body!.Append(new Paragraph(
+ new Run(new Text("Download me!"))));
+ mainPart.Document.Save();
+ }
+
+ memStream.Position = 0; // IMPORTANT: Reset position for reading
+ return File(memStream,
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "GeneratedDocument.docx");
+}
+
+// --- CREATE FROM TEMPLATE IN MEMORY ---
+// Useful for mail-merge style operations
+MemoryStream templateStream = new MemoryStream();
+File.WriteAllBytes("template.docx", templateStream.ToArray()); // Save a template first
+
+using var templateSource = new MemoryStream(File.ReadAllBytes("template.docx"));
+using var mergedDoc = (WordprocessingDocument)templateSource.Clone();
+
+// Clone() creates an editable copy. Don't forget to set position:
+mergedDoc.MainDocumentPart!.Document.Body!.Append(new Paragraph(
+ new Run(new Text("Added content"))));
+```
+
+### 1.4 Adding All Standard Parts
+
+```csharp
+// =============================================================================
+// ADDING ALL STANDARD DOCUMENT PARTS
+// =============================================================================
+// A complete document should have:
+// 1. MainDocumentPart (auto-created)
+// 2. StyleDefinitionsPart
+// 3. NumberingDefinitionsPart
+// 4. DocumentSettingsPart
+// 5. ThemePart (optional)
+// 6. Custom parts (headers, footers, comments, etc.)
+
+// --- COMPLETE SETUP METHOD ---
+public static void CreateCompleteDocument(string path)
+{
+ using var doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document);
+ var mainPart = doc.MainDocumentPart!;
+
+ // Initialize document
+ mainPart.Document = new Document(new Body());
+ var body = mainPart.Document.Body!;
+
+ // Add all parts
+ AddStylesPart(mainPart);
+ AddNumberingPart(mainPart);
+ AddSettingsPart(mainPart);
+ AddThemePart(mainPart);
+ AddHeadersAndFooters(mainPart);
+
+ // Add sample content
+ AddSampleContent(body);
+
+ // Section properties MUST be last
+ body.Append(CreateSectionProperties());
+
+ mainPart.Document.Save();
+}
+
+// --- STYLES PART ---
+// See Section 2 for detailed style creation
+private static void AddStylesPart(MainDocumentPart mainPart)
+{
+ var stylesPart = mainPart.AddNewPart();
+ var styles = new Styles();
+
+ // DocDefaults: document-wide defaults for run and paragraph properties
+ // These apply when no explicit style or direct formatting overrides them
+ styles.Append(new DocDefaults(
+ new RunPropertiesDefault(
+ new RunPropertiesBaseStyle(
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
+ new FontSize { Val = "22" }, // 22 half-points = 11pt
+ new FontSizeComplexScript { Val = "22" }
+ )
+ ),
+ new ParagraphPropertiesDefault(
+ new ParagraphPropertiesBaseStyle(
+ new SpacingBetweenLines { After = "200", Line = "276", LineRule = LineSpacingRuleValues.Auto }
+ )
+ )
+ ));
+
+ // Default Normal style
+ styles.Append(new Style(
+ new StyleName { Val = "Normal" },
+ new PrimaryStyle()
+ )
+ { Type = StyleValues.Paragraph, StyleId = "Normal", Default = true });
+
+ stylesPart.Styles = styles;
+ stylesPart.Styles.Save();
+}
+
+// --- NUMBERING PART ---
+// Required for bulleted and numbered lists
+private static void AddNumberingPart(MainDocumentPart mainPart)
+{
+ var numberingPart = mainPart.AddNewPart();
+ var numbering = new Numbering();
+
+ // AbstractNum defines the list format (bullet, number, multilevel)
+// Creates a bullet list definition with 3 levels
+ var abstractNum = new AbstractNum { AbstractNumberId = 1 };
+
+ // Level 0: Bullet (dot)
+ abstractNum.Append(new Level(
+ new StartNumberingValue { Val = 1 },
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
+ new LevelText { Val = "•" },
+ new LevelJustification { Val = LevelJustificationValues.Left },
+ new PreviousParagraphProperties(
+ new Indentation { Left = "720", Hanging = "360" }) // 720 DXA indent, 360 DXA hanging
+ )
+ { LevelIndex = 0 });
+
+ // Level 1: Dash
+ abstractNum.Append(new Level(
+ new StartNumberingValue { Val = 1 },
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
+ new LevelText { Val = "–" },
+ new LevelJustification { Val = LevelJustificationValues.Left },
+ new PreviousParagraphProperties(
+ new Indentation { Left = "1440", Hanging = "360" })
+ )
+ { LevelIndex = 1 });
+
+ // Level 2: Circle
+ abstractNum.Append(new Level(
+ new StartNumberingValue { Val = 1 },
+ new NumberingFormat { Val = NumberFormatValues.Bullet },
+ new LevelText { Val = "◦" },
+ new LevelJustification { Val = LevelJustificationValues.Left },
+ new PreviousParagraphProperties(
+ new Indentation { Left = "2160", Hanging = "360" })
+ )
+ { LevelIndex = 2 });
+
+ numbering.Append(abstractNum);
+
+ // NumberingInstance links to AbstractNum and assigns a numId
+ numbering.Append(new NumberingInstance(
+ new AbstractNumId { Val = 1 }
+ )
+ { NumberID = 1 });
+
+ numberingPart.Numbering = numbering;
+ numberingPart.Numbering.Save();
+}
+
+// --- SETTINGS PART ---
+// Contains document-level settings: zoom, proof state, default tab stop, etc.
+private static void AddSettingsPart(MainDocumentPart mainPart)
+{
+ var settingsPart = mainPart.AddNewPart();
+ var settings = new Settings();
+
+ // Zoom: document zoom percentage (default 100%)
+ // Val is a percentage value (e.g., "100" = 100%)
+ settings.Append(new Zoom { Val = "100", Percent = true, SnapToGrid = true });
+
+ // ProofState: spelling/grammar check state
+ // Val combines bits: 1=grammar, 2=spelling, 3=both
+ settings.Append(new ProofState { Val = ProofingStateValues.Clean });
+
+ // Default tab stop interval in DXA
+ // Word inserts tab stops every 720 DXA (0.5 inch) by default
+ settings.Append(new DefaultTabStop { Val = 720 });
+
+ // Character spacing control: automatically adjust character spacing
+ // to maintain consistent line spacing (similar to InDesign)
+ settings.Append(new CharacterSpacingControl { Val = CharacterSpacingValues.CompressPunctuation });
+
+ // Compatibility settings: controls how Word handles certain formatting
+ // to ensure compatibility with different Word versions
+ settings.Append(new Compatibility(
+ new UseFELayout(), // Use formatted East Asian layout
+ new UseAsianDigraphicLineBreakRules(), // CJK line breaking rules
+ new AllowSpaceOfSameStyleInTable(), // Table cell spacing
+ new DoNotUseIndentAsPercentageForTabStops(), // Legacy tab behavior
+ new ProportionalOtherIndents(), // Proportional indents
+ new LayoutTableRawTextInTable() // Raw text in layout tables
+ ));
+
+ // Revision tracking view settings
+ settings.Append(new RevisionView { DocPart = false, Formatting = true, Ink = true, Markup = true });
+
+ settingsPart.Settings = settings;
+ settingsPart.Settings.Save();
+}
+
+// --- THEME PART ---
+// Defines color scheme, font scheme, and format scheme for the document theme
+private static void AddThemePart(MainDocumentPart mainPart)
+{
+ var themePart = mainPart.AddNewPart();
+ var theme = new Theme(
+ new ThemeElements(
+ // Color scheme: 10 predefined theme colors
+ new ColorScheme(
+ new Dark1Color(new Color { Val = "000000" }),
+ new Light1Color(new Color { Val = "FFFFFF" }),
+ new Dark2Color(new Color { Val = "1F497D" }),
+ new Light2Color(new Color { Val = "EEECE1" }),
+ new Accent1Color(new Color { Val = "4F81BD" }),
+ new Accent2Color(new Color { Val = "C0504D" }),
+ new Accent3Color(new Color { Val = "9BBB59" }),
+ new Accent4Color(new Color { Val = "8064A2" }),
+ new Accent5Color(new Color { Val = "4BACC6" }),
+ new Accent6Color(new Color { Val = "F79646" }),
+ new Hyperlink(new Color { Val = "0000FF" }),
+ new FollowedHyperlinkColor(new Color { Val = "800080" })
+ ),
+ // Font scheme: major (headings) and minor (body) fonts
+ new FontScheme(
+ new MajorFont { Val = "Calibri Light" },
+ new MinorFont { Val = "Calibri" }
+ ),
+ // Format scheme: default fill and effect styles
+ new FormatScheme(
+ new FillStyleList(
+ new FillStyle { Fill = new PatternFill { PatternType = PatternValues.Solid } }
+ ),
+ new LineStyleList(
+ new LineStyle { Val = LineValues.Single }
+ )
+ )
+ ),
+ new ThemeName { Val = "Office Theme" },
+ new ThemeNames(
+ new LanguageBasedString { Val = "en-US", LanguageId = "x-none" }
+ )
+ );
+
+ themePart.Theme = theme;
+ themePart.Theme.Save();
+}
+
+// --- HEADERS AND FOOTERS ---
+private static void AddHeadersAndFooters(MainDocumentPart mainPart)
+{
+ // Header
+ var headerPart = mainPart.AddNewPart();
+ headerPart.Header = new Header(
+ new Paragraph(
+ new ParagraphProperties(
+ new Justification { Val = JustificationValues.Right }),
+ new Run(
+ new RunProperties(
+ new RunFonts { Ascii = "Calibri Light", HighAnsi = "Calibri Light" },
+ new Italic(),
+ new FontSize { Val = "20" } // 10pt
+ ),
+ new Text("Document Header"))
+ ));
+ var headerId = mainPart.GetIdOfPart(headerPart);
+
+ // Footer
+ var footerPart = mainPart.AddNewPart();
+ footerPart.Footer = new Footer(
+ new Paragraph(
+ new ParagraphProperties(
+ new Justification { Val = JustificationValues.Center }),
+ new Run(new Text("Page ") { Space = SpaceProcessingModeValues.Preserve }),
+ new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }),
+ new Run(new FieldCode(" PAGE ") { Space = SpaceProcessingModeValues.Preserve }),
+ new Run(new FieldChar { FieldCharType = FieldCharValues.End }),
+ new Run(new Text(" of ") { Space = SpaceProcessingModeValues.Preserve }),
+ new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }),
+ new Run(new FieldCode(" NUMPAGES ") { Space = SpaceProcessingModeValues.Preserve }),
+ new Run(new FieldChar { FieldCharType = FieldCharValues.End })
+ ));
+ var footerId = mainPart.GetIdOfPart(footerPart);
+
+ // Reference IDs in section properties
+ // (added in CreateSectionProperties below)
+}
+
+// --- SECTION PROPERTIES (COMPLETE) ---
+private static SectionProperties CreateSectionProperties()
+{
+ var sectPr = new SectionProperties();
+
+ // Header/Footer references (must come before page size/margins)
+ var mainPart = doc.MainDocumentPart; // Note: in real code, pass as parameter
+ sectPr.Append(new HeaderReference
+ {
+ Type = HeaderFooterValues.Default,
+ Id = mainPart!.GetIdOfPart(mainPart.HeaderParts.First())
+ });
+ sectPr.Append(new FooterReference
+ {
+ Type = HeaderFooterValues.Default,
+ Id = mainPart.GetIdOfPart(mainPart.FooterParts.First())
+ });
+
+ // Page size
+ sectPr.Append(new PageSize { Width = 12240u, Height = 15840u });
+
+ // Page margins
+ sectPr.Append(new PageMargin
+ {
+ Top = 1440,
+ Bottom = 1440,
+ Left = 1440u,
+ Right = 1440u,
+ Header = 720u,
+ Footer = 720u
+ });
+
+ // Page numbering format
+ sectPr.Append(new PageNumberType { Start = 1, Format = NumberFormatValues.Decimal });
+
+ // Column settings (default: 1 column)
+ sectPr.Append(new Columns { ColumnCount = 1, EqualWidth = true });
+
+ // Paper source (printer tray)
+ // sectPr.Append(new PaperSource { Tray = 1, Paper = 7 });
+
+ return sectPr;
+}
+```
+
+### 1.5 Unit Systems Reference
+
+```csharp
+// =============================================================================
+// UNIT SYSTEMS IN OPENXML
+// =============================================================================
+// Understanding units is critical. Wrong unit = wrong formatting.
+//
+// DXA (Twentieths of a DXA) - "Standard Document Unit"
+// 1 DXA = 1/20th of a point
+// 1 inch = 1440 DXA
+// 1 cm = 567 DXA (approx)
+// Used for: margins, indents, spacing, tab stops, column widths
+//
+// Half-Points (sz) - Font Size
+// Value is in half-points (1/2 point increments)
+// 24 = 12pt, 28 = 14pt, 36 = 18pt, 48 = 24pt
+// Used for: FontSize.Val, FontSizeComplexScript.Val
+//
+// Points (pt) - Direct Measurements
+// Standard typographic point (72 per inch)
+// Used for: some line spacing values, border widths
+//
+// EMU (English Metric Units) - Drawing Objects
+// 1 inch = 914400 EMU
+// Used for: drawing object sizes, shapes, images
+//
+// STARS (Special Twips Advanced Right-Left) - CJK Indentation
+// Used for: FirstLineChars, HangingChars (special FirstLine/Hanging for CJK)
+// Converts character counts to DXA based on font metrics
+//
+// LINE SPACING SPECIAL VALUES:
+// Line = "240" with LineRule = Auto = single spacing (default)
+// Line = "480" with LineRule = Auto = double spacing
+// Line = "360" with LineRule = Auto = 1.5 spacing
+// Line = "240" with LineRule = Exact = exactly 12pt
+// Line = "288" with LineRule = AtLeast = at least 14.4pt (grows with content)
+
+// --- CONVERSION HELPER METHODS ---
+public static class OpenXmlUnits
+{
+ // DXA conversions
+ public static int InchesToDxa(double inches) => (int)(inches * 1440);
+ public static int CmToDxa(double cm) => (int)(cm * 567.0);
+ public static int PtToDxa(double pt) => (int)(pt * 20);
+ public static double DxaToInches(int dxa) => dxa / 1440.0;
+ public static double DxaToCm(int dxa) => dxa / 567.0;
+ public static double DxaToPt(int dxa) => dxa / 20.0;
+
+ // EMU conversions (for drawings)
+ public static long InchesToEmu(double inches) => (long)(inches * 914400);
+ public static long CmToEmu(double cm) => (long)(cm * 360000);
+ public static double EmuToInches(long emu) => emu / 914400.0;
+
+ // Half-point conversions (font sizes)
+ public static int PtToHalfPt(double pt) => (int)(pt * 2);
+ public static int FontSizeToSz(double ptSize) => (int)(ptSize * 2);
+ public static double SzToPt(int sz) => sz / 2.0;
+
+ // Line spacing
+ public static int SingleSpacing => 240;
+ public static int DoubleSpacing => 480;
+ public static int OneAndHalfSpacing => 360;
+ public static int LineSpacingPt(double pt) => (int)(pt * 20); // Convert to DXA
+}
+
+// Example usage:
+var marginInInches = OpenXmlUnits.DxaToInches(1440); // 1.0
+var fontSizeInSz = OpenXmlUnits.FontSizeToSz(12.0); // 24
+var indentInDxa = OpenXmlUnits.InchesToDxa(0.5); // 720
+```
+
+---
+
+## 2. Style System Deep Dive
+
+### 2.1 Style Types and Structure
+
+```csharp
+// =============================================================================
+// STYLE TYPES OVERVIEW
+// =============================================================================
+// OpenXML defines 4 style types (StyleValues enum):
+// 1. Paragraph (w:p) - controls paragraph-level formatting
+// 2. Character (w:r) - controls inline/run-level formatting
+// 3. Table (w:tbl) - controls table-level formatting
+// 4. Numbering (w:num) - NOT a style type, but a separate numbering system
+//
+// Key insight: A style can be BOTH paragraph and character style (linked style).
+// The "linkedStyle" element links a paragraph style to a character style.
+
+// --- MINIMAL PARAGRAPH STYLE ---
+// A paragraph style controls: pPr (paragraph properties) and optionally rPr
+Style minimalParaStyle = new Style(
+ new StyleName { Val = "MyParagraphStyle" },
+ new PrimaryStyle() // Primary styles appear in Style gallery
+)
+{
+ Type = StyleValues.Paragraph,
+ StyleId = "MyParagraphStyle"
+};
+
+// --- MINIMAL CHARACTER STYLE ---
+// A character style controls: rPr only (no pPr)
+Style minimalCharStyle = new Style(
+ new StyleName { Val = "MyCharacterStyle" },
+ new PrimaryStyle()
+)
+{
+ Type = StyleValues.Character,
+ StyleId = "MyCharacterStyle"
+};
+
+// Character style with run properties (fonts, size, bold, etc.)
+Style charStyleWithFormatting = new Style(
+ new StyleName { Val = "Emphasis" },
+ new PrimaryStyle(),
+ new StyleRunProperties(
+ new Italic(),
+ new Color { Val = "C00000" } // Dark red
+ )
+)
+{
+ Type = StyleValues.Character,
+ StyleId = "Emphasis"
+};
+
+// --- LINKED STYLE (Paragraph + Character) ---
+// A linked style combines both: it can be applied to a paragraph OR a run.
+// This is how Word's "Heading 1" works — applies to paragraphs, but you can
+// also select text within a heading and apply the same style as character formatting.
+Style linkedStyle = new Style(
+ new StyleName { Val = "LinkedStyle" },
+ new PrimaryStyle(),
+ new LinkedStyle { Val = "LinkedStyleChar" }, // Links to character style
+ new StyleParagraphProperties(
+ new SpacingBetweenLines { After = "120" }
+ ),
+ new StyleRunProperties(
+ new Bold(),
+ new FontSize { Val = "24" }
+ )
+)
+{
+ Type = StyleValues.Paragraph,
+ StyleId = "LinkedStyle"
+};
+
+// Corresponding character style (normally same name + "Char" suffix by convention)
+Style linkedStyleChar = new Style(
+ new StyleName { Val = "LinkedStyle Char" }, // Word convention: adds " Char"
+ new PrimaryStyle(),
+ new StyleRunProperties(
+ new Bold(),
+ new FontSize { Val = "24" }
+ )
+)
+{
+ Type = StyleValues.Character,
+ StyleId = "LinkedStyleChar"
+};
+
+// --- TABLE STYLE ---
+Style tableStyle = new Style(
+ new StyleName { Val = "MyTableStyle" },
+ new PrimaryStyle(),
+ new StyleTableProperties(
+ new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct }, // 50% width
+ new TableBorders(
+ new TopBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
+ new BottomBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
+ new LeftBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
+ new RightBorder { Val = BorderValues.Single, Size = 4, Color = "000000" },
+ new InsideHorizontalBorder { Val = BorderValues.Single, Size = 2, Color = "CCCCCC" },
+ new InsideVerticalBorder { Val = BorderValues.Single, Size = 2, Color = "CCCCCC" }
+ ),
+ new TableCellMarginDefault(
+ new TopMargin { Width = "0", Type = TableWidthUnitValues.DXA },
+ new StartMargin { Width = "108", Type = TableWidthUnitValues.DXA },
+ new BottomMargin { Width = "0", Type = TableWidthUnitValues.DXA },
+ new EndMargin { Width = "108", Type = TableWidthUnitValues.DXA }
+ )
+ )
+)
+{
+ Type = StyleValues.Table,
+ StyleId = "MyTableStyle"
+};
+```
+
+### 2.2 DocDefaults and Document-Wide Defaults
+
+```csharp
+// =============================================================================
+// DOCDEFAULTS: DOCUMENT-WIDE DEFAULTS
+// =============================================================================
+// DocDefaults lives inside Styles and provides fallback values when:
+// 1. No explicit style is applied
+// 2. No direct formatting is applied
+// It contains RunPropertiesDefault and/or ParagraphPropertiesDefault.
+//
+// CRITICAL: DocDefaults applies to the entire document. Any explicit style
+// or direct formatting will override it.
+
+// --- COMPLETE DOCDEFAULTS SETUP ---
+var docDefaults = new DocDefaults(
+ // Run properties defaults: default font, size, language for all runs
+ new RunPropertiesDefault(
+ new RunPropertiesBaseStyle(
+ // RunFonts: which font to use for each script
+ // Word will fall back through these: ASCII -> HighAnsi -> EastAsia -> ComplexScript
+ // Always specify at minimum Ascii and HighAnsi
+ new RunFonts
+ {
+ Ascii = "Calibri", // Western/Latin font (primary)
+ HighAnsi = "Calibri", // Latin characters (often same as Ascii)
+ EastAsia = "SimSun", // East Asian font (CJK)
+ ComplexScript = "Arial", // Complex scripts (Arabic, Hebrew, Thai)
+ ASCIITheme = ThemeFontValues.Minor,
+ HighAnsiTheme = ThemeFontValues.Minor,
+ EastAsiaTheme = ThemeFontValues.Minor,
+ ComplexScriptTheme = ThemeFontValues.Minor
+ },
+ // FontSize: in HALF-POINTS (24 = 12pt, 22 = 11pt, 20 = 10pt)
+ new FontSize { Val = "22" }, // 11pt for body
+ new FontSizeComplexScript { Val = "22" },
+ // Languages: required for proper hyphenation and spell checking
+ new Languages { Val = "en-US" }, // Default language
+ new Languages { EastAsia = "zh-CN", Val = "en-US" } // Can set multiple
+ )
+ ),
+ // Paragraph properties defaults: default spacing, etc.
+ new ParagraphPropertiesDefault(
+ new ParagraphPropertiesBaseStyle(
+ // SpacingBetweenLines: default paragraph spacing
+ // After = "200" = 200 DXA = 10pt after each paragraph
+ new SpacingBetweenLines
+ {
+ After = "200",
+ Line = "276",
+ LineRule = LineSpacingRuleValues.Auto // Auto = 1.15x line height
+ }
+ )
+ )
+);
+
+// --- LAYOUT LUNCTIONS (LATENT STYLES) ---
+// Latent styles are hidden styles that exist in Word but aren't in styles.xml.
+// They provide fast-access defaults for formatting (e.g., Normal, Heading 1-6, etc.)
+// when the user hasn't explicitly customized them.
+//
+// DocDefaults can define LatentStyleCountOverride to adjust count,
+// but true latent styles are controlled by Normal.dotm (Word's global template).
+Styles CreateStylesWithDocDefaults()
+{
+ var styles = new Styles();
+
+ // DocDefaults with run and paragraph properties defaults
+ styles.Append(new DocDefaults(
+ new RunPropertiesDefault(
+ new RunPropertiesBaseStyle(
+ new RunFonts { Ascii = "Calibri", HighAnsi = "Calibri" },
+ new FontSize { Val = "22" },
+ new Languages { Val = "en-US" }
+ )
+ ),
+ new ParagraphPropertiesDefault(
+ new ParagraphPropertiesBaseStyle(
+ new SpacingBetweenLines { After = "160", Line = "276", LineRule = LineSpacingRuleValues.Auto }
+ )
+ )
+ ));
+
+ // LatentStyles: override defaults for built-in latent styles
+ // These control Word's "fast-styles" like Heading 1-6 before they're customized
+ styles.Append(new LatentStyles(
+ new Count { Val = 159 }, // Total latent style count
+ new FirstLineChars { Val = 352 }, // Default first line char count
+ new HorizontalOverflow { Val = HorizontalOverflowValues.Overflow },
+ new VerticalOverflow { Val = VerticalOverflowValues.Overflow },
+ new KoreanSpaceAdjust { Val = true },
+ // Each LatentStyleException overrides ONE attribute of ONE latent style
+ // StyleID = the built-in style name (e.g., "Normal", "heading 1")
+ // Attribute: what to change (bold, italic, font, color, etc.)
+ // The defaults for built-in headings: font=Calibri, size=24, bold
+ new LatentStyleException(
+ new Primary烙,
+ new StyleName { Val = "Normal" },
+ new UIPriority { Val = 1 },
+ new PrimaryZone(),
+ new QuickStyle()
+ ),
+ new LatentStyleException(
+ new Primary烙,
+ new StyleName { Val = "heading 1" },
+ new UIPriority { Val = 9 },
+ new PrimaryZone(),
+ new QuickStyle(),
+ new Bold(),
+ new BoldComplexScript(),
+ new FontSize { Val = "48" }, // 24pt = 48 half-pts
+ new FontSizeComplexScript { Val = "48" }
+ )
+ ));
+
+ return styles;
+}
+```
+
+### 2.3 Complete Heading Styles Hierarchy
+
+```csharp
+// =============================================================================
+// HEADING STYLES WITH PROPER INHERITANCE CHAIN
+// =============================================================================
+// Word's built-in heading system uses style inheritance:
+// Normal (base) -> Heading1 -> Heading2 -> Heading3 -> Heading4 -> Heading5 -> Heading6
+//
+// Why this matters:
+// - Each heading INHERITS from its parent (basedOn)
+// - Define common properties in Normal, override in each heading
+// - Change body font once in Normal, all headings inherit it
+// - Heading-specific properties override as needed
+
+// --- HEADING STYLE FACTORY ---
+public static Style CreateHeadingStyle(int level, FontConfig fonts)
+{
+ // Validate level (1-9 are valid, 1-6 are standard)
+ if (level < 1 || level > 9)
+ throw new ArgumentOutOfRangeException(nameof(level));
+
+ double[] headingSizes = [26.0, 20.0, 16.0, 14.0, 12.0, 11.0, 11.0, 11.0, 11.0];
+ string[] outlineLevels = ["0", "1", "2", "3", "4", "5", "6", "7", "8"};
+
+ var style = new Style(
+ new StyleName { Val = $"heading {level}" }, // Display name
+ new BasedOn { Val = level == 1 ? "Normal" : $"Heading{level - 1}" }, // Parent style
+ new NextParagraphStyle { Val = "Normal" }, // After heading -> Normal
+ new PrimaryStyle(), // Show in Styles gallery
+ new UIPriority { Val = 9 - level }, // Priority in gallery (H1 = 8, H2 = 7, etc.)
+ new QuickStyle(), // Appears in Quick Styles gallery
+ // Paragraph properties: spacing, keep options, outline level
+ new StyleParagraphProperties(
+ new KeepNext(), // Keep heading with next paragraph
+ new KeepLines(), // Keep all lines of heading together
+ new SpacingBetweenLines // Spacing before/after
+ {
+ Before = level == 1 ? "480" : "240", // H1 = 240pt before, others = 120pt
+ After = "120"
+ },
+ new OutlineLevel { Val = level - 1 } // 0-indexed for H1=0, H2=1, etc.
+ ),
+ // Run properties: font, size, bold
+ new StyleRunProperties(
+ new RunFonts
+ {
+ Ascii = fonts.HeadingFont,
+ HighAnsi = fonts.HeadingFont,
+ EastAsia = "SimHei" // Bold heading font for CJK
+ },
+ new FontSize { Val = UnitConverter.FontSizeToSz(headingSizes[level - 1]) },
+ new FontSizeComplexScript { Val = UnitConverter.FontSizeToSz(headingSizes[level - 1]) },
+ new Bold(),
+ new BoldComplexScript()
+ )
+ )
+ {
+ Type = StyleValues.Paragraph,
+ StyleId = $"Heading{level}"
+ };
+
+ return style;
+}
+
+// --- ADD ALL HEADING STYLES TO STYLES COLLECTION ---
+public static void AddHeadingStyles(Styles styles, FontConfig fonts)
+{
+ for (int i = 1; i <= 6; i++)
+ {
+ styles.Append(CreateHeadingStyle(i, fonts));
+ }
+
+ // Also add Heading 7-9 (valid in Word, less commonly used)
+ for (int i = 7; i <= 9; i++)
+ {
+ styles.Append(CreateHeadingStyle(i, fonts));
+ }
+}
+
+// --- HEADING STYLES INHERITANCE VISUALIZATION ---
+// When you apply "Heading2" (basedOn="Heading1"):
+//
+// Normal style:
+// - Font: Calibri 11pt
+// - Spacing: 0 before, 200 after
+// - No bold
+//
+// Heading1 (basedOn="Normal"):
+// - Inherits: Calibri 11pt
+// - Overrides: Calibri Light 26pt, Bold, Spacing 480 before/120 after
+// - Adds: KeepNext, KeepLines, OutlineLevel=0
+//
+// Heading2 (basedOn="Heading1"):
+// - Inherits: Calibri Light 26pt, Bold, KeepNext, KeepLines
+// - Overrides: 20pt
+// - Inherits: OutlineLevel=1
+//
+// Effective result: Heading2 = Calibri Light 20pt Bold, KeepNext+KeepLines, 480/120 spacing, OL=1
+```
+
+### 2.4 Style Inheritance Chain Resolution
+
+```csharp
+// =============================================================================
+// STYLE INHERITANCE RESOLUTION
+// =============================================================================
+// OpenXML styles resolve properties through the basedOn chain at RENDER TIME.
+// The document.xml stores only the styleId, not the resolved properties.
+// Word (or this library) walks the chain at load/display time.
+//
+// Example: Applying "Heading2" to a paragraph
+//
+// 1. Start with Heading2 style definition
+// 2. Walk basedOn chain: Heading2 -> Heading1 -> Normal -> (null)
+// 3. Collect properties in reverse order (most generic first):
+// a. Normal: Ascii=Calibri, sz=22, no bold
+// b. Heading1: Ascii=Calibri Light, sz=48, bold (override Calibri, sz, bold)
+// c. Heading2: sz=40 (override sz only)
+// 4. Final resolved style: Ascii=Calibri Light, sz=40, bold (bold from H1)
+//
+// IMPORTANT: Style override is COMPLETE for each element type:
+// - If Normal has rPr with Fonts, and Heading1 has pPr only,
+// Heading1 still inherits Normal's rPr fully.
+// - StyleRunProperties (rPr) and StyleParagraphProperties (pPr) are separate.
+
+// --- RESOLVING STYLE PROPERTIES MANUALLY ---
+// For debugging or custom rendering, you may need to resolve style chains
+public static class StyleResolver
+{
+ public record ResolvedStyle(
+ StyleName? Name,
+ RunProperties? RunProps,
+ ParagraphProperties? ParaProps,
+ string? BasedOn,
+ string Type);
+
+ public static ResolvedStyle Resolve(Styles styles, string styleId)
+ {
+ var styleMap = styles.Elements