# document-format-skills

Adopt this skill: https://proskills.md/skills/other/kagurananaga-document-format-skills

Page: https://proskills.md/skills/other/kagurananaga-document-format-skills
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 4567
sha: c2f3e1b766a5a9c48b1cf7c03c30ddd7b6b37b0b
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/SKILL.md

````text
---
name: document-format-skills
description: Chinese Word document formatting toolkit for .docx/.doc/.wps workflows. Use when Codex needs to diagnose document formatting, fix mixed Chinese/English punctuation and spacing, apply official/academic/legal/custom presets, normalize tables and page numbers, preserve or output Word revision marks, convert plain text or Markdown into formatted DOCX, or batch/script document cleanup for Chinese official documents.
---

# Document Format Skills

Use these scripts to clean and format Chinese Word documents from the command line. Prefer `scripts/process.py` for normal work because it mirrors the desktop app's core pipeline without the GUI.

## Quick Workflow

Run one smart pass when the user wants the document cleaned end to end:

```bash
uv run --with python-docx python scripts/process.py smart input.docx output.docx --preset official
```

Run diagnostics only:

```bash
uv run --with python-docx python scripts/process.py analyze input.docx
uv run --with python-docx python scripts/process.py analyze input.docx --json
```

Run only punctuation/spacing cleanup:

```bash
uv run --with python-docx python scripts/process.py punctuation input.docx output.docx --space-mode keep_en_boundary
```

Run only formatting:

```bash
uv run --with python-docx python scripts/process.py format input.docx output.docx --preset official
```

On Windows, `.doc` and `.wps` input/output are supported through WPS or Microsoft Word COM automation:

```bash
uv run --with python-docx --with pywin32 python scripts/process.py smart input.wps output.wps
```

## Scripts

| Script | Use |
| --- | --- |
| `scripts/process.py` | One-shot CLI for `smart`, `analyze`, `punctuation`, and `format`; handles `.doc/.wps` conversion on Windows. |
| `scripts/formatter.py` | Apply formatting presets, custom JSON settings, page numbers, table cleanup, revision marks, macOS font fallback. |
| `scripts/punctuation.py` | Fix punctuation while preserving run formatting; supports spacing strategies. |
| `scripts/from_text.py` | Create a DOCX from `.txt` or Markdown, then optionally run smart formatting. |
| `scripts/analyzer.py` | Lower-level diagnostic script. |
| `scripts/converter.py` | Windows-only `.doc/.wps` conversion helpers. |

## Formatting Options

Built-in presets:

- `official`: GB/T 9704-2012 style official document formatting.
- `academic`: academic paper formatting.
- `legal`: legal document formatting.
- `custom`: read the active desktop custom preset when available.

Useful flags:

```bash
--custom-settings path.json
--revision
--deep-clean
--smart-table-align
--no-page-number
--page-number-style dash|plain|page_text|page_total
--page-number-position outside|left|center|right
--page-number-offset-mm 7
--no-bold-serial
```

`--custom-settings` accepts desktop schema v2 config files, exported preset files shaped as `{"preset": {...}}`, or plain preset/override JSON. For non-custom presets, the JSON is merged over the selected preset.

## Punctuation And Spacing

Punctuation cleanup protects URLs, email addresses, Windows paths, time values like `9:30`, and standards like `ISO 9001:2015`. It fixes brackets, colons, semicolons, question/exclamation marks, Chinese comma/period contexts, ellipses, dashes, and paired quotes.

Spacing modes:

- `remove_all`: delete half-width and full-width spaces.
- `keep_en_boundary`: remove Chinese-to-Chinese spaces but keep exactly one space between Chinese and English/digits.
- `keep_all`: leave spaces unchanged.

## Text Or Markdown To DOCX

Generate and format a document from text:

```bash
uv run --with python-docx python scripts/from_text.py input.md output.docx --title "工作方案"
```

Markdown mode detects headings, bold spans, ordered/unordered lists, quotes, and fenced code blocks. `#` becomes the main title, `##` becomes `一、`, `###` becomes `（一）`, and deeper headings become numbered lower-level headings.

Use `--no-process` to only create the raw DOCX.

## Implementation Notes

- `.docx` processing needs only `python-docx`.
- `.doc/.wps` conversion needs Windows plus WPS Office or Microsoft Word and `pywin32`.
- Page number handling avoids overwriting non-page footer content and can replace existing page-number footers when requested.
- Default table formatting preserves original alignment; use `--smart-table-align` for numeric/right and short-text/center alignment.
- macOS font handling keeps installed official fonts when present and falls back to compatible system fonts only when detection confirms the original is missing.
````

## File: README.md
size: 4531
sha: bf9d26989f3aed43bedd3182a0cdbcd54cfd1b5f
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/README.md

````text
# 📄 document-format-skills 公文格式助手

> **[中文版本 README / Chinese Version](./README_CN.md)**
>
> 看不懂英文也没关系，请点击上面的链接查看中文版说明。

> 💡 **想要无需联网、一键运行修复格式的桌面应用版本？**
>
> 现已推出 **[Document Format GUI 公文格式助手](https://github.com/KaguraNanaga/docformat-gui)** —— 无需联网、一键修复公文格式的桌面应用，小白也能轻松上手！

> 🌐 **不想安装，也不需要 Agent？**
>
> 直接打开 **[公文格式处理工具网页版](https://web.gongwengeshizhushou.com)**，选择 `.docx` 文档即可开始处理。无需登录，文档只在当前浏览器中处理，不会上传到服务器。

A Word document formatting toolkit for Chinese official documents for the government, CCP (China Communist Party), and the state-owned enterprises. Diagnose formatting issues, fix punctuation, and apply standardized styles with one command. Available for Claude Code, Codex, and OpenCode.

公文格式助手是一个面向中文公文排版的 Skill 工具包，用于诊断 Word 文档格式问题、修复中英文标点和空格混用、统一公文/论文/法律文书格式、处理页码和表格，并支持从纯文本或 Markdown 生成规范 DOCX。

## Features

- 中文用户如果不熟悉命令行，可以优先使用 [Document Format GUI 公文格式助手](https://github.com/KaguraNanaga/docformat-gui)：无需联网、一键修复公文格式。
- Smart one-shot processing: punctuation/spacing cleanup plus formatting.
- Format diagnosis for punctuation, numbering, paragraph, and font issues.
- Official, academic, legal, and custom presets.
- GB/T 9704-2012 style page margins, fonts, line spacing, headings, signatures, dates, and page numbers.
- Safer page-number handling with styles, positions, offsets, replacement control, and non-page footer protection.
- Table normalization with optional smart alignment.
- Custom settings compatible with the desktop app schema v2 and exported preset JSON.
- Word revision marks for supported formatting changes.
- macOS font fallback for common Chinese official-document fonts.
- `.doc` / `.wps` conversion on Windows when WPS Office or Microsoft Word is installed.
- Plain text or Markdown to formatted DOCX.

## Requirements

- Python 3.8+
- `python-docx`
- `pywin32` only for `.doc/.wps` conversion on Windows

Use `uv` for ad-hoc runs:

```bash
uv run --with python-docx python scripts/process.py --help
```

For Windows `.doc/.wps` conversion:

```bash
uv run --with python-docx --with pywin32 python scripts/process.py --help
```

## Quick Start

Smart cleanup:

```bash
uv run --with python-docx python scripts/process.py smart input.docx output.docx --preset official
```

Analyze only:

```bash
uv run --with python-docx python scripts/process.py analyze input.docx
uv run --with python-docx python scripts/process.py analyze input.docx --json
```

Punctuation and spacing only:

```bash
uv run --with python-docx python scripts/process.py punctuation input.docx output.docx --space-mode keep_en_boundary
```

Formatting only:

```bash
uv run --with python-docx python scripts/process.py format input.docx output.docx --preset official
```

Create a formatted DOCX from Markdown or text:

```bash
uv run --with python-docx python scripts/from_text.py input.md output.docx --title "Work Plan"
```

## Useful Options

```bash
--preset official|academic|legal|custom
--custom-settings path.json
--revision
--deep-clean
--smart-table-align
--no-page-number
--page-number-style dash|plain|page_text|page_total
--page-number-position outside|left|center|right
--space-mode remove_all|keep_en_boundary|keep_all
```

`--custom-settings` accepts desktop schema v2 config files, exported preset files like `{"preset": {...}}`, or plain preset/override JSON.

## Scripts

| Script | Purpose |
| --- | --- |
| `scripts/process.py` | Main CLI pipeline: `smart`, `analyze`, `punctuation`, `format`. |
| `scripts/formatter.py` | Formatting engine and preset handling. |
| `scripts/punctuation.py` | Punctuation and spacing fixer. |
| `scripts/from_text.py` | Text/Markdown to DOCX generator. |
| `scripts/analyzer.py` | Diagnostic helpers. |
| `scripts/converter.py` | Windows `.doc/.wps` conversion helpers. |

## Notes

- `.docx` is the most reliable format.
- `.doc/.wps` requires Windows plus WPS Office or Microsoft Word.
- Keep a backup of important documents before running automated formatting.

## License

MIT
````

## File: scripts/__init__.py
size: 0
sha: e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/__init__.py

```text

```

## File: scripts/analyzer.py
size: 9165
sha: 09c22a55f0cf43c6b82e8d93010bf608cb5a9d90
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/analyzer.py

```text
#!/usr/bin/env python3
"""格式诊断模块 v2 - 修复列表项误报"""

import re
import sys
from collections import defaultdict
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH

# 不需要首行缩进的模式（只有主标题不需要缩进）
NO_INDENT_PATTERNS = [
    r'^附件[：:]',                      # 附件：
    r'^联系人[：:]',                    # 联系人：
    r'^抄送[：:]',                      # 抄送：
    r'^主送[：:]',                      # 主送：
]

def is_no_indent_para(text, alignment):
    """检查是否是不需要首行缩进的段落（只有居中的主标题不需要）"""
    # 居中的短文本（主标题）
    if alignment == WD_ALIGN_PARAGRAPH.CENTER:
        return True
    # 特殊行
    for pattern in NO_INDENT_PATTERNS:
        if re.match(pattern, text.strip()):
            return True
    return False

def analyze_punctuation(doc):
    """分析标点符号问题"""
    issues = []
    
    patterns = [
        ('英文括号', r'[\(\)]'),
        ('英文引号', r'["\']'),
        ('英文冒号', r'(?<=[^\d\s]):(?=[^\d/\\])'),
        ('英文逗号', r'(?<=[^\d]),(?=[^\d])'),
        ('英文分号', r';'),
        ('英文问号', r'\?'),
        ('英文叹号', r'!'),
    ]
    
    # 省略号：2个及以上连续的点（不是省略号格式）
    ellipsis_pattern = r'\.{2,}'
    # 破折号：连续的-
    dash_pattern = r'--+'
    # 句末英文句号：中文后面的单独句点（不是省略号的一部分）
    # 使用负向前瞻确保不是连续句点的一部分
    period_pattern = r'(?<=[一-鿿])\.(?!\.)'
    
    for i, para in enumerate(doc.paragraphs):
        text = para.text
        if not text.strip():
            continue
        
        # 只在包含中文的段落中检查
        if not re.search(r'[一-鿿]', text):
            continue
        
        for name, pattern in patterns:
            for match in re.finditer(pattern, text):
                issues.append({
                    'para': i + 1,
                    'type': name,
                    'char': match.group(),
                })
        
        # 检查省略号（连续多个点）
        for match in re.finditer(ellipsis_pattern, text):
            issues.append({'para': i + 1, 'type': '不规范省略号', 'char': match.group()})
        
        # 检查破折号
        for match in re.finditer(dash_pattern, text):
            issues.append({'para': i + 1, 'type': '不规范破折号', 'char': match.group()})
        
        # 检查句末英文句号（中文后面的单独句点）
        for match in re.finditer(period_pattern, text):
            issues.append({'para': i + 1, 'type': '英文句号', 'char': match.group()})
    
    return issues

def analyze_numbering(doc):
    """分析序号问题"""
    issues = []
    
    numbering_patterns = {
        'chinese_1': r'^[一二三四五六七八九十]+、',
        'chinese_2': r'^（[一二三四五六七八九十]+）',
        'arabic_dot': r'^\d+\.',
        'arabic_comma': r'^\d+、',
        'arabic_paren': r'^\d+[）\)]',
        'arabic_paren_full': r'^（\d+）',
    }
    
    found_styles = defaultdict(list)
    
    for i, para in enumerate(doc.paragraphs):
        text = para.text.strip()
        if not text:
            continue
        
        for style_name, pattern in numbering_patterns.items():
            if re.match(pattern, text):
                found_styles[style_name].append(i + 1)
                break
    
    # 检查阿拉伯数字序号风格是否统一
    arabic_styles = [k for k in found_styles if k.startswith('arabic')]
    if len(arabic_styles) > 1:
        issues.append({
            'type': '序号格式不统一',
            'detail': f"同时存在: {', '.join(arabic_styles)}",
        })
    
    return issues

def analyze_paragraph_format(doc):
    """分析段落格式问题"""
    issues = []
    
    indent_issues = []
    line_spacing_values = defaultdict(list)
    
    for i, para in enumerate(doc.paragraphs):
        text = para.text.strip()
        
        # 跳过空段落和短段落（可能是标题）
        if not text or len(text) < 10:
            continue
        
        alignment = para.paragraph_format.alignment
        
        # 跳过不需要缩进的段落（居中的主标题等）
        if is_no_indent_para(text, alignment):
            continue
        
        pf = para.paragraph_format
        
        # 检查首行缩进
        indent = pf.first_line_indent
        if indent is None or indent == Pt(0) or (hasattr(indent, 'pt') and indent.pt == 0):
            indent_issues.append(i + 1)
        
        # 记录行距
        if pf.line_spacing is not None:
            line_spacing_values[str(pf.line_spacing)].append(i + 1)
    
    if indent_issues:
        issues.append({
            'type': '缺少首行缩进',
            'paras': indent_issues
        })
    
    if len(line_spacing_values) > 1:
        issues.append({
            'type': '行距不统一',
            'detail': f"存在 {len(line_spacing_values)} 种不同行距",
        })
    
    return issues

def analyze_font(doc):
    """分析字体问题"""
    issues = []
    
    font_names = set()
    font_sizes = set()
    
    for para in doc.paragraphs:
        if not para.text.strip():
            continue
        for run in para.runs:
            if run.font.name:
                font_names.add(run.font.name)
            if run.font.size:
                font_sizes.add(str(run.font.size))
    
    if len(font_names) > 4:
        issues.append({
            'type': '字体种类过多',
            'detail': f"检测到 {len(font_names)} 种字体: {', '.join(list(font_names)[:5])}..."
        })
    
    if len(font_sizes) > 4:
        issues.append({
            'type': '字号不统一',
            'detail': f"检测到 {len(font_sizes)} 种字号"
        })
    
    return issues

def print_report(results):
    """打印诊断报告"""
    print('=' * 50)
    print('           格式诊断报告')
    print('=' * 50)
    print()
    
    total = 0
    
    # 标点问题
    punct = results['punctuation']
    if punct:
        by_type = defaultdict(list)
        for issue in punct:
            by_type[issue['type']].append(issue['para'])
        
        print(f"【标点问题】共 {len(punct)} 处")
        for issue_type, paras in by_type.items():
            unique_paras = sorted(set(paras))
            if len(unique_paras) > 5:
                para_str = f"第{unique_paras[0]}、{unique_paras[1]}...{unique_paras[-1]}段"
            else:
                para_str = f"第{', '.join(map(str, unique_paras))}段"
            print(f"  - {issue_type}: {para_str}")
        print()
        total += len(punct)
    
    # 序号问题
    num = results['numbering']
    if num:
        print(f"【序号问题】共 {len(num)} 处")
        for issue in num:
            print(f"  - {issue['type']}: {issue.get('detail', '')}")
        print()
        total += len(num)
    
    # 段落问题
    para = results['paragraph']
    if para:
        print(f"【段落问题】共 {len(para)} 处")
        for issue in para:
            if issue['type'] == '缺少首行缩进':
                paras = issue['paras']
                if len(paras) > 5:
                    para_str = f"第{paras[0]}、{paras[1]}...等{len(paras)}段"
                else:
                    para_str = f"第{', '.join(map(str, paras))}段"
                print(f"  - {issue['type']}: {para_str}")
            else:
                print(f"  - {issue['type']}: {issue.get('detail', '')}")
        print()
        total += len(para)
    
    # 字体问题
    font = results['font']
    if font:
        print(f"【字体问题】共 {len(font)} 处")
        for issue in font:
            print(f"  - {issue['type']}: {issue.get('detail', '')}")
        print()
        total += len(font)
    
    # 总结
    print('-' * 50)
    if total == 0:
        print('OK 未发现明显格式问题')
    else:
        print(f'共发现 {total} 处格式问题')
        print()
        print('建议：')
        if results['punctuation']:
            print('  - 运行 punctuation.py 修复标点问题')
        if results['paragraph'] or results['font']:
            print('  - 运行 formatter.py 统一段落和字体格式')
    print()

def main():
    if len(sys.argv) < 2:
        print('Usage: python analyzer.py input.docx [--json]')
        sys.exit(1)
    
    input_file = sys.argv[1]
    print(f'Analyzing: {input_file}')
    print()
    
    doc = Document(input_file)
    
    results = {
        'punctuation': analyze_punctuation(doc),
        'numbering': analyze_numbering(doc),
        'paragraph': analyze_paragraph_format(doc),
        'font': analyze_font(doc)
    }
    
    if '--json' in sys.argv:
        import json
        print(json.dumps(results, ensure_ascii=False, indent=2))
    else:
        print_report(results)

if __name__ == '__main__':
    main()
```

## File: scripts/converter.py
size: 5220
sha: 562fd8385e0dbcd54a05783e4a42c50915beeb94
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/converter.py

```text
import os
import time
import tempfile
from pathlib import Path

def _ensure_windows():
    if os.name != 'nt':
        raise RuntimeError("当前系统不支持 COM 转换，请在 Windows 上运行")

def _safe_quit(app):
    """安全退出 COM 应用，兼容 Word 和 WPS"""
    if app is None:
        return
    try:
        app.Quit()
    except Exception:
        pass
    time.sleep(0.5)

def _safe_close(doc):
    """安全关闭文档"""
    if doc is None:
        return
    try:
        doc.Close(SaveChanges=False)
    except Exception:
        pass

def _create_app(prog_id):
    """创建 COM 应用实例"""
    import win32com.client

    try:
        app = win32com.client.DispatchEx(prog_id)
    except Exception:
        app = win32com.client.Dispatch(prog_id)

    try:
        app.Visible = False
    except Exception:
        pass
    try:
        app.DisplayAlerts = False
    except Exception:
        pass

    return app

def _detect_all_apps():
    """
    检测系统中所有可用的 Office 应用。
    返回列表：[(prog_id, name), ...]
    """
    _ensure_windows()
    import pythoncom
    import win32com.client

    candidates = [
        ('Kwps.Application', 'WPS'),          # WPS 2019+
        ('wps.Application', 'WPS'),            # WPS 旧版
        ('Word.Application', 'Microsoft Word'),
    ]

    available = []
    pythoncom.CoInitialize()
    try:
        for prog_id, name in candidates:
            try:
                app = win32com.client.Dispatch(prog_id)
                _safe_quit(app)
                available.append((prog_id, name))
            except Exception:
                continue
    finally:
        pythoncom.CoUninitialize()

    return available

def detect_office_app(prefer_wps=False):
    """
    检测安装的 Office 应用，返回 COM ProgID。

    Args:
        prefer_wps: 如果为 True，优先返回 WPS（即使 Word 也可用）

    Returns:
        (prog_id, app_name) 或 (None, None)
    """
    available = _detect_all_apps()
    if not available:
        return None, None

    if prefer_wps:
        # 优先找 WPS
        for prog_id, name in available:
            if name == 'WPS':
                return prog_id, name

    # 返回第一个可用的（默认顺序：WPS > Word）
    return available[0]

def convert_to_docx(input_path, output_path=None):
    """
    将 .doc/.wps 转换为 .docx
    """
    _ensure_windows()
    try:
        import pythoncom
    except ModuleNotFoundError as e:
        raise RuntimeError("缺少 pywin32（pythoncom）。请重新下载最新版 EXE 或安装 pywin32 后再试。") from e

    input_path = Path(input_path).resolve()
    if not input_path.exists():
        raise FileNotFoundError(f"文件不存在: {input_path}")

    if output_path is None:
        fd, temp_path = tempfile.mkstemp(suffix='.docx')
        os.close(fd)
        output_path = temp_path

    output_path = Path(output_path).resolve()

    prog_id, _ = detect_office_app()
    if not prog_id:
        raise RuntimeError("未检测到 WPS 或 Microsoft Office，无法转换 .doc/.wps 文件")

    app = None
    doc = None
    pythoncom.CoInitialize()
    try:
        app = _create_app(prog_id)
        doc = app.Documents.Open(str(input_path))
        doc.SaveAs2(str(output_path), FileFormat=16)
        return str(output_path)
    finally:
        _safe_close(doc)
        _safe_quit(app)
        pythoncom.CoUninitialize()

def convert_from_docx(input_path, output_path, format='doc'):
    """
    将 .docx 转换回 .doc 或 .wps

    处理逻辑：
    - format='doc' → 用任意可用的 Office 应用保存
    - format='wps' → 专门尝试用 WPS 保存；如果 WPS 不可用，回退为 .doc

    Returns:
        str: 实际输出的文件路径（如果回退了格式，路径后缀会变）
    """
    _ensure_windows()
    try:
        import pythoncom
    except ModuleNotFoundError as e:
        raise RuntimeError("缺少 pywin32（pythoncom）。请重新下载最新版 EXE 或安装 pywin32 后再试。") from e

    # .wps 格式必须用 WPS Office 来保存
    if format == 'wps':
        prog_id, app_name = detect_office_app(prefer_wps=True)
        if not prog_id:
            raise RuntimeError("未检测到 Office/WPS")

        if app_name != 'WPS':
            # 系统只有 Word，没有 WPS → 回退为 .doc
            format = 'doc'
            output_path = str(Path(output_path).with_suffix('.doc'))
    else:
        prog_id, app_name = detect_office_app()
        if not prog_id:
            raise RuntimeError("未检测到 Office/WPS")

    # FileFormat 常量
    format_map = {
        'doc': 0,    # wdFormatDocument (.doc)
        'wps': 0,    # WPS 用 FileFormat=0 保存，扩展名决定实际格式
    }

    app = None
    doc = None
    pythoncom.CoInitialize()
    try:
        time.sleep(1)

        app = _create_app(prog_id)
        doc = app.Documents.Open(str(Path(input_path).resolve()))
        doc.SaveAs2(str(Path(output_path).resolve()), FileFormat=format_map.get(format, 0))

        return output_path
    finally:
        _safe_close(doc)
        _safe_quit(app)
        pythoncom.CoUninitialize()
```

## File: scripts/fix_spacing.py
size: 1243
sha: c97b8cbe97a8f7c510023e70ab2cda925f9ab254
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/fix_spacing.py

```text
#!/usr/bin/env python3
"""行距统一工具 - 修复段落行距不一致"""

import sys
from docx import Document
from docx.shared import Pt

def fix_line_spacing(input_path, output_path):
    """统一段落行距"""
    print(f"Reading: {input_path}")
    doc = Document(input_path)

    # 公文标准行距：28pt固定值（约355600 twips）
    target_spacing = 355600  # 28pt in twips

    changes = 0

    for i, para in enumerate(doc.paragraphs):
        text = para.text.strip()
        if not text:
            continue

        pf = para.paragraph_format

        # 跳过标题（通常行距可能不同）
        # 标题特征：短、居中、有特定编号
        if len(text) < 20 or pf.alignment is not None:
            continue

        # 修改行距为固定值28pt
        if pf.line_spacing != target_spacing:
            pf.line_spacing = Pt(28)  # 设置为28pt固定值
            changes += 1

    print(f"Fixed line spacing for {changes} paragraphs")
    doc.save(output_path)
    print(f"Saved: {output_path}")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python fix_spacing.py input.docx output.docx")
        sys.exit(1)

    fix_line_spacing(sys.argv[1], sys.argv[2])
```

## File: scripts/fix_spacing_simple.py
size: 874
sha: 43ceeaaa3a81f912527f256ce73376867004d234
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/fix_spacing_simple.py

```text
#!/usr/bin/env python3
"""行距统一工具 - 简化版"""

import sys
from docx import Document
from docx.shared import Pt

def fix_line_spacing(input_path, output_path):
    """统一所有段落行距为28pt固定值"""
    print(f"Reading: {input_path}")
    doc = Document(input_path)

    # 修改所有段落的行距
    for i, para in enumerate(doc.paragraphs):
        text = para.text.strip()
        if not text:
            continue

        pf = para.paragraph_format

        # 统一设置为28pt固定值
        pf.line_spacing = Pt(28)

    print("Fixed line spacing for all text paragraphs")
    doc.save(output_path)
    print(f"Saved: {output_path}")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python fix_spacing_simple.py input.docx output.docx")
        sys.exit(1)

    fix_line_spacing(sys.argv[1], sys.argv[2])
```

## File: scripts/formatter.py
size: 85104
sha: 43e88524399b920b19b7f52fee06bf1216955d53
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/formatter.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/formatter.py

## File: scripts/from_text.py
size: 10588
sha: 9c386818598b9f01cd66a25dfc5e0012d586fe0e
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/from_text.py

````text
#!/usr/bin/env python3
"""Create a DOCX from plain text or Markdown, then optionally format it."""

import argparse
import logging
import os
import re
import sys
import tempfile
from copy import deepcopy
from pathlib import Path

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt

ROOT_DIR = Path(__file__).resolve().parent.parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from scripts.formatter import (  # noqa: E402
    PRESETS,
    _merge_preset_settings,
    format_document,
    load_custom_preset,
    load_preset_file,
)
from scripts.punctuation import process_document as fix_punctuation  # noqa: E402

logger = logging.getLogger("docformat.from_text")

def detect_markdown(text):
    """Heuristically detect whether text looks like Markdown."""
    if not text or not text.strip():
        return False
    text = text.lstrip("﻿")

    score = 0
    lines = text.split("\n")

    if sum(1 for line in lines if re.match(r"^\s*#{1,6}\s+\S", line)) >= 1:
        score += 3
    if len(re.findall(r"\*\*[^*\n]+\*\*", text)) >= 2:
        score += 2
    if sum(1 for line in lines if re.match(r"^\s*[-*+]\s+\S", line)) >= 2:
        score += 2
    if "```" in text:
        score += 2
    if sum(1 for line in lines if line.startswith("> ")) >= 1:
        score += 1

    return score >= 3

def parse_markdown_inline(text):
    """Return [(text, is_bold), ...] for **bold** and __bold__ spans."""
    parts = []
    pattern = re.compile(r"\*\*([^*\n]+)\*\*|__([^_\n]+)__")
    last_end = 0

    for match in pattern.finditer(text):
        if match.start() > last_end:
            parts.append((text[last_end:match.start()], False))
        bold_text = match.group(1) or match.group(2)
        if bold_text:
            parts.append((bold_text, True))
        last_end = match.end()

    if last_end < len(text):
        parts.append((text[last_end:], False))

    return parts or [(text, False)]

def _add_title(doc, title):
    para = doc.add_paragraph()
    para.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = para.add_run(title.strip())
    run.font.size = Pt(22)
    return para

def create_docx_from_text(title, body_text, output_path):
    """Create a minimal DOCX from title and plain text."""
    doc = Document()
    _add_title(doc, title)

    body_text = body_text.strip()
    if body_text:
        for block in body_text.split("\n\n"):
            block = block.strip()
            if not block:
                continue
            for line in block.split("\n"):
                line = line.strip()
                if line:
                    doc.add_paragraph(line)

    doc.save(output_path)
    return output_path

def create_docx_from_markdown(title, md_text, output_path):
    """Create a DOCX from a small, document-oriented Markdown subset."""
    doc = Document()
    lines = md_text.split("\n")

    cn_nums = [
        "一", "二", "三", "四", "五", "六", "七", "八", "九", "十",
        "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
    ]

    def cn(n):
        return cn_nums[n - 1] if 1 <= n <= len(cn_nums) else str(n)

    h2_counter = 0
    h3_counters = {}
    h4_counters = {}
    current_h2 = 0
    current_h3 = 0
    title_added = False
    in_code_block = False
    code_buffer = []

    def add_para_with_inline(text, alignment=None, size=None):
        para = doc.add_paragraph()
        if alignment is not None:
            para.alignment = alignment
        for content, is_bold in parse_markdown_inline(text):
            if not content:
                continue
            run = para.add_run(content)
            run.font.bold = is_bold
            if size:
                run.font.size = Pt(size)
        return para

    def flush_code():
        for code_line in code_buffer:
            if code_line.strip():
                doc.add_paragraph(code_line)
        code_buffer.clear()

    for line in lines:
        if line.strip().startswith("```"):
            if in_code_block:
                flush_code()
                in_code_block = False
            else:
                in_code_block = True
            continue

        if in_code_block:
            code_buffer.append(line)
            continue

        if not line.strip():
            continue

        heading = re.match(r"^\s*(#{1,6})\s*(.*)$", line)
        if heading:
            level = len(heading.group(1))
            content = heading.group(2).strip()
            if level == 1 and not title_added:
                add_para_with_inline(content, alignment=WD_ALIGN_PARAGRAPH.CENTER, size=22)
                title_added = True
            elif level <= 2:
                h2_counter += 1
                current_h2 = h2_counter
                add_para_with_inline(f"{cn(h2_counter)}、{content}")
            elif level == 3:
                h3_counters[current_h2] = h3_counters.get(current_h2, 0) + 1
                current_h3 = h3_counters[current_h2]
                add_para_with_inline(f"（{cn(current_h3)}）{content}")
            else:
                key = (current_h2, current_h3)
                h4_counters[key] = h4_counters.get(key, 0) + 1
                add_para_with_inline(f"{h4_counters[key]}. {content}")
            continue

        unordered = re.match(r"^\s*[-*+]\s+(.*)$", line)
        ordered = re.match(r"^\s*\d+\.\s+(.*)$", line)
        quote = re.match(r"^>\s+(.*)$", line)
        if unordered:
            add_para_with_inline(unordered.group(1).strip())
        elif ordered:
            add_para_with_inline(ordered.group(1).strip())
        elif quote:
            add_para_with_inline(quote.group(1).strip())
        else:
            add_para_with_inline(line.strip())

    if in_code_block:
        flush_code()

    if not title_added and title.strip():
        title_para = _add_title(doc, title)
        body = doc.element.body
        body.remove(title_para._p)
        body.insert(0, title_para._p)

    doc.save(output_path)
    return output_path

def _format_overrides(args):
    overrides = {}
    if args.deep_clean:
        overrides["deep_clean"] = True
    if args.smart_table_align:
        overrides.setdefault("table", {})["smart_align"] = True
    if args.no_page_number:
        overrides["page_number"] = False
    return overrides

def _load_custom_settings(args):
    settings = load_preset_file(args.custom_settings) if args.custom_settings else None
    overrides = _format_overrides(args)
    if args.preset == "custom" and overrides and settings is None:
        settings = load_custom_preset() or deepcopy(PRESETS["official"])
    if overrides:
        settings = _merge_preset_settings(settings or {}, overrides)
    return settings

def generate_and_process(args):
    text = Path(args.input).read_text(encoding=args.encoding).lstrip("﻿")
    title = args.title or Path(args.input).stem
    use_markdown = args.markdown or (not args.plain and detect_markdown(text))

    if args.no_process:
        raw_output = args.output
    else:
        fd, raw_output = tempfile.mkstemp(suffix=".docx")
        os.close(fd)

    try:
        if use_markdown:
            create_docx_from_markdown(title, text, raw_output)
            logger.info("Generated raw DOCX from Markdown")
        else:
            create_docx_from_text(title, text, raw_output)
            logger.info("Generated raw DOCX from plain text")

        if args.no_process:
            logger.info("Saved: %s", args.output)
            return args.output

        fd, fixed_path = tempfile.mkstemp(suffix=".docx")
        os.close(fd)
        try:
            fix_punctuation(raw_output, fixed_path, space_mode=args.space_mode)
            format_document(
                fixed_path,
                args.output,
                preset_name=args.preset,
                revision_mode=args.revision,
                bold_serial=not args.no_bold_serial,
                custom_settings=_load_custom_settings(args),
            )
        finally:
            if os.path.exists(fixed_path):
                os.unlink(fixed_path)

        logger.info("Saved: %s", args.output)
        return args.output
    finally:
        if not args.no_process and os.path.exists(raw_output):
            os.unlink(raw_output)

def main(argv=None):
    parser = argparse.ArgumentParser(
        description="Create a DOCX from .txt/.md content and optionally apply smart formatting."
    )
    parser.add_argument("input", help="Input text or Markdown file")
    parser.add_argument("output", help="Output .docx file")
    parser.add_argument("--title", help="Document title; defaults to input file stem")
    parser.add_argument("--encoding", default="utf-8-sig", help="Input file encoding")
    parser.add_argument("--markdown", action="store_true", help="Treat input as Markdown")
    parser.add_argument("--plain", action="store_true", help="Treat input as plain text")
    parser.add_argument("--no-process", action="store_true", help="Only generate DOCX, without punctuation/formatting")
    parser.add_argument(
        "--space-mode",
        choices=("remove_all", "keep_en_boundary", "keep_all"),
        default="remove_all",
        help="Spacing mode used during punctuation processing.",
    )
    parser.add_argument(
        "--preset",
        choices=tuple(PRESETS.keys()) + ("custom",),
        default="official",
        help="Formatting preset.",
    )
    parser.add_argument("--custom-settings", help="Custom preset/config JSON file")
    parser.add_argument("--revision", action="store_true", help="Output supported formatting changes as revisions")
    parser.add_argument("--no-bold-serial", action="store_true", help="Do not bold 一是/二是 body prefixes")
    parser.add_argument("--deep-clean", action="store_true", help="Clear inherited formatting before applying preset")
    parser.add_argument("--smart-table-align", action="store_true", help="Align table cells by content type")
    parser.add_argument("--no-page-number", action="store_true", help="Skip adding page numbers")
    parser.add_argument(
        "--log-level",
        default="INFO",
        choices=("DEBUG", "INFO", "WARNING", "ERROR"),
        help="Logging level.",
    )
    args = parser.parse_args(argv)

    if args.markdown and args.plain:
        parser.error("--markdown and --plain cannot be used together")

    logging.basicConfig(level=getattr(logging, args.log_level), format="%(message)s")
    generate_and_process(args)

if __name__ == "__main__":
    main()
````

## File: scripts/process.py
size: 8968
sha: 266a5ab984f082fd536c3474130992a90f0d27d2
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/process.py

```text
#!/usr/bin/env python3
"""One-shot CLI pipeline for document formatting tasks."""

import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
from copy import deepcopy
from pathlib import Path

from docx import Document

ROOT_DIR = Path(__file__).resolve().parent.parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from scripts.analyzer import (  # noqa: E402
    analyze_font,
    analyze_numbering,
    analyze_paragraph_format,
    analyze_punctuation,
    print_report,
)
from scripts.formatter import (  # noqa: E402
    PRESETS,
    _merge_preset_settings,
    format_document,
    load_custom_preset,
    load_preset_file,
)
from scripts.punctuation import process_document as fix_punctuation  # noqa: E402

logger = logging.getLogger("docformat.process")

def analyze_document(path, as_json=False):
    doc = Document(path)
    results = {
        "punctuation": analyze_punctuation(doc),
        "numbering": analyze_numbering(doc),
        "paragraph": analyze_paragraph_format(doc),
        "font": analyze_font(doc),
    }
    if as_json:
        print(json.dumps(results, ensure_ascii=False, indent=2))
    else:
        print_report(results)
    return results

def _format_overrides(args):
    overrides = {}
    if args.deep_clean:
        overrides["deep_clean"] = True
    if args.split_heading_at_punct:
        overrides["split_heading_at_punct"] = True
    if args.smart_table_align:
        overrides.setdefault("table", {})["smart_align"] = True
    if args.no_page_number:
        overrides["page_number"] = False
    if args.no_replace_existing_page_number:
        overrides["replace_existing_page_number"] = False

    page_number_fields = {
        "page_number_style": args.page_number_style,
        "page_number_position": args.page_number_position,
        "page_number_offset_mm": args.page_number_offset_mm,
        "page_number_size": args.page_number_size,
        "page_number_font": args.page_number_font,
    }
    for key, value in page_number_fields.items():
        if value is not None:
            overrides[key] = value

    return overrides

def _load_cli_custom_settings(args):
    settings = load_preset_file(args.custom_settings) if args.custom_settings else None
    overrides = _format_overrides(args)
    if args.preset == "custom" and overrides and settings is None:
        settings = load_custom_preset() or deepcopy(PRESETS["official"])
    if overrides:
        settings = _merge_preset_settings(settings or {}, overrides)
    return settings

def _convert_input_if_needed(path):
    ext = Path(path).suffix.lower()
    if ext not in (".doc", ".wps"):
        return path, None

    if os.name != "nt":
        raise RuntimeError(".doc/.wps conversion is only available on Windows with Word or WPS installed")

    from scripts.converter import convert_to_docx

    logger.info("Converting %s to .docx...", ext)
    temp_docx = convert_to_docx(path)
    return temp_docx, temp_docx

def _prepare_output_path(output_path):
    ext = Path(output_path).suffix.lower()
    if ext not in (".doc", ".wps"):
        return output_path, None

    fd, temp_output = tempfile.mkstemp(suffix=".docx")
    os.close(fd)
    return temp_output, temp_output

def _convert_output_if_needed(temp_output_docx, requested_output):
    requested_ext = Path(requested_output).suffix.lower()
    if requested_ext not in (".doc", ".wps"):
        return requested_output

    if os.name != "nt":
        fallback = str(Path(requested_output).with_suffix(".docx"))
        shutil.copy2(temp_output_docx, fallback)
        logger.warning("Cannot convert to %s on this platform; saved %s", requested_ext, fallback)
        return fallback

    from scripts.converter import convert_from_docx

    try:
        return convert_from_docx(
            temp_output_docx,
            requested_output,
            format=requested_ext.lstrip("."),
        )
    except Exception as exc:
        fallback = str(Path(requested_output).with_suffix(".docx"))
        shutil.copy2(temp_output_docx, fallback)
        logger.warning("Output conversion failed: %s; saved %s", exc, fallback)
        return fallback

def run_pipeline(args):
    input_path, temp_input = _convert_input_if_needed(args.input)
    output_docx = None
    temp_output = None
    try:
        if args.mode == "analyze":
            return analyze_document(input_path, as_json=args.json)

        output_docx, temp_output = _prepare_output_path(args.output)

        if args.mode == "punctuation":
            fix_punctuation(input_path, output_docx, space_mode=args.space_mode)
        elif args.mode == "format":
            format_document(
                input_path,
                output_docx,
                preset_name=args.preset,
                revision_mode=args.revision,
                bold_serial=not args.no_bold_serial,
                custom_settings=_load_cli_custom_settings(args),
            )
        elif args.mode == "smart":
            fd, temp_fixed = tempfile.mkstemp(suffix=".docx")
            os.close(fd)
            try:
                fix_punctuation(input_path, temp_fixed, space_mode=args.space_mode)
                format_document(
                    temp_fixed,
                    output_docx,
                    preset_name=args.preset,
                    revision_mode=args.revision,
                    bold_serial=not args.no_bold_serial,
                    custom_settings=_load_cli_custom_settings(args),
                )
            finally:
                if os.path.exists(temp_fixed):
                    os.unlink(temp_fixed)
        else:
            raise ValueError(f"Unknown mode: {args.mode}")

        actual_output = _convert_output_if_needed(output_docx, args.output)
        logger.info("Saved: %s", actual_output)
        return actual_output
    finally:
        for path in (temp_input, temp_output):
            if path and os.path.exists(path):
                try:
                    os.unlink(path)
                except OSError:
                    pass

def main(argv=None):
    parser = argparse.ArgumentParser(
        description="Analyze, fix punctuation, format, or smart-process document files."
    )
    parser.add_argument("mode", choices=("smart", "analyze", "punctuation", "format"))
    parser.add_argument("input", help="Input .docx file; .doc/.wps are supported on Windows with Office/WPS")
    parser.add_argument("output", nargs="?", help="Output file for non-analyze modes")
    parser.add_argument("--json", action="store_true", help="Print analysis result as JSON")
    parser.add_argument(
        "--space-mode",
        choices=("remove_all", "keep_en_boundary", "keep_all"),
        default="remove_all",
        help="Spacing mode used during punctuation/smart processing.",
    )
    parser.add_argument(
        "--preset",
        choices=tuple(PRESETS.keys()) + ("custom",),
        default="official",
        help="Formatting preset.",
    )
    parser.add_argument("--custom-settings", help="Custom preset/config JSON file")
    parser.add_argument("--revision", action="store_true", help="Output supported formatting changes as revisions")
    parser.add_argument("--no-bold-serial", action="store_true", help="Do not bold 一是/二是 body prefixes")
    parser.add_argument("--deep-clean", action="store_true", help="Clear inherited formatting before applying preset")
    parser.add_argument("--split-heading-at-punct", action="store_true", help="Split heading+body paragraphs at punctuation")
    parser.add_argument("--smart-table-align", action="store_true", help="Align table cells by content type")
    parser.add_argument("--no-page-number", action="store_true", help="Skip adding page numbers")
    parser.add_argument(
        "--page-number-style",
        choices=("dash", "plain", "page_text", "page_total"),
        help="Page number style.",
    )
    parser.add_argument(
        "--page-number-position",
        choices=("outside", "left", "center", "right"),
        help="Page number position.",
    )
    parser.add_argument("--page-number-offset-mm", type=float, help="Page number offset below text area")
    parser.add_argument("--page-number-size", type=int, help="Page number font size")
    parser.add_argument("--page-number-font", help="Page number font")
    parser.add_argument("--no-replace-existing-page-number", action="store_true", help="Keep existing page numbers")
    parser.add_argument(
        "--log-level",
        default="INFO",
        choices=("DEBUG", "INFO", "WARNING", "ERROR"),
        help="Logging level.",
    )
    args = parser.parse_args(argv)

    if args.mode != "analyze" and not args.output:
        parser.error("output is required for smart, punctuation, and format modes")

    logging.basicConfig(level=getattr(logging, args.log_level), format="%(message)s")
    run_pipeline(args)

if __name__ == "__main__":
    main()
```

## File: scripts/punctuation.py
size: 13225
sha: f926615390712ff5bba7a1894838992f0d7a3ded
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/scripts/punctuation.py

```text
#!/usr/bin/env python3
"""
标点符号修复 v5
- 修复引号处理bug：使用明确的Unicode转义序列
- 正确处理省略号和句号
"""

import re
import sys
import argparse
from docx import Document

# 中文标点（使用Unicode转义确保正确）
LEFT_DOUBLE_QUOTE = '“'   # " 左双引号
RIGHT_DOUBLE_QUOTE = '”'  # " 右双引号
LEFT_SINGLE_QUOTE = '‘'   # ' 左单引号
RIGHT_SINGLE_QUOTE = '’'  # ' 右单引号

# 基本替换映射
REPLACEMENTS = {
    "(": "（",
    ")": "）",
    ":": "：",
    ";": "；",
    "?": "？",
    "!": "！",
}

# 占位符前缀（使用不可能出现在正常文本中的字符序列）
_PLACEHOLDER_PREFIX = "\x02PROT"

def _protect_special_patterns(text):
    """提取并保护不应被替换的特殊模式，返回 (处理后文本, 保护列表)"""
    protected = []
    counter = [0]

    def _replace_with_placeholder(match):
        placeholder = f"{_PLACEHOLDER_PREFIX}{counter[0]}\x03"
        protected.append((placeholder, match.group()))
        counter[0] += 1
        return placeholder

    result = text

    # 保护 URL（http:// https:// ftp://）
    result = re.sub(r"(?:https?|ftp)://\S+", _replace_with_placeholder, result)

    # 保护邮箱地址
    result = re.sub(r"[\w.+-]+@[\w-]+\.[\w.-]+", _replace_with_placeholder, result)

    # 保护 Windows 文件路径 C:\ D:\
    result = re.sub(r"[A-Za-z]:\\", _replace_with_placeholder, result)

    # 保护标准编号 ISO 9001:2015 等（字母+数字+冒号+数字）
    result = re.sub(r"[A-Za-z]+[\s-]?\d+:\d{2,}", _replace_with_placeholder, result)

    # 保护时间格式 HH:MM 或 HH:MM:SS
    # 注意：不能用 \b，因为 Python3 中中文字符也属于 \w，
    # 导致"上午9:30"中 午 和 9 之间没有 \b 边界
    result = re.sub(r"(?<!\d)(\d{1,2}:\d{2}(?::\d{2})?)(?!\d)", _replace_with_placeholder, result)

    return result, protected

def _restore_protected(text, protected):
    """恢复被保护的内容"""
    result = text
    for placeholder, original in protected:
        result = result.replace(placeholder, original)
    return result

def has_chinese(text):
    """检查是否包含中文"""
    return bool(re.search(r"[一-鿿]", text))

def fix_text(text):
    """修复文本中的标点"""
    if not text:
        return text

    # 保护特殊模式
    result, protected = _protect_special_patterns(text)

    # ===== 第一步：处理省略号（必须在句号之前）=====
    result = re.sub(r"\.{2,}", "……", result)
    result = re.sub(r"。{2,}", "……", result)

    # ===== 第二步：处理破折号 =====
    result = re.sub(r"--+", "——", result)
    result = re.sub(r"—(?!—)", "——", result)

    # ===== 第三步：基本标点替换（只在有中文的文本中）=====
    if has_chinese(result):
        for en, cn in REPLACEMENTS.items():
            result = result.replace(en, cn)

    # ===== 第四步：逗号特殊处理 =====
    result = re.sub(r"([一-鿿]),", r"\1，", result)
    result = re.sub(r",([一-鿿])", r"，\1", result)

    # ===== 第五步：句号特殊处理 =====
    result = re.sub(r"([一-鿿])\.(\s|$)", r"\1。\2", result)

    # ===== 第六步：双引号处理 =====
    # 需要处理的双引号字符（使用Unicode确保正确）
    double_quote_chars = [
        '"',        # U+0022 ASCII直引号
        '“',   # U+201C 左双引号 "
        '”',   # U+201D 右双引号 "
        '„',   # U+201E 双低引号 „
        '‟',   # U+201F 双高反引号 ‟
        '「',   # U+300C 日文左引号 「
        '」',   # U+300D 日文右引号 」
    ]

    # 统一替换为临时标记
    temp_result = result
    for q in double_quote_chars:
        temp_result = temp_result.replace(q, "\x00")

    # 配对处理
    if "\x00" in temp_result:
        chars = list(temp_result)
        quote_count = 0
        for i, c in enumerate(chars):
            if c == "\x00":
                # 偶数位置用左引号，奇数位置用右引号
                if quote_count % 2 == 0:
                    chars[i] = LEFT_DOUBLE_QUOTE  # "
                else:
                    chars[i] = RIGHT_DOUBLE_QUOTE  # "
                quote_count += 1
        result = "".join(chars)

    # ===== 第七步：单引号处理 =====
    single_quote_chars = [
        "'",        # U+0027 ASCII单引号
        '‘',   # U+2018 左单引号 '
        '’',   # U+2019 右单引号 '
        '‚',   # U+201A 单低引号 ‚
        '‛',   # U+201B 单高反引号 ‛
    ]

    temp_result = result
    for q in single_quote_chars:
        temp_result = temp_result.replace(q, "\x01")

    if "\x01" in temp_result:
        chars = list(temp_result)
        quote_count = 0
        for i, c in enumerate(chars):
            if c == "\x01":
                # 偶数位置用左引号，奇数位置用右引号
                if quote_count % 2 == 0:
                    chars[i] = LEFT_SINGLE_QUOTE  # '
                else:
                    chars[i] = RIGHT_SINGLE_QUOTE  # '
                quote_count += 1
        result = "".join(chars)

    # 恢复被保护的内容
    result = _restore_protected(result, protected)
    return result

def _fix_simple_punctuation(text):
    """只做不涉及配对的简单标点替换，保留引号不动"""
    if not text:
        return text

    # 保护特殊模式
    result, protected = _protect_special_patterns(text)

    # 省略号（必须在句号之前）
    result = re.sub(r"\.{2,}", "……", result)
    result = re.sub(r"。{2,}", "……", result)

    # 破折号
    result = re.sub(r"--+", "——", result)
    result = re.sub(r"—(?!—)", "——", result)

    # 基本替换（只在有中文时）
    if has_chinese(result):
        for en, cn in REPLACEMENTS.items():
            result = result.replace(en, cn)

    # 逗号
    result = re.sub(r"([一-鿿]),", r"\1，", result)
    result = re.sub(r",([一-鿿])", r"，\1", result)

    # 句号
    result = re.sub(r"([一-鿿])\.(\s|$)", r"\1。\2", result)

    # 恢复被保护的内容
    result = _restore_protected(result, protected)
    return result

def _fix_quotes_whole_text(text):
    """对完整文本做引号配对替换"""
    result = text

    # 双引号
    double_quote_chars = ['"', "“", "”", "„", "‟", "「", "」"]
    temp = result
    for q in double_quote_chars:
        temp = temp.replace(q, "\x00")

    if "\x00" in temp:
        chars = list(temp)
        quote_idx = 0
        for i, c in enumerate(chars):
            if c == "\x00":
                chars[i] = LEFT_DOUBLE_QUOTE if quote_idx % 2 == 0 else RIGHT_DOUBLE_QUOTE
                quote_idx += 1
        result = "".join(chars)

    # 单引号
    single_quote_chars = ["'", "‘", "’", "‚", "‛"]
    temp = result
    for q in single_quote_chars:
        temp = temp.replace(q, "\x01")

    if "\x01" in temp:
        chars = list(temp)
        quote_idx = 0
        for i, c in enumerate(chars):
            if c == "\x01":
                chars[i] = LEFT_SINGLE_QUOTE if quote_idx % 2 == 0 else RIGHT_SINGLE_QUOTE
                quote_idx += 1
        result = "".join(chars)

    return result

def _redistribute_text_to_runs(runs, new_full_text):
    """将新的完整文本按原 run 的长度边界重新分配回各 run，保留格式"""
    run_lengths = [len(run.text) for run in runs]

    # 如果长度一致（只是字符替换，没有增删），直接按原长度切分
    total_original = sum(run_lengths)
    if len(new_full_text) == total_original:
        pos = 0
        for i, run in enumerate(runs):
            run.text = new_full_text[pos:pos + run_lengths[i]]
            pos += run_lengths[i]
    else:
        # 长度变了（极少情况），回退到旧方案：全塞第一个 run
        runs[0].text = new_full_text
        for run in runs[1:]:
            run.text = ""

def _process_spaces_text(text, mode):
    """根据 mode 处理文本中的空格，返回处理后的文本"""
    if mode == 'keep_all' or not text:
        return text
    if mode == 'remove_all':
        # 删除所有半角空格和全角空格
        return text.replace('　', '').replace(' ', '')
    if mode == 'keep_en_boundary':
        CN = r'一-鿿㐀-䶿豈-﫿'
        EN = r'[A-Za-z0-9]'
        CN_cls = f'[{CN}]'

        # 第一步：删除纯中文之间的空格（不涉及英文/数字边界）
        text = re.sub(f'(?<={CN_cls}) +(?={CN_cls})', '', text)

        # 第二步：将中文与英文/数字边界处的空格（0个或多个）统一替换为恰好1个
        # 中文 → 英文/数字
        text = re.sub(f'(?<={CN_cls}) *(?={EN})', ' ', text)
        # 英文/数字 → 中文
        text = re.sub(f'(?<={EN}) *(?={CN_cls})', ' ', text)

        # 第三步：修正因第二步可能在段落首尾产生的多余前导/尾随空格
        # 段落开头的英文/数字不应有前导空格
        text = re.sub(r'^ +', '', text)
        # 段落结尾的英文/数字不应有尾随空格
        text = re.sub(r' +$', '', text)

        return text
    return text

def process_spaces(para, mode='remove_all'):
    """处理段落内空格，返回 True 表示有改动"""
    if mode == 'keep_all':
        return False
    full_text = para.text
    if not full_text.strip():
        return False
    new_text = _process_spaces_text(full_text, mode)
    if new_text == full_text:
        return False
    _redistribute_text_to_runs(para.runs, new_text)
    return True

def process_paragraph(para, space_mode='remove_all'):
    """处理段落 - 简单替换按 run 做（保留格式），引号配对跨 run 做"""
    full_text = para.text
    if not full_text.strip():
        return False

    runs = para.runs
    if not runs:
        return False

    changed = False

    # 第一步：逐 run 做简单标点替换（保留所有格式）
    for run in runs:
        original = run.text
        fixed = _fix_simple_punctuation(original)
        if fixed != original:
            run.text = fixed
            changed = True

    # 第二步：引号配对需要整段处理
    full_after_simple = para.text
    full_after_quotes = _fix_quotes_whole_text(full_after_simple)

    if full_after_quotes != full_after_simple:
        _redistribute_text_to_runs(runs, full_after_quotes)
        changed = True

    # 空格处理
    if process_spaces(para, space_mode):
        changed = True

    return changed

def process_document(input_path, output_path, space_mode='remove_all'):
    """处理文档"""
    print(f"Reading: {input_path}")
    print(f"Space mode: {space_mode}")
    doc = Document(input_path)

    changes = 0

    # 处理段落
    for i, para in enumerate(doc.paragraphs):
        if process_paragraph(para, space_mode=space_mode):
            changes += 1
            preview = para.text[:50] + "..." if len(para.text) > 50 else para.text
            print(f"  Para {i + 1}: {preview}")

    # 处理表格
    table_changes = 0
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for para in cell.paragraphs:
                    if process_paragraph(para, space_mode=space_mode):
                        table_changes += 1

    if table_changes > 0:
        print(f"  Tables: {table_changes} cells fixed")

    print()
    print(f"Total: {changes} paragraphs + {table_changes} table cells fixed")
    doc.save(output_path)
    print(f"Saved: {output_path}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Fix Chinese document punctuation and optional spacing in a DOCX file."
    )
    parser.add_argument("input", help="Input .docx file")
    parser.add_argument("output", help="Output .docx file")
    parser.add_argument(
        "--space-mode",
        choices=("remove_all", "keep_en_boundary", "keep_all"),
        default="remove_all",
        help=(
            "Space handling: remove_all deletes all spaces; keep_en_boundary keeps one "
            "space between Chinese and English/digits; keep_all preserves spaces."
        ),
    )
    args = parser.parse_args()

    process_document(args.input, args.output, space_mode=args.space_mode)

# 测试用例（验证 fix_text）
# assert fix_text('会议时间:上午9:30至下午14:30,请准时参加.') == '会议时间：上午9:30至下午14:30，请准时参加。'
# assert fix_text('请于14:30前将材料发送至 report@gov.cn,逾期不候.') == '请于14:30前将材料发送至 report@gov.cn，逾期不候。'
# assert fix_text('详情请访问 https://www.example.com:8080/path 了解.') == '详情请访问 https://www.example.com:8080/path 了解。'
# assert fix_text('参照 ISO 9001:2015 执行.') == '参照 ISO 9001:2015 执行。'
# assert fix_text('每日9:00前完成巡检.') == '每日9:00前完成巡检。'
# assert '还需要改进' in fix_text('他说"这个方案"不错，但是"还需要改进')  # 奇数引号照常替换
```

## File: .gitignore
size: 78
sha: fa1b0bf0c07a28db18ca60221894fc8a4e29cce7
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/.gitignore

```text
__pycache__/
*.py[cod]
.pytest_cache/
.venv/
venv/
custom_settings.json
*.tmp
```

## File: LICENSE
size: 1071
sha: 00b05e572565475653d95722370b24fddd2c5aba
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2025 Gloria LaRoche

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: pytest.ini
size: 42
sha: 4584de7e860925957a2daa58cfb4de8acc1e4802
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/pytest.ini

```text
[pytest]
testpaths = tests
pythonpath = .
```

## File: README_CN.md
size: 3703
sha: 37ee8124d6c5de3922922fefbd6a08a074a4846c
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/README_CN.md

````text
# document-format-skills 公文格式助手

用于清理和格式化中文 Word 文档的命令行 Skill。当前核心处理逻辑已同步到 [Document Format GUI](https://github.com/KaguraNanaga/docformat-gui) v1.8.7，适合 Codex、Claude Code、OpenCode 等 agent 在没有桌面 UI 的场景下直接调用。

英文说明 / English docs: [README.md](./README.md)

> 🌐 **不想安装，也不需要 Agent？**
>
> 直接打开 **[公文格式处理工具网页版](https://web.gongwengeshizhushou.com)**，选择 `.docx` 文档即可开始处理。无需登录，文档只在当前浏览器中处理，不会上传到服务器。

## 功能

- 智能一键处理：标点/空格清理 + 文档格式统一。
- 格式诊断：检查标点、序号、段落、字体问题。
- 内置公文、学术论文、法律文书预设。
- 公文格式支持页边距、字体字号、行距、标题层级、主送机关、落款、日期、页码等规范化。
- 页码支持样式、位置、距版心偏移、替换已有页码，并避免覆盖非页码页脚内容。
- 表格格式统一，支持可选的智能对齐。
- 支持桌面端 schema v2 自定义配置和导出的 preset JSON。
- 支持输出 Word 修订标记。
- 支持 macOS 常用中文公文字体回退。
- Windows 下可借助 WPS Office 或 Microsoft Word 处理 `.doc` / `.wps`。
- 支持从纯文本或 Markdown 生成并格式化 DOCX。

## 环境要求

- Python 3.8+
- `python-docx`
- Windows `.doc/.wps` 转换需要 `pywin32`、WPS Office 或 Microsoft Word

推荐使用 `uv` 临时安装依赖：

```bash
uv run --with python-docx python scripts/process.py --help
```

Windows 处理 `.doc/.wps` 时：

```bash
uv run --with python-docx --with pywin32 python scripts/process.py --help
```

## 快速开始

智能一键处理：

```bash
uv run --with python-docx python scripts/process.py smart input.docx output.docx --preset official
```

只做诊断：

```bash
uv run --with python-docx python scripts/process.py analyze input.docx
uv run --with python-docx python scripts/process.py analyze input.docx --json
```

只修复标点和空格：

```bash
uv run --with python-docx python scripts/process.py punctuation input.docx output.docx --space-mode keep_en_boundary
```

只应用格式：

```bash
uv run --with python-docx python scripts/process.py format input.docx output.docx --preset official
```

从 Markdown 或纯文本生成格式化 DOCX：

```bash
uv run --with python-docx python scripts/from_text.py input.md output.docx --title "工作方案"
```

## 常用参数

```bash
--preset official|academic|legal|custom
--custom-settings path.json
--revision
--deep-clean
--smart-table-align
--no-page-number
--page-number-style dash|plain|page_text|page_total
--page-number-position outside|left|center|right
--space-mode remove_all|keep_en_boundary|keep_all
```

`--custom-settings` 支持三类 JSON：桌面端 schema v2 配置、形如 `{"preset": {...}}` 的导出预设、普通 preset/override 字典。非 `custom` 预设下会把 JSON 合并到所选预设上。

## 脚本说明

| 脚本 | 用途 |
| --- | --- |
| `scripts/process.py` | 主入口：`smart`、`analyze`、`punctuation`、`format`。 |
| `scripts/formatter.py` | 格式化引擎和预设处理。 |
| `scripts/punctuation.py` | 标点和空格修复。 |
| `scripts/from_text.py` | 纯文本/Markdown 转 DOCX。 |
| `scripts/analyzer.py` | 格式诊断。 |
| `scripts/converter.py` | Windows `.doc/.wps` 转换辅助。 |

## 注意

- `.docx` 是最稳定的处理格式。
- `.doc/.wps` 需要 Windows、WPS Office 或 Microsoft Word。
- 自动排版前建议保留原文件备份。

## 许可证

MIT
````

## File: requirements-dev.txt
size: 32
sha: da8ea73e0a077cfebdbe5e8763a494eb229e9000
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/requirements-dev.txt

```text
pytest>=7.0
python-docx>=0.8.11
```

## File: requirements.txt
size: 58
sha: c9cff6c3061b5a511682357b15b862f162542f25
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/requirements.txt

```text
python-docx>=0.8.11
pywin32>=305; sys_platform == "win32"
```

## File: tests/test_formatter_regression.py
size: 4698
sha: 7aded4223effc2a1a75776df7d2090e95e924b31
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/tests/test_formatter_regression.py

```text
import tempfile
import zipfile
from copy import deepcopy
from pathlib import Path

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm

from scripts.formatter import PRESETS, add_page_number, detect_para_type, format_document

def _detect_chain(texts, doc_idx_offset=0):
    results = []
    previous = None
    for i, text in enumerate(texts):
        para_type = detect_para_type(
            text=text,
            index=i + doc_idx_offset,
            total=len(texts) + doc_idx_offset,
            alignment=None,
            all_texts=texts,
            all_texts_index=i,
            prev_para_type=previous,
        )
        results.append(para_type)
        previous = para_type
    return results

def _footer_text(footer):
    return "".join(paragraph.text for paragraph in footer.paragraphs)

def test_multiline_title_and_recipient_detection():
    texts = [
        "某某市人民政府办公室",
        "关于印发2026年度重点工作任务清单的",
        "通知",
        "各部门、各单位：",
        "现将有关事项通知如下。",
    ]
    assert _detect_chain(texts) == ["title", "title", "title", "recipient", "body"]

def test_dotted_date_not_misidentified_as_heading():
    texts = [f"第{i}段正文。" for i in range(20)] + [
        "某某市发展和改革委员会",
        "2026.04.20",
    ]
    assert _detect_chain(texts)[-2:] == ["signature", "date"]

def test_official_page_number_outside_spacing_and_offset():
    doc = Document()
    section = doc.sections[0]
    section.bottom_margin = Cm(3.5)

    add_page_number(doc, style="dash", position="outside", offset_from_text_mm=7)

    assert abs(section.footer_distance.cm - 2.8) < 0.02
    assert section.footer.paragraphs[0].alignment == WD_ALIGN_PARAGRAPH.RIGHT
    assert section.even_page_footer.paragraphs[0].alignment == WD_ALIGN_PARAGRAPH.LEFT
    assert _footer_text(section.footer).endswith(" —　")
    assert _footer_text(section.even_page_footer).startswith("　— ")

def test_page_number_styles_and_replacement():
    with tempfile.TemporaryDirectory() as folder:
        source = Path(folder) / "source.docx"
        output = Path(folder) / "output.docx"
        doc = Document()
        doc.add_paragraph("测试正文。")
        add_page_number(doc, style="dash", position="outside")
        doc.save(source)

        custom = deepcopy(PRESETS["official"])
        custom.update({
            "name": "页码测试",
            "page_number_style": "page_text",
            "page_number_position": "center",
            "page_number_size": 12,
            "page_number_offset_mm": 10,
            "replace_existing_page_number": True,
        })
        format_document(str(source), str(output), preset_name="custom", custom_settings=custom)

        result = Document(output)
        section = result.sections[0]
        assert section.footer.paragraphs[0].alignment == WD_ALIGN_PARAGRAPH.CENTER
        assert "第 " in _footer_text(section.footer)
        assert " 页" in _footer_text(section.footer)
        assert abs(section.footer_distance.cm - 2.5) < 0.02

        with zipfile.ZipFile(output) as archive:
            footer_xml = "".join(
                archive.read(name).decode("utf-8")
                for name in archive.namelist()
                if name.startswith("word/footer") and name.endswith(".xml")
            )
        assert footer_xml.count("第 ") == 1
        assert "— " not in footer_xml

def test_non_page_footer_content_is_not_overwritten():
    doc = Document()
    footer = doc.sections[0].footer
    footer.paragraphs[0].text = "内部资料"

    add_page_number(doc, style="plain", replace_existing=True)

    assert footer.paragraphs[0].text == "内部资料"
    assert "PAGE" not in footer._element.xml

def test_format_document_resets_styles_and_strips_autospacing():
    with tempfile.TemporaryDirectory() as folder:
        source = Path(folder) / "source.docx"
        output = Path(folder) / "output.docx"
        doc = Document()
        doc.add_paragraph("一、第一项工作", style="Heading 3")
        doc.add_paragraph("正文段落。")
        doc.add_paragraph("（一）小标题", style="Heading 4")
        doc.save(source)

        format_document(str(source), str(output), preset_name="official")

        result = Document(output)
        for paragraph in result.paragraphs:
            if paragraph.text.strip():
                assert paragraph.style.name == "Normal"

        with zipfile.ZipFile(output) as archive:
            styles_xml = archive.read("word/styles.xml").decode("utf-8")
        assert "Autospacing" not in styles_xml
```

## File: tests/test_punctuation_and_text.py
size: 2020
sha: 247eefc58ab4b82a83fc52573853a96d50037c3f
upstream: https://github.com/kagurananaga/document-format-skills/blob/HEAD/tests/test_punctuation_and_text.py

```text
import tempfile
from pathlib import Path

from docx import Document

from scripts.from_text import create_docx_from_markdown, detect_markdown
from scripts.punctuation import _process_spaces_text, fix_text, process_paragraph

def test_punctuation_protects_special_patterns():
    text = "会议时间:上午9:30至下午14:30,请发送至 report@gov.cn,参照 ISO 9001:2015 执行."
    fixed = fix_text(text)
    assert "9:30" in fixed
    assert "14:30" in fixed
    assert "report@gov.cn" in fixed
    assert "ISO 9001:2015" in fixed
    assert "会议时间：" in fixed
    assert "执行。" in fixed

def test_space_modes():
    assert _process_spaces_text("中 文 A测 试 1项", "remove_all") == "中文A测试1项"
    assert _process_spaces_text("中 文 A测 试 1项", "keep_en_boundary") == "中文 A 测试 1 项"
    assert _process_spaces_text("中 文 A测 试 1项", "keep_all") == "中 文 A测 试 1项"

def test_process_paragraph_preserves_run_count_for_same_length_changes():
    doc = Document()
    paragraph = doc.add_paragraph()
    paragraph.add_run("他说")
    paragraph.add_run('"好"')

    assert process_paragraph(paragraph, space_mode="keep_all")
    assert paragraph.text == "他说“好”"
    assert len(paragraph.runs) == 2

def test_markdown_generation_maps_headings():
    markdown = """# 主标题

## 工作背景
正文内容。

### 总体情况
**重点**内容。
"""
    assert detect_markdown(markdown)
    assert detect_markdown("﻿" + markdown.lstrip())

    with tempfile.TemporaryDirectory() as folder:
        output = Path(folder) / "out.docx"
        create_docx_from_markdown("备用标题", markdown, output)
        doc = Document(output)

    texts = [paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()]
    assert texts[0] == "主标题"
    assert texts[1] == "一、工作背景"
    assert texts[3] == "（一）总体情况"
    assert texts[4] == "重点内容。"
    assert doc.paragraphs[4].runs[0].font.bold is True
```
