dsh-docx-format 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/docxfmt.py ADDED
@@ -0,0 +1,1859 @@
1
+ # -*- coding: utf-8 -*-
2
+ """docxfmt.py — 通用公文格式规范化引擎 (dsh-docx-format)
3
+
4
+ 用法:
5
+ python docxfmt.py <file.docx|dir> [--mode apply|check] [--recursive] [--json] [--print] [--config '<json>']
6
+ 模式:
7
+ apply 规范化并写回(原子替换)
8
+ check 只检查不修改,输出违规项
9
+ 退出码: 0 成功;1 参数/运行错误;2 check 模式下存在违规。
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import base64
15
+ import copy
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import time
24
+ from collections import Counter
25
+
26
+ try:
27
+ from docx import Document
28
+ from docx.enum.table import WD_TABLE_ALIGNMENT
29
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
30
+ from docx.oxml import OxmlElement
31
+ from docx.oxml.ns import qn
32
+ from docx.shared import Cm, Pt
33
+ from docx.table import Table
34
+ from docx.text.paragraph import Paragraph
35
+ except Exception as exc: # pragma: no cover
36
+ print(json.dumps({"ok": False, "error": "python-docx 不可用: %s" % exc}, ensure_ascii=False))
37
+ sys.exit(1)
38
+
39
+ CENTER = WD_ALIGN_PARAGRAPH.CENTER
40
+ RIGHT = WD_ALIGN_PARAGRAPH.RIGHT
41
+ JUSTIFY = WD_ALIGN_PARAGRAPH.JUSTIFY
42
+
43
+ DEFAULTS = {
44
+ "fonts": {
45
+ "title": "方正小标宋简体",
46
+ "body": "仿宋",
47
+ "h1": "黑体",
48
+ "h2": "楷体",
49
+ "h3": "仿宋",
50
+ "latin": "Times New Roman",
51
+ "footer": "宋体",
52
+ "tableHead": "黑体",
53
+ "tableBody": "仿宋",
54
+ "tableCaption": "方正小标宋简体",
55
+ },
56
+ "sizes": {"title": 22, "body": 16, "table": 12, "footer": 14, "spacer": 10.5},
57
+ "linePt": 29,
58
+ # 首行缩进以“字符”为单位(w:firstLineChars),不用磅值
59
+ "indentChars": 2,
60
+ # 附件:左/右/悬挂缩进一律 0,只用“首行缩进”这一种特殊缩进。
61
+ # attach_line 「附件:1.……」 首行 2 字符
62
+ # attach_cont 「2.……」 首行 5 字符(= 3 字“附件:”+ 2 字“1.”)
63
+ # attach_wrap 手工换行出来的续行 首行 6 字符
64
+ "attachLineIndentChars": 2,
65
+ "attachContIndentChars": 5,
66
+ "attachWrapIndentChars": 6,
67
+ # 附件条目超出一行时,用 Word/WPS 实测折行点,把视觉行拆成真实段落(续行 6 字符)。
68
+ # 拿不到排版引擎就只设首行缩进,不拆段(由用户手工换行)。
69
+ "attachSplit": {"enabled": True, "mode": "word", "maxRounds": 12,
70
+ "minCharsToMeasure": 20},
71
+ # 所有段落段前/段后一律 0 磅;空行用独立空段落(整行)表达
72
+ "spaceBeforePt": 0,
73
+ "spaceAfterPt": 0,
74
+ "marginsCm": {"top": 3.6, "bottom": 3.0, "left": 2.7, "right": 2.7},
75
+ "titleBlankBeforeLines": 2,
76
+ "titleBlankAfterLines": 1,
77
+ "attachBlankBeforeLines": 1,
78
+ "attachBlankAfterLines": 2,
79
+ # 文件中的“附件1”标记:下与附件标题空出一行(参考要求未规定其上要空行)
80
+ "attachTagBlankAfterLines": 1,
81
+ "tableBordersPt": {"outer": 1.5, "inner": 0.5},
82
+ "rowHeightCm": 0.7,
83
+ "pageNumber": True,
84
+ # enabled=False:完全不处理落款(不右对齐、不加空行、不补空格)。
85
+ # 默认 True 只格式化文档里【已有】的落款,绝不新增;“默认不写落款”由提示词层
86
+ # 控制(未明确要求署名/日期时不生成落款文字)。
87
+ "signature": {"enabled": True, "seal": False, "datePadSpaces": 2,
88
+ "blankLinesBefore": 2},
89
+ # 正文命中这些关键词时整篇跳过(白名单),如“实验报告”
90
+ "skipContentKeywords": ["实验报告"],
91
+ "normalize": {
92
+ "stripLeadingSpace": True,
93
+ "fullwidthNumberDot": True,
94
+ "twoCharCellSpace": True,
95
+ "dashFont": True,
96
+ "boldOff": True,
97
+ # 中文内容里英文前后不留空格(「使用AI工具」);纯英文语句的空格保持原样
98
+ "cjkLatinSpace": True,
99
+ },
100
+ }
101
+
102
+ RE_H1 = re.compile(r"^[ \u3000]*[一二三四五六七八九十百]{1,4}、")
103
+ RE_H2 = re.compile(r"^[ \u3000]*[((][一二三四五六七八九十百]{1,4}[))]")
104
+ RE_H3 = re.compile(r"^[ \u3000]*\d{1,2}\s*[..、](?!\d)")
105
+ RE_ATTACH_TAG = re.compile(r"^[ \u3000]*附件\s*\d{0,2}\s*$")
106
+ RE_ATTACH_LINE = re.compile(r"^[ \u3000]*附件\s*[::]")
107
+ RE_ATTACH_ITEM = re.compile(r"^[((]?\d{1,2}\s*[..、))]")
108
+ RE_DATE = re.compile(r"\d{4}\s*年\s*\d{1,2}\s*月\s*\d{1,2}\s*日")
109
+ RE_LEAD_SPACE = re.compile(r"^[\u3000 ]+")
110
+ RE_FULLWIDTH_SPACE = "\u3000"
111
+
112
+
113
+ # ---------------------------------------------------------------- 工具函数
114
+ def ename(value):
115
+ if value is None:
116
+ return None
117
+ return getattr(value, "name", None) or str(value)
118
+
119
+
120
+ def pt_of(length):
121
+ if length is None:
122
+ return None
123
+ try:
124
+ return round(length.pt, 2)
125
+ except Exception:
126
+ return None
127
+
128
+
129
+ def text_width(s):
130
+ """按全角字符数估算显示宽度(半角记 0.5)。"""
131
+ w = 0.0
132
+ for ch in s:
133
+ w += 0.5 if ord(ch) < 0x2000 else 1.0
134
+ return w
135
+
136
+
137
+ def is_cjk(ch):
138
+ return "\u4e00" <= ch <= "\u9fff"
139
+
140
+
141
+ def merge_config(user):
142
+ cfg = copy.deepcopy(DEFAULTS)
143
+ if not user:
144
+ return cfg
145
+ for k, v in user.items():
146
+ if isinstance(v, dict) and isinstance(cfg.get(k), dict):
147
+ cfg[k].update(v)
148
+ else:
149
+ cfg[k] = v
150
+ return cfg
151
+
152
+
153
+ # ---------------------------------------------------------------- 报告收集
154
+ class Report:
155
+ def __init__(self, path, mode, fix):
156
+ self.path = path
157
+ self.mode = mode
158
+ self.fix = fix
159
+ self.rules = {} # rule -> {"count":int,"samples":[...]}
160
+ self.warnings = []
161
+ self.stats = Counter()
162
+ self.total = 0
163
+
164
+ def want(self, rule, where, current, expected, apply_fn=None):
165
+ """记录一处偏差;fix 模式下调用 apply_fn。返回是否命中偏差。"""
166
+ if current == expected:
167
+ return False
168
+ self.total += 1
169
+ entry = self.rules.setdefault(rule, {"count": 0, "samples": []})
170
+ entry["count"] += 1
171
+ if len(entry["samples"]) < 3:
172
+ entry["samples"].append(
173
+ {"where": where, "current": _s(current), "expected": _s(expected)}
174
+ )
175
+ if self.fix and apply_fn is not None:
176
+ apply_fn()
177
+ return True
178
+
179
+ def warn(self, msg):
180
+ if msg not in self.warnings:
181
+ self.warnings.append(msg)
182
+
183
+ def as_dict(self, changed):
184
+ return {
185
+ "ok": True,
186
+ "file": self.path,
187
+ "mode": self.mode,
188
+ "changed": bool(changed),
189
+ "violations": self.total,
190
+ "rules": self.rules,
191
+ "stats": dict(self.stats),
192
+ "warnings": self.warnings,
193
+ }
194
+
195
+
196
+ def _s(v):
197
+ if v is None:
198
+ return "无"
199
+ if isinstance(v, bool):
200
+ return "是" if v else "否"
201
+ return str(v)
202
+
203
+
204
+ # ---------------------------------------------------------------- 字体/段落
205
+ def set_run(run, font, size, latin, report, where, cfg):
206
+ if run.text is None or run.text == "":
207
+ if run._element.findall(".//" + qn("w:drawing")):
208
+ pass
209
+ f = run.font
210
+ rPr = run._element.get_or_add_rPr()
211
+
212
+ if cfg["normalize"]["boldOff"]:
213
+ if f.bold:
214
+ report.want("run.bold", where, "加粗", "常规",
215
+ lambda: setattr(f, "bold", None))
216
+ cur_ascii = f.name
217
+ if cur_ascii != latin:
218
+ report.want("run.font.latin", where, cur_ascii, latin,
219
+ lambda: setattr(f, "name", latin))
220
+ if rPr.find(qn("w:rFonts")) is None:
221
+ f.name = latin
222
+ rFonts = rPr.find(qn("w:rFonts"))
223
+ cur_ea = rFonts.get(qn("w:eastAsia"))
224
+ if cur_ea != font:
225
+ report.want("run.font.eastAsia", where, cur_ea, font,
226
+ lambda: rFonts.set(qn("w:eastAsia"), font))
227
+ cur_sz = pt_of(f.size)
228
+ if cur_sz != size:
229
+ report.want("run.font.size", where, cur_sz, size,
230
+ lambda: setattr(f, "size", Pt(size)))
231
+ if f.highlight_color is not None:
232
+ report.want("run.highlight", where, ename(f.highlight_color), "无",
233
+ lambda: setattr(f, "highlight_color", None))
234
+
235
+
236
+ def style_runs(par, font, size, latin, report, label, cfg):
237
+ for idx, run in enumerate(par.runs):
238
+ where = "%s#r%d" % (label, idx)
239
+ if (cfg["normalize"]["dashFont"] and run.text
240
+ and set(run.text) <= {"—", "-"} and run.text.strip()):
241
+ # 破折号用 Times New Roman
242
+ set_run(run, latin, size, latin, report, where, cfg)
243
+ else:
244
+ set_run(run, font, size, latin, report, where, cfg)
245
+
246
+
247
+ # ---------------------------------------------------------------- 缩进(字符单位)
248
+ # python-docx 没有 firstLineChars / leftChars 的 API,直接写 OOXML 属性。
249
+ # Word 优先使用 *Chars 属性(1/100 字符),*FirstLine/*Left 仅作兼容回退值。
250
+ IND_SUCCESSORS = ("w:contextualSpacing", "w:mirrorIndents", "w:suppressOverlap", "w:jc",
251
+ "w:textDirection", "w:textAlignment", "w:textboxTightWrap", "w:outlineLvl",
252
+ "w:divId", "w:cnfStyle", "w:rPr", "w:sectPr", "w:pPrChange")
253
+
254
+ IND_CHAR_ATTRS = ("w:firstLineChars", "w:leftChars", "w:rightChars",
255
+ "w:hangingChars", "w:hanging")
256
+
257
+ # w:autoSpaceDE / autoSpaceDN 的 schema 后继元素(必须插在它们之前)
258
+ AUTOSPACE_SUCCESSORS = ("w:bidi", "w:adjustRightInd", "w:snapToGrid", "w:spacing",
259
+ "w:ind", "w:contextualSpacing", "w:mirrorIndents",
260
+ "w:suppressOverlap", "w:jc", "w:textDirection",
261
+ "w:textAlignment", "w:textboxTightWrap", "w:outlineLvl",
262
+ "w:divId", "w:cnfStyle", "w:rPr", "w:sectPr", "w:pPrChange")
263
+
264
+ # 空段落有两种:正文侧(沿用仿宋三号正文格式)与标题侧(沿用方正小标宋二号居中)
265
+ BLANK_KINDS = ("blank", "blank_title")
266
+
267
+
268
+ def _mark_rpr(par, make=False):
269
+ """段落标记的 w:pPr/w:rPr(空段落的“字体”就存在这里)。"""
270
+ pPr = par._p.pPr
271
+ if pPr is None:
272
+ if not make:
273
+ return None
274
+ pPr = par._p.get_or_add_pPr()
275
+ rPr = pPr.find(qn("w:rPr"))
276
+ if rPr is None and make:
277
+ rPr = OxmlElement("w:rPr")
278
+ pPr.append(rPr) # w:rPr 是 pPr 的最后一个子元素
279
+ return rPr
280
+
281
+
282
+ def _mark_font(par):
283
+ """读段落标记的 (东亚字体, 字号磅);未显式设置则为 None(继承样式)。"""
284
+ rPr = _mark_rpr(par)
285
+ if rPr is None:
286
+ return None, None
287
+ font = None
288
+ rf = rPr.find(qn("w:rFonts"))
289
+ if rf is not None:
290
+ font = rf.get(qn("w:eastAsia")) or rf.get(qn("w:ascii"))
291
+ size = None
292
+ sz = rPr.find(qn("w:sz"))
293
+ if sz is not None:
294
+ try:
295
+ size = int(sz.get(qn("w:val"))) / 2.0
296
+ except (TypeError, ValueError):
297
+ size = None
298
+ return font, size
299
+
300
+
301
+ def _write_mark_font(par, font, size_pt, latin):
302
+ """写段落标记的字体字号:手工回车时 Word 也是把字体记在段落标记上。"""
303
+ rPr = _mark_rpr(par, make=True)
304
+ rf = rPr.find(qn("w:rFonts"))
305
+ if rf is None:
306
+ rf = OxmlElement("w:rFonts")
307
+ rPr.insert(0, rf)
308
+ rf.set(qn("w:ascii"), latin)
309
+ rf.set(qn("w:hAnsi"), latin)
310
+ rf.set(qn("w:eastAsia"), font)
311
+ rf.set(qn("w:cs"), latin)
312
+ val = str(int(round(float(size_pt) * 2)))
313
+ for tag in ("w:sz", "w:szCs"):
314
+ el = rPr.find(qn(tag))
315
+ if el is None:
316
+ el = OxmlElement(tag)
317
+ rPr.append(el)
318
+ el.set(qn("w:val"), val)
319
+
320
+
321
+ def _get_ind(par, make=False):
322
+ pPr = par._p.pPr
323
+ if pPr is None:
324
+ if not make:
325
+ return None
326
+ pPr = par._p.get_or_add_pPr()
327
+ ind = pPr.find(qn("w:ind"))
328
+ if ind is None and make:
329
+ ind = OxmlElement("w:ind")
330
+ try:
331
+ pPr.insert_element_before(ind, *IND_SUCCESSORS)
332
+ except Exception:
333
+ pPr.append(ind)
334
+ return ind
335
+
336
+
337
+ def _get_chars(par, attr):
338
+ ind = _get_ind(par)
339
+ if ind is None:
340
+ return None
341
+ raw = ind.get(qn(attr))
342
+ if raw is None or raw == "":
343
+ return None
344
+ try:
345
+ return int(round(int(raw))) / 100.0
346
+ except ValueError:
347
+ return None
348
+
349
+
350
+ def set_chars_indent(par, attr, chars, fallback_pt):
351
+ """把 *Chars 缩进写入 w:ind(chars 为 None 时清除该属性)。"""
352
+ ind = _get_ind(par, make=True)
353
+ char_attr = qn("w:" + attr + "Chars")
354
+ pt_attr = qn("w:" + attr)
355
+ other = {
356
+ "firstLine": "hanging",
357
+ "left": "leftChars",
358
+ "right": "rightChars",
359
+ }.get(attr)
360
+ if chars is None or chars == 0:
361
+ for key in (char_attr, pt_attr):
362
+ if ind.get(key) is not None:
363
+ del ind.attrib[key]
364
+ else:
365
+ ind.set(char_attr, str(int(round(chars * 100))))
366
+ ind.set(pt_attr, str(int(round(fallback_pt.twips))))
367
+ if attr == "firstLine":
368
+ # 首行缩进与悬挂互斥:写首行就清悬挂
369
+ for key in (qn("w:hangingChars"), qn("w:hanging")):
370
+ if ind.get(key) is not None:
371
+ del ind.attrib[key]
372
+ elif attr == "hanging" and chars:
373
+ for key in (qn("w:firstLineChars"), qn("w:firstLine")):
374
+ if ind.get(key) is not None:
375
+ del ind.attrib[key]
376
+
377
+
378
+ def clear_side_indent(par):
379
+ """清掉左/右/悬挂缩进(字符与磅两套属性),保留首行缩进。
380
+
381
+ 公文里唯一允许的缩进是“首行缩进”,左右缩进与悬挂缩进一律 0。
382
+ """
383
+ ind = _get_ind(par)
384
+ if ind is None:
385
+ return
386
+ for key in ("w:leftChars", "w:left", "w:rightChars", "w:right",
387
+ "w:hangingChars", "w:hanging"):
388
+ if ind.get(qn(key)) is not None:
389
+ del ind.attrib[qn(key)]
390
+
391
+
392
+ def _has_side(chars, pt):
393
+ """侧边缩进是否非 0(字符或磅任一表达)。"""
394
+ if chars:
395
+ return abs(chars) > 0.01
396
+ return pt is not None and abs(pt) > 0.5
397
+
398
+
399
+ def _side_desc(chars, pt):
400
+ """侧边缩进的当前值描述;0 与“无”统一写成 0,避免误判偏差。"""
401
+ if chars:
402
+ return "%.2f 字符" % chars
403
+ if pt is not None and abs(pt) > 0.5:
404
+ return "%.1f 磅" % pt
405
+ return "0"
406
+
407
+
408
+ def _get_pt(ind, attr):
409
+ """读 w:left / w:hanging 的磅值(twips / 20)。"""
410
+ if ind is None:
411
+ return None
412
+ raw = ind.get(qn(attr))
413
+ if raw in (None, ""):
414
+ return None
415
+ try:
416
+ return int(raw) / 20.0
417
+ except ValueError:
418
+ return None
419
+
420
+
421
+ def _style_blank(par, cfg, kind="blank"):
422
+ """空行 = 独立空段落,但格式要与“手工回车”的结果一致:
423
+
424
+ - 标题上/下那几行沿用标题格式:方正小标宋简体二号、居中、无首行缩进;
425
+ - 其余空行沿用正文格式:仿宋三号、两端对齐、首行缩进 2 字符。
426
+
427
+ 段落标记(w:pPr/w:rPr)就是 Word 存“空段落字体”的地方,所以字体字号写在那里。
428
+ """
429
+ title_side = kind == "blank_title"
430
+ pf = par.paragraph_format
431
+ pf.line_spacing_rule = WD_LINE_SPACING.EXACTLY
432
+ pf.line_spacing = Pt(cfg["linePt"])
433
+ _write_zero_spacing(par)
434
+ pf.alignment = CENTER if title_side else JUSTIFY
435
+ font = cfg["fonts"]["title"] if title_side else cfg["fonts"]["body"]
436
+ size = cfg["sizes"]["title"] if title_side else cfg["sizes"]["body"]
437
+ _write_mark_font(par, font, size, cfg["fonts"]["latin"])
438
+ chars = 0.0 if title_side else float(cfg["indentChars"])
439
+ set_chars_indent(par, "firstLine", chars, Pt(chars * float(cfg["sizes"]["body"])))
440
+ set_chars_indent(par, "left", None, Pt(0))
441
+ set_chars_indent(par, "right", None, Pt(0))
442
+
443
+
444
+ def style_par(par, kind, report, label, cfg):
445
+ pf = par.paragraph_format
446
+ fonts = cfg["fonts"]
447
+ sizes = cfg["sizes"]
448
+ line = Pt(cfg["linePt"])
449
+ body_pt = Pt(sizes["body"])
450
+ indent_chars = float(cfg["indentChars"]) # 首行缩进 2 字符
451
+
452
+ if kind in BLANK_KINDS:
453
+ report.stats["para.blank"] += 1
454
+ title_side = kind == "blank_title"
455
+ b_font = fonts["title"] if title_side else fonts["body"]
456
+ b_size = float(sizes["title"] if title_side else sizes["body"])
457
+ b_align = CENTER if title_side else JUSTIFY
458
+ b_chars = 0.0 if title_side else indent_chars
459
+ if pf.line_spacing_rule != WD_LINE_SPACING.EXACTLY or pt_of(pf.line_spacing) != float(cfg["linePt"]):
460
+ report.want("blank.lineSpacing", label, pt_of(pf.line_spacing), float(cfg["linePt"]),
461
+ (lambda: (setattr(pf, "line_spacing_rule", WD_LINE_SPACING.EXACTLY),
462
+ setattr(pf, "line_spacing", line))))
463
+ _zero_spacing(par, pf, report, label, cfg)
464
+ # 空段落也要像手工回车那样带着前后文的字体、字号、对齐与首行缩进
465
+ cur_font, cur_size = _mark_font(par)
466
+ cur_chars = _get_chars(par, "w:firstLineChars")
467
+ drift = []
468
+ if cur_font != b_font:
469
+ drift.append("字体 %s" % (cur_font or "继承样式"))
470
+ if cur_size is None or abs(cur_size - b_size) > 0.01:
471
+ drift.append("字号 %s" % ("继承样式" if cur_size is None else "%g 磅" % cur_size))
472
+ if pf.alignment != b_align:
473
+ drift.append("对齐 %s" % ("居中" if pf.alignment == CENTER
474
+ else "两端对齐" if pf.alignment == JUSTIFY
475
+ else ("左对齐" if pf.alignment is None
476
+ else str(pf.alignment))))
477
+ if abs((cur_chars or 0.0) - b_chars) > 0.01:
478
+ drift.append("首行缩进 %.2f 字符" % (cur_chars or 0.0))
479
+ if drift:
480
+ report.want("blank.mark", label, "、".join(drift),
481
+ "%s %g 磅、%s、首行缩进 %g 字符"
482
+ % (b_font, b_size,
483
+ "居中" if title_side else "两端对齐", b_chars),
484
+ (lambda p=par, k=kind: _style_blank(p, cfg, k)))
485
+ _clear_indent_chars(par, report, label, kind, b_chars)
486
+ return
487
+
488
+ if kind == "caption_spacer":
489
+ report.stats["para.blank"] += 1
490
+ if not _spacer_props_ok(par._p, cfg):
491
+ report.want("table.captionSpacer", label, "空行行高/字号不符",
492
+ "行高最小值 0 磅、5 号字",
493
+ lambda: _write_spacer_props(par._p, cfg))
494
+ return
495
+
496
+ want_align = None
497
+ want_font = fonts["body"]
498
+ want_size = sizes["body"]
499
+ want_first_chars = indent_chars
500
+ want_left_chars = 0.0
501
+ want_hang_chars = 0.0
502
+ want_line_single = False # 图片行用单倍行距,不套 29 磅固定值
503
+
504
+ if kind in ("title", "title_first", "title_mid", "title_last", "title_only"):
505
+ want_align, want_font, want_size = CENTER, fonts["title"], sizes["title"]
506
+ want_first_chars = None
507
+ elif kind == "table_caption":
508
+ want_align, want_font, want_size = CENTER, fonts["tableCaption"], sizes["title"]
509
+ want_first_chars = None
510
+ elif kind == "h1":
511
+ want_font = fonts["h1"]
512
+ elif kind == "h2":
513
+ want_font = fonts["h2"]
514
+ elif kind == "h3":
515
+ want_font = fonts["h3"]
516
+ elif kind == "attach_tag":
517
+ want_align, want_font, want_first_chars = JUSTIFY, fonts["h1"], None
518
+ elif kind == "attach_line":
519
+ # 「附件:1.……」:左/右/悬挂全 0,只有首行缩进 2 字符
520
+ want_align = JUSTIFY
521
+ want_first_chars = float(cfg["attachLineIndentChars"])
522
+ elif kind == "attach_cont":
523
+ # 多附件的“2.……”:首行缩进 5 字符,与冒号后序号同一竖线
524
+ want_align = JUSTIFY
525
+ want_first_chars = float(cfg["attachContIndentChars"])
526
+ elif kind == "attach_wrap":
527
+ # 手工换行出来的续行:首行缩进 6 字符
528
+ want_align = JUSTIFY
529
+ want_first_chars = float(cfg["attachWrapIndentChars"])
530
+ elif kind == "sign_org":
531
+ if cfg["signature"]["enabled"]:
532
+ want_align, want_first_chars = RIGHT, None
533
+ else:
534
+ want_align, want_first_chars = None, None # 不写落款:不改造版式
535
+ elif kind == "sign_date":
536
+ if cfg["signature"]["enabled"]:
537
+ want_align, want_first_chars = RIGHT, None
538
+ else:
539
+ want_align, want_first_chars = None, None
540
+ elif kind == "image":
541
+ # 图片所在行:居中、无缩进(首行/左右/悬挂全 0)、单倍行距
542
+ want_align, want_first_chars = CENTER, None
543
+ want_line_single = True
544
+ else:
545
+ want_align = JUSTIFY
546
+
547
+ report.stats["para." + kind] += 1
548
+
549
+ def do_align():
550
+ pf.alignment = want_align
551
+
552
+ if want_align is None:
553
+ if pf.alignment is not None:
554
+ report.want("par.alignment", label, ename(pf.alignment), "无",
555
+ lambda: setattr(pf, "alignment", None))
556
+ else:
557
+ report.want("par.alignment", label, ename(pf.alignment), ename(want_align), do_align)
558
+
559
+ if want_line_single:
560
+ _check_single_line(par, pf, report, label)
561
+ else:
562
+ cur_rule = ename(pf.line_spacing_rule)
563
+ if pf.line_spacing_rule != WD_LINE_SPACING.EXACTLY:
564
+ report.want("par.lineRule", label, cur_rule, "EXACTLY",
565
+ lambda: setattr(pf, "line_spacing_rule", WD_LINE_SPACING.EXACTLY))
566
+ if pt_of(pf.line_spacing) != float(cfg["linePt"]):
567
+ report.want("par.lineSpacing", label, pt_of(pf.line_spacing), float(cfg["linePt"]),
568
+ lambda: setattr(pf, "line_spacing", line))
569
+
570
+ # 首行缩进:以字符为单位(w:firstLineChars=200 → 2 字符)
571
+ cur_chars = _get_chars(par, "w:firstLineChars")
572
+ if want_first_chars is None:
573
+ if cur_chars is not None:
574
+ report.want("par.firstLineChars", label, "%.2f 字符" % cur_chars, "无",
575
+ (lambda p=par: set_chars_indent(p, "firstLine", None, body_pt)))
576
+ if not want_hang_chars and pf.first_line_indent is not None \
577
+ and abs(pt_of(pf.first_line_indent) or 0) > 1:
578
+ # 悬挂缩进时 python-docx 会把 w:hanging 读成负的 first_line_indent,
579
+ # 那种情况由下面的 hanging 分支管,这里不能判它违规。
580
+ report.want("par.firstLineIndent", label, pt_of(pf.first_line_indent), "无",
581
+ (lambda p=par: set_chars_indent(p, "firstLine", None, body_pt)))
582
+ else:
583
+ if cur_chars is None or abs(cur_chars - want_first_chars) > 0.01:
584
+ report.want("par.firstLineChars", label,
585
+ "无(%.1f 磅)" % (pt_of(pf.first_line_indent) or 0) if cur_chars is None
586
+ else "%.2f 字符" % cur_chars,
587
+ "%.2f 字符" % want_first_chars,
588
+ (lambda p=par, c=want_first_chars, b=body_pt:
589
+ set_chars_indent(p, "firstLine", c, Pt(c * b.pt))))
590
+
591
+ # 侧边缩进(左 / 右 / 悬挂)一律 0:可用的“特殊缩进”只有首行缩进
592
+ ind = _get_ind(par)
593
+ cur_left_chars = _get_chars(par, "w:leftChars")
594
+ cur_left_pt = _get_pt(ind, "w:left")
595
+ cur_hang_chars = _get_chars(par, "w:hangingChars")
596
+ cur_hang_pt = _get_pt(ind, "w:hanging")
597
+
598
+ if want_left_chars:
599
+ if (cur_left_chars is None or abs(cur_left_chars - want_left_chars) > 0.01
600
+ or _has_side(None, cur_left_pt)):
601
+ report.want("par.leftChars", label, _side_desc(cur_left_chars, cur_left_pt),
602
+ "%.2f 字符" % want_left_chars,
603
+ (lambda p=par, c=want_left_chars, b=body_pt:
604
+ set_chars_indent(p, "left", c, Pt(c * b.pt))))
605
+ elif _has_side(cur_left_chars, cur_left_pt):
606
+ report.want("par.leftIndent", label, _side_desc(cur_left_chars, cur_left_pt), "0",
607
+ (lambda p=par: clear_side_indent(p)))
608
+
609
+ if want_hang_chars:
610
+ if (cur_hang_chars is None or abs(cur_hang_chars - want_hang_chars) > 0.01
611
+ or _has_side(None, cur_hang_pt)):
612
+ report.want("par.hangingChars", label, _side_desc(cur_hang_chars, cur_hang_pt),
613
+ "%.2f 字符" % want_hang_chars,
614
+ (lambda p=par, c=want_hang_chars, b=body_pt:
615
+ set_chars_indent(p, "hanging", c, Pt(c * b.pt))))
616
+ elif _has_side(cur_hang_chars, cur_hang_pt):
617
+ report.want("par.hangingIndent", label, _side_desc(cur_hang_chars, cur_hang_pt), "0",
618
+ (lambda p=par: clear_side_indent(p)))
619
+
620
+ _zero_spacing(par, pf, report, label, cfg)
621
+
622
+ cur_right = pt_of(pf.right_indent) or 0
623
+ if abs(cur_right) > 1:
624
+ report.want("par.rightIndent", label, cur_right, 0,
625
+ (lambda: setattr(pf, "right_indent", None)))
626
+
627
+ # 中英文之间不留自动间距(否则没有空格字符也看着像有空格)
628
+ auto_space_off(par, report, label)
629
+
630
+ if par.runs:
631
+ style_runs(par, want_font, want_size, fonts["latin"], report, label, cfg)
632
+
633
+
634
+ def _spacing_elm(par):
635
+ pPr = par._p.find(qn("w:pPr"))
636
+ return None if pPr is None else pPr.find(qn("w:spacing"))
637
+
638
+
639
+ def _is_single_line(par):
640
+ """w:line="240" + w:lineRule="auto"(或缺省 lineRule)即标准单倍行距。"""
641
+ sp = _spacing_elm(par)
642
+ if sp is None or sp.get(qn("w:line")) != "240":
643
+ return False
644
+ return (sp.get(qn("w:lineRule")) or "auto") == "auto"
645
+
646
+
647
+ def _write_single_line(par):
648
+ pPr = par._p.get_or_add_pPr()
649
+ sp = pPr.get_or_add_spacing()
650
+ sp.set(qn("w:line"), "240")
651
+ sp.set(qn("w:lineRule"), "auto")
652
+
653
+
654
+ def _check_single_line(par, pf, report, label):
655
+ """图片行:要求单倍行距(w:line=240 lineRule=auto),不套 29 磅固定值。"""
656
+ if _is_single_line(par):
657
+ return
658
+ sp = _spacing_elm(par)
659
+ raw = None if sp is None else sp.get(qn("w:line"))
660
+ if raw is None:
661
+ cur = "继承样式"
662
+ else:
663
+ try:
664
+ val = float(raw)
665
+ except (TypeError, ValueError):
666
+ val = 0.0
667
+ rule = sp.get(qn("w:lineRule")) or "auto"
668
+ if rule == "exact":
669
+ cur = "%g 磅(固定)" % round(val / 20.0, 1)
670
+ elif rule == "atLeast":
671
+ cur = "%g 磅(最小值)" % round(val / 20.0, 1)
672
+ else:
673
+ cur = "%g 倍" % round(val / 240.0, 2)
674
+ report.want("par.lineSingle", label, cur, "单倍行距",
675
+ lambda: _write_single_line(par))
676
+
677
+
678
+ def _write_zero_spacing(par):
679
+ """把段前/段后显式写成 0 磅,并清掉“行”单位与自动间距。
680
+
681
+ 只把 w:before / w:after 删掉是不行的:Word 会继续继承 docDefaults 或
682
+ Normal 样式里的段后间距(常见 w:after="200" = 10 磅),用户看到的就是
683
+ “段前段后不是 0 磅”。
684
+ """
685
+ pPr = par._p.get_or_add_pPr()
686
+ sp = pPr.get_or_add_spacing()
687
+ for key in ("w:beforeLines", "w:afterLines",
688
+ "w:beforeAutospacing", "w:afterAutospacing"):
689
+ sp.attrib.pop(qn(key), None)
690
+ sp.set(qn("w:before"), "0")
691
+ sp.set(qn("w:after"), "0")
692
+
693
+
694
+ def _zero_spacing(par, pf, report, label, cfg):
695
+ """段前/段后一律 0 磅:间距由独立空段落表达,不用段前段后。"""
696
+ pPr = par._p.get_or_add_pPr()
697
+ sp = pPr.find(qn("w:spacing"))
698
+ need = sp is None
699
+ if sp is not None:
700
+ for key in ("w:before", "w:after"):
701
+ if (sp.get(qn(key)) or "") != "0":
702
+ need = True
703
+ for key in ("w:beforeLines", "w:afterLines",
704
+ "w:beforeAutospacing", "w:afterAutospacing"):
705
+ if sp.get(qn(key)) is not None:
706
+ need = True
707
+ if need:
708
+ report.want("par.spaceZero", label, "非 0 磅或继承样式", "0 磅",
709
+ lambda: _write_zero_spacing(par))
710
+
711
+
712
+ def _clear_indent_chars(par, report, label, kind, first_chars=0.0):
713
+ """清掉不该有的字符缩进;*first_chars* 是本 kind 期望的首行缩进(默认 0)。"""
714
+ for attr, name in (("firstLine", "firstLineChars"), ("left", "leftChars"),
715
+ ("right", "rightChars")):
716
+ cur = _get_chars(par, "w:" + name)
717
+ if cur is None:
718
+ continue
719
+ if attr == "firstLine" and abs(cur - float(first_chars)) <= 0.01:
720
+ continue
721
+ report.want("par." + name, label, "%.2f 字符" % cur, "无",
722
+ (lambda p=par, a=attr: set_chars_indent(p, a, None, Pt(0))))
723
+ cur_hang = _get_chars(par, "w:hangingChars")
724
+ if cur_hang is not None:
725
+ report.want("par.hangingChars", label, "%.2f 字符" % cur_hang, "无",
726
+ (lambda p=par: set_hanging_chars(p, None, Pt(0))))
727
+
728
+
729
+ # ---------------------------------------------------------------- 文本规范化
730
+ CJK_PUNCT = ",。、;:?!“”‘’()【】《》〈〉「」『』…—~· "
731
+ ASCII_LATIN = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
732
+ ASCII_SPACE = " \t\u3000"
733
+
734
+
735
+ def is_cjk_char(ch):
736
+ """汉字或中文标点。"""
737
+ if not ch:
738
+ return False
739
+ if ch in CJK_PUNCT:
740
+ return True
741
+ return "\u4e00" <= ch <= "\u9fff" or "\u3400" <= ch <= "\u4dbf"
742
+
743
+
744
+ def is_latin_char(ch):
745
+ return bool(ch) and ch in ASCII_LATIN
746
+
747
+
748
+ ALNUM_CHARS = ASCII_LATIN + "0123456789"
749
+
750
+
751
+ def _token_bounds(text, pos, step):
752
+ """从 pos 起沿 step 方向吃掉连续的字母数字,返回区间 [start, end)。"""
753
+ i = pos
754
+ while 0 <= i < len(text) and text[i] in ALNUM_CHARS:
755
+ i += step
756
+ return (i + 1, pos + 1) if step < 0 else (pos, i)
757
+
758
+
759
+ def _token_has_latin(text, start, end):
760
+ return any(ch in ASCII_LATIN for ch in text[start:end])
761
+
762
+
763
+ def cjk_latin_gaps(text):
764
+ """中文与英文之间的空白区间 [(start, end)];纯中文/纯数字相邻不返回。
765
+
766
+ 英文按“词”判定:含字母的字母数字串(AI、Word、5G、A4)算英文,
767
+ 纯数字(2026)不算,所以「2026 年」保持不变。
768
+ """
769
+ gaps = []
770
+ i = 0
771
+ n = len(text)
772
+ while i < n:
773
+ if text[i] not in ASCII_SPACE:
774
+ i += 1
775
+ continue
776
+ j = i
777
+ while j < n and text[j] in ASCII_SPACE:
778
+ j += 1
779
+ left_cjk = i > 0 and is_cjk_char(text[i - 1])
780
+ right_cjk = j < n and is_cjk_char(text[j])
781
+ left_latin = right_latin = False
782
+ if i > 0 and text[i - 1] in ALNUM_CHARS:
783
+ s, e = _token_bounds(text, i - 1, -1)
784
+ left_latin = _token_has_latin(text, s, e)
785
+ if j < n and text[j] in ALNUM_CHARS:
786
+ s, e = _token_bounds(text, j, 1)
787
+ right_latin = _token_has_latin(text, s, e)
788
+ if (left_cjk and right_latin) or (left_latin and right_cjk):
789
+ gaps.append((i, j))
790
+ i = j
791
+ return gaps
792
+
793
+
794
+ def drop_char_ranges(runs, gaps):
795
+ """按全局字符位置删除 runs 里对应的字符(空格可能落在任一 run)。"""
796
+ drop = set()
797
+ for start, end in gaps:
798
+ drop.update(range(start, end))
799
+ pos = 0
800
+ for run in runs:
801
+ t = run.text
802
+ if not t:
803
+ continue
804
+ kept = "".join(ch for k, ch in enumerate(t) if (pos + k) not in drop)
805
+ pos += len(t)
806
+ if kept != t:
807
+ run.text = kept
808
+
809
+
810
+ def auto_space_off(par, report, label):
811
+ """关闭 Word 的“自动调整中西文间距”(w:autoSpaceDE / w:autoSpaceDN)。
812
+
813
+ Word 默认会在中英文之间自动塞约 1/4 空格:文本里没有空格字符,
814
+ 渲染出来依然像「使用 AI 工具」。要做到真正的“英文前后不加空格”,
815
+ 必须把这两个开关置 0。
816
+ """
817
+ pPr = par._p.get_or_add_pPr()
818
+ for tag in ("w:autoSpaceDE", "w:autoSpaceDN"):
819
+ el = pPr.find(qn(tag))
820
+ if el is not None and (el.get(qn("w:val")) or "").lower() in ("0", "false", "off"):
821
+ continue
822
+
823
+ def apply(t=tag, e=el, p=pPr):
824
+ node = e
825
+ if node is None:
826
+ node = OxmlElement(t)
827
+ p.insert_element_before(node, *AUTOSPACE_SUCCESSORS)
828
+ node.set(qn("w:val"), "0")
829
+
830
+ report.want("par.autoSpace", label,
831
+ "开启(Word 自动在中英文之间加间距)", "关闭(autoSpaceDE/DN=0)", apply)
832
+
833
+
834
+ def normalize_text(par, report, label, cfg):
835
+ p = par
836
+ text = p.text
837
+ if not text:
838
+ return
839
+ n = cfg["normalize"]
840
+ if n["stripLeadingSpace"] and RE_LEAD_SPACE.match(text):
841
+ stripped = text.lstrip("\u3000 ")
842
+ if stripped and p.runs:
843
+ first = p.runs[0]
844
+ report.want("text.leadingSpace", label, "存在行首空格", "无",
845
+ lambda: setattr(first, "text", first.text.lstrip("\u3000 ")))
846
+ if n["fullwidthNumberDot"]:
847
+ m = re.match(r"^(\s*)(\d{1,2})\.(?!\d)", p.text)
848
+ if m and p.runs:
849
+ runs = p.runs
850
+ for run in runs:
851
+ if "." in run.text and re.match(r"^\s*\d{1,2}\.\D*", run.text):
852
+ new = re.sub(r"^(\s*\d{1,2})\.(?!\d)\s*", "\\1.", run.text)
853
+ if new != run.text:
854
+ report.want("text.numberDot", label, "半角序号点", "全角.",
855
+ (lambda r=run, v=new: setattr(r, "text", v)))
856
+ break
857
+ # 「附件:1. xxx」里的序号点也要全角,且不留空格
858
+ for run in p.runs:
859
+ if "附件" not in run.text:
860
+ continue
861
+ new = re.sub(r"(附件:\s*)(\d{1,2})\s*\.(?!\d)\s*", "\\1\\2.", run.text)
862
+ new = re.sub(r"(附件:\s*)(\d{1,2})\s*.\s+", "\\1\\2.", new)
863
+ if new != run.text:
864
+ report.want("text.attachNumberDot", label, "附件序号半角点/空格", "全角.",
865
+ (lambda r=run, v=new: setattr(r, "text", v)))
866
+ break
867
+ if n.get("cjkLatinSpace", True):
868
+ runs = p.runs
869
+ joined = "".join(r.text for r in runs)
870
+ gaps = cjk_latin_gaps(joined)
871
+ if gaps:
872
+ report.want("text.cjkLatinSpace", label,
873
+ "中文与英文之间夹着空白(共 %d 处)" % len(gaps),
874
+ "中文内英文前后不加空格(如「使用AI工具」)",
875
+ (lambda rs=runs, gs=gaps: drop_char_ranges(rs, gs)))
876
+
877
+
878
+ # ---------------------------------------------------------------- 表格
879
+ BORDER_ORDER = ["top", "left", "bottom", "right", "insideH", "insideV"]
880
+
881
+
882
+ def set_borders(tbl, report, label, cfg):
883
+ """外边框 1.5 磅、内边框 0.5 磅(sz 单位为 1/8 磅)。"""
884
+ tblPr = tbl._element.tblPr
885
+ want_sz = {}
886
+ for edge in BORDER_ORDER:
887
+ kind = "outer" if edge in ("top", "left", "bottom", "right") else "inner"
888
+ want_sz[edge] = str(int(round(cfg["tableBordersPt"][kind] * 8)))
889
+
890
+ cur_el = tblPr.find(qn("w:tblBorders"))
891
+ diffs = []
892
+ for edge in BORDER_ORDER:
893
+ cur = None if cur_el is None else cur_el.find(qn("w:" + edge))
894
+ val = None if cur is None else cur.get(qn("w:val"))
895
+ sz = None if cur is None else cur.get(qn("w:sz"))
896
+ if val in (None, "nil", "none") or sz != want_sz[edge]:
897
+ diffs.append((edge, "%s/%s" % (val, sz), "single/%s" % want_sz[edge]))
898
+ if not diffs:
899
+ return
900
+ def rebuild():
901
+ old = tblPr.find(qn("w:tblBorders"))
902
+ if old is not None:
903
+ tblPr.remove(old)
904
+ el = OxmlElement("w:tblBorders")
905
+ for edge in BORDER_ORDER:
906
+ b = OxmlElement("w:" + edge)
907
+ b.set(qn("w:val"), "single")
908
+ b.set(qn("w:sz"), want_sz[edge])
909
+ b.set(qn("w:space"), "0")
910
+ b.set(qn("w:color"), "auto")
911
+ el.append(b)
912
+ tblPr.insert_element_before(el, "w:shd", "w:tblLayout", "w:tblCellMar",
913
+ "w:tblLook", "w:tblCaption", "w:tblDescription")
914
+ for edge, cur_s, want_s in diffs:
915
+ report.want("table.border." + edge, label, cur_s, want_s, rebuild)
916
+
917
+
918
+ def style_table(tbl, report, label, cfg):
919
+ report.stats["tables"] += 1
920
+ tblPr = tbl._element.tblPr
921
+ jc = tblPr.find(qn("w:jc"))
922
+ if jc is None or jc.get(qn("w:val")) != "center":
923
+ report.want("table.alignment", label, None if jc is None else jc.get(qn("w:val")), "center",
924
+ lambda: (_set_or_make(tblPr, "w:jc", {"w:val": "center"})))
925
+ set_borders(tbl, report, label, cfg)
926
+
927
+ # 表格本体缩进清零,避免 tblInd 把整表推偏导致“看起来没居中”
928
+ tblInd = tblPr.find(qn("w:tblInd"))
929
+ if tblInd is not None and (tblInd.get(qn("w:w")) or "0") != "0":
930
+ report.want("table.indent", label, tblInd.get(qn("w:w")), 0,
931
+ lambda: tblPr.remove(tblInd))
932
+
933
+ fonts, sizes = cfg["fonts"], cfg["sizes"]
934
+ for r_i, row in enumerate(tbl.rows):
935
+ trPr = row._tr.get_or_add_trPr()
936
+ h = trPr.find(qn("w:trHeight"))
937
+ want_twips = str(int(round(Cm(cfg["rowHeightCm"]).twips)))
938
+ if h is None:
939
+ report.want("table.rowHeight", "%s.r%d" % (label, r_i), "无", cfg["rowHeightCm"],
940
+ lambda r=trPr, t=want_twips: _set_or_make(r, "w:trHeight",
941
+ {"w:val": t, "w:hRule": "atLeast"}))
942
+ else:
943
+ if h.get(qn("w:hRule")) != "atLeast":
944
+ report.want("table.rowHeight.rule", "%s.r%d" % (label, r_i),
945
+ h.get(qn("w:hRule")), "atLeast",
946
+ lambda e=h: e.set(qn("w:hRule"), "atLeast"))
947
+ if (h.get(qn("w:val")) or "0") != want_twips:
948
+ report.want("table.rowHeight.value", "%s.r%d" % (label, r_i),
949
+ h.get(qn("w:val")), cfg["rowHeightCm"],
950
+ lambda e=h, t=want_twips: e.set(qn("w:val"), t))
951
+ if r_i == 0:
952
+ if trPr.find(qn("w:tblHeader")) is None:
953
+ report.want("table.headerRepeat", "%s.r0" % label, "未重复标题行", "重复",
954
+ lambda r=trPr: _set_or_make(r, "w:tblHeader", {}))
955
+ head = r_i == 0
956
+ for c_i, cell in enumerate(row.cells):
957
+ tcPr = cell._tc.get_or_add_tcPr()
958
+ va = tcPr.find(qn("w:vAlign"))
959
+ if va is None or va.get(qn("w:val")) != "center":
960
+ report.want("table.vAlign", "%s.r%d.c%d" % (label, r_i, c_i), None, "center",
961
+ lambda p=tcPr: _set_or_make(p, "w:vAlign", {"w:val": "center"}))
962
+ font = fonts["tableHead"] if head else fonts["tableBody"]
963
+ for p_i, par in enumerate(cell.paragraphs):
964
+ where = "%s.r%d.c%d.p%d" % (label, r_i, c_i, p_i)
965
+ # 单元格也要处理中英混排(「AI 平台」→「AI平台」)
966
+ normalize_text(par, report, where, cfg)
967
+ auto_space_off(par, report, where)
968
+ pf = par.paragraph_format
969
+ if pf.line_spacing_rule != WD_LINE_SPACING.SINGLE:
970
+ report.want("table.lineRule", where, ename(pf.line_spacing_rule), "SINGLE",
971
+ lambda x=pf: setattr(x, "line_spacing_rule", WD_LINE_SPACING.SINGLE))
972
+ if pt_of(pf.line_spacing) not in (None, 1.0):
973
+ report.want("table.lineSpacing", where, pt_of(pf.line_spacing), "单倍",
974
+ lambda x=pf: setattr(x, "line_spacing", 1.0))
975
+ if pf.first_line_indent not in (None, 0):
976
+ report.want("table.firstLineIndent", where, pt_of(pf.first_line_indent), "无",
977
+ lambda x=pf: setattr(x, "first_line_indent", None))
978
+ for attr in ("firstLine", "left", "right"):
979
+ cur_chars = _get_chars(par, "w:" + attr + "Chars")
980
+ if cur_chars is not None:
981
+ report.want("table.%sChars" % attr, where, "%.2f 字符" % cur_chars, "无",
982
+ (lambda p=par, a=attr: set_chars_indent(p, a, None, Pt(0))))
983
+ _zero_spacing(par, pf, report, where, cfg)
984
+ # 单元格内容(含表头与正文)一律水平居中,并清掉左右缩进
985
+ if pf.alignment != CENTER:
986
+ report.want("table.cellAlign", where, ename(pf.alignment), "CENTER",
987
+ lambda x=pf: setattr(x, "alignment", CENTER))
988
+ if (pt_of(pf.left_indent) or 0) != 0:
989
+ report.want("table.cellLeftIndent", where, pt_of(pf.left_indent), 0,
990
+ lambda x=pf: setattr(x, "left_indent", None))
991
+ if (pt_of(pf.right_indent) or 0) != 0:
992
+ report.want("table.cellRightIndent", where, pt_of(pf.right_indent), 0,
993
+ lambda x=pf: setattr(x, "right_indent", None))
994
+ if cfg["normalize"]["twoCharCellSpace"] and par.text and re.fullmatch(r"[\u4e00-\u9fff]{2}", par.text):
995
+ _spread_two_chars(par, report, where, font, sizes["table"], cfg)
996
+ if par.runs:
997
+ style_runs(par, font, sizes["table"], fonts["latin"], report, where, cfg)
998
+
999
+
1000
+ def _spread_two_chars(par, report, where, font, size, cfg):
1001
+ """表格内两个字的词语中间加两个半格空格。"""
1002
+ target = par.text[0] + " " + par.text[1]
1003
+ nonempty = [r for r in par.runs if r.text]
1004
+ keep_el = nonempty[0]._element if nonempty else None
1005
+
1006
+ def apply():
1007
+ if keep_el is None:
1008
+ run = par.add_run()
1009
+ set_run(run, font, size, cfg["fonts"]["latin"], _NullReport(), where, cfg)
1010
+ run.text = target
1011
+ return
1012
+ for r in par.runs:
1013
+ r.text = target if r._element is keep_el else ""
1014
+
1015
+ report.want("text.twoCharCell", where, par.text, target, apply)
1016
+
1017
+
1018
+ class _NullReport:
1019
+ def want(self, *a, **k):
1020
+ return False
1021
+
1022
+
1023
+ def _set_or_make(parent, tag, attrs):
1024
+ el = parent.find(qn(tag))
1025
+ if el is None:
1026
+ el = OxmlElement(tag)
1027
+ parent.append(el)
1028
+ for k, v in attrs.items():
1029
+ el.set(qn(k), v)
1030
+ return el
1031
+
1032
+
1033
+ # ---------------------------------------------------------------- 页脚页码
1034
+ def set_footer(section, report, cfg, fix=True):
1035
+ footer = section.footer
1036
+ if not fix:
1037
+ has_field = "PAGE" in footer._element.xml
1038
+ par0 = footer.paragraphs[0] if footer.paragraphs else None
1039
+ align_ok = par0 is not None and par0.paragraph_format.alignment == CENTER
1040
+ if not (has_field and align_ok):
1041
+ report.want("footer.pageNumber", "footer",
1042
+ "有" if has_field else "无页码域", "底端居中 — 1 —")
1043
+ return
1044
+ if footer.is_linked_to_previous:
1045
+ footer.is_linked_to_previous = False
1046
+ par = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
1047
+ has_field = "PAGE" in par._element.xml or True
1048
+ for child in list(par._p):
1049
+ if child.tag != qn("w:pPr"):
1050
+ par._p.remove(child)
1051
+ pf = par.paragraph_format
1052
+ pf.alignment = CENTER
1053
+ if pf.first_line_indent not in (None, 0):
1054
+ report.want("footer.firstLineIndent", "footer", pt_of(pf.first_line_indent), "无",
1055
+ lambda: setattr(pf, "first_line_indent", None))
1056
+
1057
+ def mk_run(text=None):
1058
+ r = par.add_run()
1059
+ rPr = r._element.get_or_add_rPr()
1060
+ rFonts = OxmlElement("w:rFonts")
1061
+ rFonts.set(qn("w:ascii"), cfg["fonts"]["latin"])
1062
+ rFonts.set(qn("w:hAnsi"), cfg["fonts"]["latin"])
1063
+ rFonts.set(qn("w:eastAsia"), cfg["fonts"]["footer"])
1064
+ rPr.append(rFonts)
1065
+ r.font.size = Pt(cfg["sizes"]["footer"])
1066
+ if text is not None:
1067
+ r.text = text
1068
+ return r
1069
+
1070
+ def add_field_run(fld_type=None, instr=None):
1071
+ r = mk_run()
1072
+ if instr is not None:
1073
+ el = OxmlElement("w:instrText")
1074
+ el.set(qn("xml:space"), "preserve")
1075
+ el.text = instr
1076
+ else:
1077
+ el = OxmlElement("w:fldChar")
1078
+ el.set(qn("w:fldCharType"), fld_type)
1079
+ r._element.append(el)
1080
+ return r
1081
+
1082
+ mk_run("— ")
1083
+ add_field_run("begin")
1084
+ add_field_run(instr=" PAGE ")
1085
+ add_field_run("separate")
1086
+ mk_run("1")
1087
+ add_field_run("end")
1088
+ mk_run(" —")
1089
+ report.stats["footer"] = report.stats.get("footer", 0) + 1
1090
+
1091
+
1092
+ # ---------------------------------------------------------------- 主流程
1093
+ def _looks_like_attach_wrap(par, cfg):
1094
+ """判断是否是附件条目被拆出来的续行:首行缩进正好等于 attachWrapIndentChars。"""
1095
+ want = float(cfg["attachWrapIndentChars"])
1096
+ cur = _get_chars(par, "w:firstLineChars")
1097
+ return cur is not None and abs(cur - want) < 0.05
1098
+
1099
+
1100
+ def classify(items, cfg):
1101
+ """返回 [(kind, obj, text)],kinds: title/table_caption/h1/h2/h3/attach_tag/attach_line/
1102
+ sign_org/sign_date/image/body/blank/tbl"""
1103
+ out = []
1104
+ paras = [(i, obj) for i, (t, obj) in enumerate(items) if t == "p"]
1105
+ nonempty = [(i, p) for i, p in paras if p.text.strip()]
1106
+ title_idx = set()
1107
+ if nonempty:
1108
+ i0 = nonempty[0][0]
1109
+ title_idx.add(i0)
1110
+ # 标题续行:紧跟其后、短、非标题模式、非编号
1111
+ prev_len = len(nonempty[0][1].text.strip())
1112
+ for i, p in nonempty[1:3]:
1113
+ txt = p.text.strip()
1114
+ if (i == i0 + 1 and prev_len <= 18 and len(txt) <= 40
1115
+ and not txt.endswith(("。", ":", ",", ";", "!", "?", "、", ":"))
1116
+ and not RE_H1.match(txt) and not RE_H2.match(txt)
1117
+ and not RE_ATTACH_LINE.match(txt) and not RE_ATTACH_TAG.match(txt)):
1118
+ title_idx.add(i)
1119
+ else:
1120
+ break
1121
+
1122
+ # 落款:末尾日期行
1123
+ sign = {}
1124
+ tail = [(i, p) for i, p in paras if p.text.strip()][-6:]
1125
+ for pos, (i, p) in enumerate(tail):
1126
+ if RE_DATE.search(p.text) and text_width(p.text.strip()) <= 26:
1127
+ sign[i] = "sign_date"
1128
+ if pos > 0:
1129
+ prev_i, prev_p = tail[pos - 1]
1130
+ if (text_width(prev_p.text.strip()) <= 24 and not RE_DATE.search(prev_p.text)
1131
+ and not prev_p.text.strip().endswith(("。", ".", ",", ";"))):
1132
+ sign[prev_i] = "sign_org"
1133
+ break
1134
+
1135
+ for i, (t, obj) in enumerate(items):
1136
+ if t == "tbl":
1137
+ out.append(("tbl", obj, ""))
1138
+ continue
1139
+ p = obj
1140
+ txt = p.text.strip()
1141
+ if i in title_idx:
1142
+ out.append(("title", p, txt))
1143
+ elif i in sign:
1144
+ out.append((sign[i], p, txt))
1145
+ elif not txt:
1146
+ has_img = bool(p._element.findall(".//" + qn("w:drawing")))
1147
+ out.append(("image" if has_img else "blank", p, ""))
1148
+ elif RE_ATTACH_TAG.match(p.text or txt):
1149
+ out.append(("attach_tag", p, txt))
1150
+ elif RE_ATTACH_LINE.match(p.text or txt):
1151
+ out.append(("attach_line", p, txt))
1152
+ elif RE_H1.match(p.text):
1153
+ out.append(("h1", p, txt))
1154
+ elif RE_H2.match(p.text):
1155
+ out.append(("h2", p, txt))
1156
+ elif RE_H3.match(p.text):
1157
+ out.append(("h3", p, txt))
1158
+ elif p._element.findall(".//" + qn("w:drawing")):
1159
+ out.append(("image", p, txt))
1160
+ else:
1161
+ out.append(("body", p, txt))
1162
+ # 附件续行:紧接“附件:XXX”之后的附件条目,需与冒号后首字对齐
1163
+ in_attach = False
1164
+ for idx, (t, obj, txt) in enumerate(out):
1165
+ if t == "tbl":
1166
+ in_attach = False
1167
+ continue
1168
+ kind = t
1169
+ if kind == "attach_line":
1170
+ in_attach = True
1171
+ continue
1172
+ if not in_attach:
1173
+ continue
1174
+ if kind in BLANK_KINDS:
1175
+ continue # 空行不打断附件条目序列
1176
+ if kind in ("sign_org", "sign_date", "attach_tag", "title"):
1177
+ in_attach = False
1178
+ elif RE_ATTACH_ITEM.match(txt):
1179
+ out[idx] = ("attach_cont", obj, txt)
1180
+ elif _looks_like_attach_wrap(obj, cfg):
1181
+ # 我们自己拆出来的续行(首行缩进 6 字符)→ 保持附件归属
1182
+ out[idx] = ("attach_wrap", obj, txt)
1183
+ else:
1184
+ in_attach = False
1185
+ # 表标题:紧邻表格之前的段落
1186
+ for idx, (t, obj, txt) in enumerate(out):
1187
+ if t != "tbl":
1188
+ continue
1189
+ j = idx - 1
1190
+ while j >= 0 and out[j][0] in BLANK_KINDS:
1191
+ j -= 1
1192
+ if j >= 0:
1193
+ kind, prev, ptxt = out[j]
1194
+ if kind == "body" and ptxt and text_width(ptxt) <= 40 and not ptxt.endswith("。"):
1195
+ out[j] = ("table_caption", prev, ptxt)
1196
+ # 表标题与表格之间那一段:专用“0 行高、5 号字”空段,不能按普通空行排 29 磅
1197
+ for idx, (t, obj, txt) in enumerate(out):
1198
+ if t != "tbl":
1199
+ continue
1200
+ j = idx - 1
1201
+ while j >= 0 and out[j][0] in BLANK_KINDS + ("caption_spacer",):
1202
+ j -= 1
1203
+ if j >= 0 and out[j][0] == "table_caption":
1204
+ for k in range(j + 1, idx):
1205
+ out[k] = ("caption_spacer", out[k][1], "")
1206
+ # 空行也带格式:标题上空、多行标题之间、标题下固定那 1 行 → 沿用标题格式;
1207
+ # 其余空行沿用正文格式——和“手工回车”继承出来的结果一致。
1208
+ title_positions = [i for i, (t, _o, _x) in enumerate(out) if t == "title"]
1209
+ if title_positions:
1210
+ first_t, last_t = title_positions[0], title_positions[-1]
1211
+ title_side = set(range(0, first_t)) | set(range(first_t + 1, last_t))
1212
+ j = last_t + 1
1213
+ room = int(cfg["titleBlankAfterLines"])
1214
+ while j < len(out) and out[j][0] == "blank" and room > 0:
1215
+ title_side.add(j)
1216
+ room -= 1
1217
+ j += 1
1218
+ for idx in title_side:
1219
+ if out[idx][0] == "blank":
1220
+ out[idx] = ("blank_title", out[idx][1], "")
1221
+ return out
1222
+
1223
+
1224
+ def _spacer_size_val(cfg):
1225
+ return str(int(round(cfg["sizes"]["spacer"] * 2)))
1226
+
1227
+
1228
+ def _spacer_props_ok(p_el, cfg):
1229
+ pPr = p_el.find(qn("w:pPr"))
1230
+ if pPr is None:
1231
+ return False
1232
+ sp = pPr.find(qn("w:spacing"))
1233
+ if sp is None:
1234
+ return False
1235
+ if sp.get(qn("w:line")) != "0" or sp.get(qn("w:lineRule")) != "atLeast":
1236
+ return False
1237
+ if (sp.get(qn("w:before")) or "") != "0" or (sp.get(qn("w:after")) or "") != "0":
1238
+ return False
1239
+ rPr = pPr.find(qn("w:rPr"))
1240
+ sz = None if rPr is None else rPr.find(qn("w:sz"))
1241
+ return sz is not None and sz.get(qn("w:val")) == _spacer_size_val(cfg)
1242
+
1243
+
1244
+ def _write_spacer_props(p_el, cfg):
1245
+ """行高最小值 0 磅、字号 5 号、段前段后 0 —— 表标题与表格之间那一行。"""
1246
+ pPr = p_el.get_or_add_pPr()
1247
+ sp = pPr.get_or_add_spacing()
1248
+ for key in ("w:beforeLines", "w:afterLines",
1249
+ "w:beforeAutospacing", "w:afterAutospacing"):
1250
+ sp.attrib.pop(qn(key), None)
1251
+ sp.set(qn("w:line"), "0")
1252
+ sp.set(qn("w:lineRule"), "atLeast")
1253
+ sp.set(qn("w:before"), "0")
1254
+ sp.set(qn("w:after"), "0")
1255
+ rPr = pPr.find(qn("w:rPr"))
1256
+ if rPr is None:
1257
+ rPr = OxmlElement("w:rPr")
1258
+ pPr.append(rPr)
1259
+ val = _spacer_size_val(cfg)
1260
+ for tag in ("w:sz", "w:szCs"):
1261
+ el = rPr.find(qn(tag))
1262
+ if el is None:
1263
+ el = OxmlElement(tag)
1264
+ rPr.append(el)
1265
+ el.set(qn("w:val"), val)
1266
+
1267
+
1268
+ def format_table_caption_spacer(items, kinds, report, cfg):
1269
+ """表标题与表格之间插入一行(行高最小值 0,字号 5 号);已有则只校正属性。"""
1270
+ n = 0
1271
+ for idx, (t, obj) in enumerate(items):
1272
+ if t != "tbl":
1273
+ continue
1274
+ j = idx - 1
1275
+ while j >= 0 and kinds[j] in BLANK_KINDS + ("caption_spacer",):
1276
+ j -= 1
1277
+ if j < 0 or kinds[j] != "table_caption":
1278
+ continue
1279
+ n += 1
1280
+ prev_p = items[j][1]
1281
+ nxt = prev_p._p.getnext()
1282
+ if nxt is not None and nxt.tag == qn("w:p") and _is_blank_el(nxt):
1283
+ if not _spacer_props_ok(nxt, cfg):
1284
+ report.want("table.captionSpacer", "table%d" % n,
1285
+ "空行行高/字号不符", "行高最小值 0 磅、5 号字",
1286
+ lambda e=nxt: _write_spacer_props(e, cfg))
1287
+ continue
1288
+ spacer = OxmlElement("w:p")
1289
+ _write_spacer_props(spacer, cfg)
1290
+ prev_p._p.addnext(spacer)
1291
+ report.want("table.captionSpacer", "table%d" % n,
1292
+ "表标题与表格间无空行", "插入空行",
1293
+ lambda: None)
1294
+ report.stats["table.spacer"] += 1
1295
+
1296
+
1297
+ def _is_blank_el(el):
1298
+ if el.tag != qn("w:p"):
1299
+ return False
1300
+ if el.findall(".//" + qn("w:drawing")):
1301
+ return False
1302
+ return not "".join(el.itertext()).strip()
1303
+
1304
+
1305
+ def _count_blanks_before(par):
1306
+ n = 0
1307
+ prev = par._p.getprevious()
1308
+ while prev is not None and _is_blank_el(prev):
1309
+ n += 1
1310
+ prev = prev.getprevious()
1311
+ return n
1312
+
1313
+
1314
+ def _next_anchor_par(par):
1315
+ """其后第一个非空段落(跳过空段落;表格不作为锚点)。"""
1316
+ cur = par._p.getnext()
1317
+ while cur is not None:
1318
+ if cur.tag == qn("w:p") and not _is_blank_el(cur):
1319
+ return Paragraph(cur, par._parent)
1320
+ cur = cur.getnext()
1321
+ return None
1322
+
1323
+
1324
+ def _anchor_after_attach(seq, idx):
1325
+ """「附件:…」之后第一个非附件条目、非空行的段落。
1326
+
1327
+ 附件条目(attach_cont)属于同一段附件说明,不能把它们和“附件:”拆开插空行。
1328
+ """
1329
+ for j in range(idx + 1, len(seq)):
1330
+ kind, obj, _txt = seq[j]
1331
+ if kind in BLANK_KINDS + ("attach_cont", "attach_wrap"):
1332
+ continue
1333
+ if kind == "tbl":
1334
+ return None
1335
+ return obj
1336
+ return None
1337
+
1338
+
1339
+ def ensure_blank_lines(kinds, report, cfg):
1340
+ """段前段后一律 0 磅,空行改用独立空段落(整行)表达。
1341
+
1342
+ 按参考要求保证:标题上空 2 行、下空 1 行;附件说明前空 1 行、后空 2 行;
1343
+ 文末「附件1」标记前空 1 行;落款前空 2 行(仅 signature.enabled 时)。
1344
+ """
1345
+ plan = {}
1346
+
1347
+ def bump(par, want, label, blank_kind="blank"):
1348
+ if par is None or not want:
1349
+ return
1350
+ key = id(par._p)
1351
+ old = plan.get(key)
1352
+ if old is None or old[1] < want:
1353
+ plan[key] = (par, want, label, blank_kind)
1354
+
1355
+ titles = [obj for k, obj, _t in kinds if k == "title"]
1356
+ if titles:
1357
+ bump(titles[0], cfg["titleBlankBeforeLines"], "标题前", "blank_title")
1358
+ bump(_next_anchor_par(titles[-1]), cfg["titleBlankAfterLines"], "标题后", "blank_title")
1359
+ for idx, (k, obj, _t) in enumerate(kinds):
1360
+ if k == "attach_line":
1361
+ bump(obj, cfg["attachBlankBeforeLines"], "附件说明前")
1362
+ bump(_anchor_after_attach(kinds, idx), cfg["attachBlankAfterLines"], "附件说明后")
1363
+ elif k == "attach_tag":
1364
+ bump(_next_anchor_par(obj), cfg["attachTagBlankAfterLines"], "附件标记与附件标题之间")
1365
+ elif k == "sign_org" and cfg["signature"]["enabled"]:
1366
+ bump(obj, cfg["signature"]["blankLinesBefore"], "落款前")
1367
+
1368
+ touched = 0
1369
+ for par, want, label, blank_kind in plan.values():
1370
+ cur = _count_blanks_before(par)
1371
+ if cur == want:
1372
+ continue
1373
+ if cur < want:
1374
+ for _ in range(want - cur):
1375
+ _style_blank(par.insert_paragraph_before(), cfg, blank_kind)
1376
+ else:
1377
+ for _ in range(cur - want):
1378
+ prev = par._p.getprevious()
1379
+ if prev is None or not _is_blank_el(prev):
1380
+ break
1381
+ prev.getparent().remove(prev)
1382
+ report.want("doc.blankLines", "doc." + label,
1383
+ "%d 个空行" % cur, "%d 个空行" % want)
1384
+ touched += 1
1385
+ return touched
1386
+
1387
+
1388
+ def _collect_body(doc):
1389
+ body = doc.element.body
1390
+ items = []
1391
+ for child in list(body.iterchildren()):
1392
+ if child.tag == qn("w:p"):
1393
+ items.append(("p", Paragraph(child, doc)))
1394
+ elif child.tag == qn("w:tbl"):
1395
+ items.append(("tbl", Table(child, doc)))
1396
+ return items
1397
+
1398
+
1399
+ # --------------------------------------------------------------- 附件自动分段
1400
+ # “附件:1.……”这类条目往往长到要折行。公文做法是把它拆成真正的多个段落:
1401
+ # 第 1 段(“附件:1.……首行”)首行缩进 2 字符;
1402
+ # 每个折行出来的续行段落首行缩进 6 字符(“附件:”3 字 + “1.”2 字 + 半字),
1403
+ # 后续条目“2.……”首行缩进 5 字符。左/右/悬挂缩进一律 0,段前段后 0。
1404
+ #
1405
+ # 折行位置不靠字宽估算:把待测段落单独存成临时文档交给 Word/WPS 排版,用
1406
+ # Range.Information(wdFirstCharacterLineNumber) 读回每个字符落在第几行,
1407
+ # 按实测行边界拆段,因此和最终打印效果完全一致。
1408
+
1409
+ _WORD_MEASURE_PS = r"""
1410
+ $ErrorActionPreference = 'Stop'
1411
+ $src = '@SRC@'
1412
+ $out = '@OUT@'
1413
+ $app = $null
1414
+ $doc = $null
1415
+ try {
1416
+ $app = New-Object -ComObject Word.Application
1417
+ $app.Visible = $false
1418
+ $app.DisplayAlerts = 0
1419
+ $doc = $app.Documents.Open($src, $false, $true)
1420
+ $parts = New-Object System.Collections.Generic.List[string]
1421
+ $count = $doc.Paragraphs.Count
1422
+ for ($p = 1; $p -le $count; $p++) {
1423
+ $r = $doc.Paragraphs($p).Range
1424
+ $t = $r.Text -replace "`r", "" -replace "`a", ""
1425
+ $len = $t.Length
1426
+ if ($len -eq 0) { $parts.Add('[]'); continue }
1427
+ if ([int]$r.ComputeStatistics(1) -le 1) { $parts.Add('[[' + 0 + ',' + ($len - 1) + ']]'); continue }
1428
+ $segs = New-Object System.Collections.Generic.List[string]
1429
+ $prev = -1
1430
+ $start = 0
1431
+ for ($i = 0; $i -lt $len; $i++) {
1432
+ $ln = [int]$doc.Range($r.Start + $i, $r.Start + $i + 1).Information(10)
1433
+ if ($ln -ne $prev) {
1434
+ if ($prev -ne -1) { $segs.Add('[' + $start + ',' + ($i - 1) + ']') }
1435
+ $start = $i
1436
+ $prev = $ln
1437
+ }
1438
+ }
1439
+ $segs.Add('[' + $start + ',' + ($len - 1) + ']')
1440
+ $parts.Add('[' + ($segs -join ',') + ']')
1441
+ }
1442
+ [System.IO.File]::WriteAllText($out, '[' + ($parts -join ',') + ']', [System.Text.UTF8Encoding]::new($false))
1443
+ 'OK'
1444
+ } catch {
1445
+ 'ERR ' + $_.Exception.Message
1446
+ } finally {
1447
+ if ($doc) { try { $doc.Close($false) } catch {} }
1448
+ if ($app) { try { $app.Quit() } catch {} }
1449
+ }
1450
+ """
1451
+
1452
+
1453
+ def _powershell():
1454
+ for name in ("powershell.exe", "powershell", "pwsh"):
1455
+ found = shutil.which(name)
1456
+ if found:
1457
+ return found
1458
+ return None
1459
+
1460
+
1461
+ def _word_measure(path):
1462
+ """调用 Word/WPS 读回每段的行区间;不可用时返回 None。"""
1463
+ shell = _powershell()
1464
+ if not shell:
1465
+ return None
1466
+ fd, out_json = tempfile.mkstemp(suffix=".json")
1467
+ os.close(fd)
1468
+ script = _WORD_MEASURE_PS.replace("@SRC@", path).replace("@OUT@", out_json)
1469
+ enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
1470
+ try:
1471
+ proc = subprocess.run([shell, "-NoProfile", "-NonInteractive",
1472
+ "-EncodedCommand", enc],
1473
+ capture_output=True, timeout=180)
1474
+ head = (proc.stdout or b"").decode("utf-8", "replace").strip()
1475
+ if not head.startswith("OK"):
1476
+ return None
1477
+ return json.loads(open(out_json, encoding="utf-8").read())
1478
+ except Exception:
1479
+ return None
1480
+ finally:
1481
+ try:
1482
+ os.unlink(out_json)
1483
+ except OSError:
1484
+ pass
1485
+
1486
+
1487
+ def _sibling_pos(el):
1488
+ """元素在 body 里的位置(前面有几个元素兄弟)。lxml 代理对象不保证同一性,用 XPath 数最稳。"""
1489
+ return int(el.xpath("count(preceding-sibling::*)"))
1490
+
1491
+
1492
+ def _measure_attach_lines(doc, entries, wrap_chars, body_pt=16.0):
1493
+ """entries: [(body 位置, Paragraph, label, is_wrap)](已按位置升序);返回等长行区间列表。
1494
+
1495
+ 两种测量几何:
1496
+ * 起始段(`附件:1.` / `2.`):保持它自己的 firstLineChars,量出“首行写到哪换行”;
1497
+ * 续行段(已经拆出来的 wrap 段):把缩进临时设成 `leftChars = 6 字符`、firstLine 清零,
1498
+ 量成“整段 6 字符缩进”的均匀版式——拆出来的每一段都从 6 字符开始,只有这样量才准。
1499
+ """
1500
+ if not entries:
1501
+ return []
1502
+ tmpdir = tempfile.mkdtemp(prefix="docxfmt-measure-")
1503
+ src = os.path.join(tmpdir, "measure.docx")
1504
+ try:
1505
+ doc.save(src)
1506
+ probe = Document(src)
1507
+ keep = dict((pos, is_wrap) for pos, _p, _l, is_wrap in entries)
1508
+ body = probe.element.body
1509
+ cursor = 0
1510
+ for child in list(body.iterchildren()):
1511
+ if child.tag == qn("w:sectPr"):
1512
+ continue
1513
+ pos = cursor
1514
+ cursor += 1
1515
+ if pos not in keep:
1516
+ body.remove(child)
1517
+ continue
1518
+ if not keep[pos]:
1519
+ continue
1520
+ par = Paragraph(child, probe)
1521
+ ind = _get_ind(par, make=True)
1522
+ # 探测段落只用磅值左缩进:实测 `w:leftChars` 与 `w:left` 并存时 Word 会按
1523
+ # 别的方式解释(6 字符被当成 30 磅,折行点偏后 2 个字),只写磅值才准。
1524
+ ind.set(qn("w:left"), str(int(round(float(wrap_chars) * float(body_pt) * 20))))
1525
+ for name in ("w:leftChars", "w:firstLineChars", "w:firstLine",
1526
+ "w:hangingChars", "w:hanging"):
1527
+ if ind.get(qn(name)) is not None:
1528
+ del ind.attrib[qn(name)]
1529
+ probe.save(src)
1530
+ res = _word_measure(src)
1531
+ if res is None or len(res) != len(entries):
1532
+ return None
1533
+ return res
1534
+ finally:
1535
+ shutil.rmtree(tmpdir, ignore_errors=True)
1536
+
1537
+
1538
+ def _do_split_par(par, segs, cfg):
1539
+ """按给定文本切片把一个段落拆成多个段落,续行首行缩进 attachWrapIndentChars。"""
1540
+ p_el = par._p
1541
+ parent = p_el.getparent()
1542
+ runs = list(par.runs)
1543
+ spans = []
1544
+ pos = 0
1545
+ for seg in segs:
1546
+ spans.append((pos, pos + len(seg)))
1547
+ pos += len(seg)
1548
+ els = []
1549
+ for a, b in spans:
1550
+ el = copy.deepcopy(p_el)
1551
+ for child in list(el):
1552
+ if child.tag != qn("w:pPr"):
1553
+ el.remove(child)
1554
+ cursor = 0
1555
+ for r in runs:
1556
+ rtxt = r.text
1557
+ rs = cursor
1558
+ cursor += len(rtxt)
1559
+ lo, hi = max(rs, a), min(cursor, b)
1560
+ if hi <= lo:
1561
+ continue
1562
+ new_r = copy.deepcopy(r._r)
1563
+ for t in new_r.findall(qn("w:t")):
1564
+ new_r.remove(t)
1565
+ t = OxmlElement("w:t")
1566
+ t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
1567
+ t.text = rtxt[lo - rs:hi - rs]
1568
+ new_r.append(t)
1569
+ el.append(new_r)
1570
+ els.append(el)
1571
+ anchor = p_el
1572
+ for el in els:
1573
+ anchor.addnext(el)
1574
+ anchor = el
1575
+ parent.remove(p_el)
1576
+ wrap_chars = float(cfg["attachWrapIndentChars"])
1577
+ body_pt = float(cfg["sizes"]["body"])
1578
+ for el in els[1:]:
1579
+ sub = Paragraph(el, par._parent)
1580
+ set_chars_indent(sub, "firstLine", wrap_chars, Pt(wrap_chars * body_pt))
1581
+
1582
+
1583
+ def split_attach_paragraphs(doc, report, cfg):
1584
+ """把超过一行的附件条目按 Word 实测折行点拆段;返回是否有改动。"""
1585
+ if not cfg["attachSplit"]["enabled"]:
1586
+ return False
1587
+ if cfg["attachSplit"]["mode"] != "word":
1588
+ return False # indent-only:只排 2/5 字符缩进,折行交给使用者手工处理
1589
+ kinds = classify(_collect_body(doc), cfg)
1590
+ targets = []
1591
+ for i, (kind, obj, _txt) in enumerate(kinds):
1592
+ if kind not in ("attach_line", "attach_cont", "attach_wrap"):
1593
+ continue
1594
+ style_par(obj, kind, report, "p%d" % i, cfg) # 先落缩进,测量才准
1595
+ # 版心宽 15.6cm ≈ 27.6 个三号汉字,按 6 字符缩进算也还有 21 字;
1596
+ # 短于此的条目不可能折行,不必启动 Word(省 3~6 秒)
1597
+ if len(obj.text) < int(cfg["attachSplit"]["minCharsToMeasure"]):
1598
+ continue
1599
+ targets.append((_sibling_pos(obj._p), obj, "p%d" % i, kind == "attach_wrap"))
1600
+ targets.sort(key=lambda t: t[0])
1601
+ if not targets:
1602
+ return False
1603
+ ranges = _measure_attach_lines(doc, targets, cfg["attachWrapIndentChars"],
1604
+ cfg["sizes"]["body"])
1605
+ if ranges is None:
1606
+ report.warn("附件自动分段不可用:本机没有能调用的 Word/WPS 排版引擎,"
1607
+ "已按“附件条目首行缩进 2/5 字符、左右悬挂 0”排版,折行请手工换行。")
1608
+ return False
1609
+ changed = False
1610
+ for (_pidx, par, label, is_wrap), rng in zip(targets, ranges):
1611
+ if not rng or len(rng) < 2:
1612
+ continue
1613
+ text = par.text
1614
+ if not text:
1615
+ continue
1616
+ if is_wrap:
1617
+ segs = [text[s:e + 1] for s, e in rng if 0 <= s <= e < len(text)]
1618
+ else:
1619
+ # 起始段只切第一处折行;剩下的尾巴留给下一轮按 6 字符缩进量
1620
+ cut = rng[0][1] + 1
1621
+ segs = [text[:cut], text[cut:]]
1622
+ if len(segs) < 2 or "".join(segs) != text or not all(segs):
1623
+ continue
1624
+ report.want("attach.split", label, "1 段 %d 字(自动折行)" % len(text),
1625
+ "%d 段(续行首行缩进 %g 字符)"
1626
+ % (len(segs), cfg["attachWrapIndentChars"]),
1627
+ (lambda p=par, s=segs: _do_split_par(p, s, cfg)))
1628
+ changed = True
1629
+ return changed
1630
+
1631
+
1632
+ def process(path, mode, cfg):
1633
+ t0 = time.time()
1634
+ fix = mode == "apply"
1635
+ doc = Document(path)
1636
+ report = Report(os.path.abspath(path), mode, fix)
1637
+
1638
+ for section in doc.sections:
1639
+ m = cfg["marginsCm"]
1640
+ for attr, key in (("top_margin", "top"), ("bottom_margin", "bottom"),
1641
+ ("left_margin", "left"), ("right_margin", "right")):
1642
+ cur = getattr(section, attr)
1643
+ want = Cm(m[key])
1644
+ if cur is None or abs(cur.cm - m[key]) > 0.02:
1645
+ report.want("page.margin." + key, "section", None if cur is None else round(cur.cm, 2), m[key],
1646
+ (lambda s=section, a=attr, w=want: setattr(s, a, w)))
1647
+ if cfg["pageNumber"]:
1648
+ set_footer(section, report, cfg, fix)
1649
+
1650
+ body = doc.element.body
1651
+ items = _collect_body(doc)
1652
+
1653
+ kinds = classify(items, cfg)
1654
+ if fix:
1655
+ if cfg["attachSplit"]["enabled"]:
1656
+ for _round in range(max(1, int(cfg["attachSplit"]["maxRounds"]))):
1657
+ if not split_attach_paragraphs(doc, report, cfg):
1658
+ break
1659
+ items = _collect_body(doc)
1660
+ kinds = classify(items, cfg)
1661
+ ensure_blank_lines(kinds, report, cfg)
1662
+ format_table_caption_spacer(items, [k for k, _o, _t in kinds], report, cfg)
1663
+ items = _collect_body(doc)
1664
+ kinds = classify(items, cfg)
1665
+
1666
+ if not fix and cfg["attachSplit"]["enabled"]:
1667
+ split_attach_paragraphs(doc, report, cfg)
1668
+
1669
+ title_positions = [i for i, (k, _o, _t) in enumerate(kinds) if k == "title"]
1670
+ if title_positions:
1671
+ if len(title_positions) == 1:
1672
+ kinds[title_positions[0]] = ("title_only",) + tuple(kinds[title_positions[0]][1:])
1673
+ else:
1674
+ for pos, idx in enumerate(title_positions):
1675
+ name = "title_first" if pos == 0 else ("title_last" if pos == len(title_positions) - 1 else "title_mid")
1676
+ kinds[idx] = (name,) + tuple(kinds[idx][1:])
1677
+ table_idx = 0
1678
+ for i, (kind, obj, txt) in enumerate(kinds):
1679
+ label = "p%d" % i
1680
+ if kind == "tbl":
1681
+ style_table(obj, report, "t%d" % table_idx, cfg)
1682
+ table_idx += 1
1683
+ continue
1684
+ if kind in BLANK_KINDS:
1685
+ style_par(obj, kind, report, label, cfg)
1686
+ continue
1687
+ if kind in ("body", "h1", "h2", "h3", "attach_line", "attach_cont",
1688
+ "attach_wrap", "table_caption") or kind.startswith("title"):
1689
+ normalize_text(obj, report, label, cfg)
1690
+ style_par(obj, kind, report, label, cfg)
1691
+ if kind == "sign_org" and cfg["signature"]["enabled"]:
1692
+ _pad_signature(obj, report, label, cfg, kinds, i)
1693
+ if kind == "sign_date" and cfg["signature"]["enabled"]:
1694
+ _pad_date(obj, report, label, cfg)
1695
+
1696
+ if not fix:
1697
+ # check 模式:只统计表标题与表格之间是否缺空行,内存里插入不写回
1698
+ format_table_caption_spacer(items, [k for k, _o, _t in kinds], report, cfg)
1699
+
1700
+ changed = report.total > 0
1701
+ if fix and changed:
1702
+ tmp = path + ".tmp.docx"
1703
+ doc.save(tmp)
1704
+ os.replace(tmp, path)
1705
+ out = report.as_dict(changed)
1706
+ out["writeBack"] = bool(fix and changed)
1707
+ out["elapsedMs"] = int((time.time() - t0) * 1000)
1708
+ return out
1709
+
1710
+
1711
+ def _pad_date(par, report, label, cfg):
1712
+ txt = par.text
1713
+ pad = cfg["signature"]["datePadSpaces"]
1714
+ want = txt.rstrip("\u3000 ") + "\u3000" * pad
1715
+ if par.runs and not txt.endswith("\u3000" * pad):
1716
+ last = par.runs[-1]
1717
+ report.want("signature.datePad", label, txt, want,
1718
+ (lambda r=last, w=want, cur=txt: setattr(r, "text", r.text + "\u3000" * pad)))
1719
+
1720
+
1721
+ def _pad_signature(par, report, label, cfg, kinds, i):
1722
+ """按参考样例给署名补尾部全角空格:无需盖章→与日期左边缘对齐;需盖章→居中对齐。"""
1723
+ date_txt = None
1724
+ for j in range(i + 1, len(kinds)):
1725
+ if kinds[j][0] == "sign_date":
1726
+ date_txt = kinds[j][2]
1727
+ break
1728
+ if not date_txt:
1729
+ return
1730
+ need = text_width(date_txt.rstrip("\u3000 ")) + cfg["signature"]["datePadSpaces"]
1731
+ mine = text_width(par.text.rstrip("\u3000 "))
1732
+ if cfg["signature"]["seal"]:
1733
+ pad = int(round((need - mine) / 2))
1734
+ else:
1735
+ pad = int(round(need - mine))
1736
+ pad = max(cfg["signature"]["datePadSpaces"], pad)
1737
+ want = par.text.rstrip("\u3000 ") + "\u3000" * pad
1738
+ if par.runs and par.text != want:
1739
+ last = par.runs[-1]
1740
+ cur = par.text
1741
+ report.want("signature.orgPad", label, cur.strip("\u3000"), want.strip("\u3000"),
1742
+ (lambda r=last, d=pad, c=cur: setattr(r, "text", c.rstrip("\u3000 ") + "\u3000" * d)))
1743
+
1744
+
1745
+ def doc_text(path):
1746
+ doc = Document(path)
1747
+ parts = [p.text for p in doc.paragraphs]
1748
+ for tbl in doc.tables:
1749
+ for row in tbl.rows:
1750
+ for cell in row.cells:
1751
+ parts.append(cell.text)
1752
+ return "\n".join(parts)
1753
+
1754
+
1755
+ def skip_reason(path, cfg):
1756
+ """白名单:正文命中 skipContentKeywords(默认「实验报告」)时整篇跳过。"""
1757
+ kws = cfg.get("skipContentKeywords") or []
1758
+ if not kws:
1759
+ return None
1760
+ try:
1761
+ text = doc_text(path)
1762
+ except Exception:
1763
+ return None
1764
+ for kw in kws:
1765
+ if kw and kw in text:
1766
+ return kw
1767
+ return None
1768
+
1769
+
1770
+ def _collect(paths, recursive):
1771
+ out = []
1772
+ for p in paths:
1773
+ if os.path.isdir(p):
1774
+ if recursive:
1775
+ for root, _dirs, files in os.walk(p):
1776
+ for f in sorted(files):
1777
+ if f.lower().endswith(".docx") and not f.startswith("~$"):
1778
+ out.append(os.path.join(root, f))
1779
+ else:
1780
+ for f in sorted(os.listdir(p)):
1781
+ fp = os.path.join(p, f)
1782
+ if os.path.isfile(fp) and f.lower().endswith(".docx") and not f.startswith("~$"):
1783
+ out.append(fp)
1784
+ else:
1785
+ out.append(p)
1786
+ return out
1787
+
1788
+
1789
+ def main(argv=None):
1790
+ ap = argparse.ArgumentParser(description="docx 公文格式规范化")
1791
+ ap.add_argument("path", nargs="+")
1792
+ ap.add_argument("--mode", choices=["apply", "check"], default="apply")
1793
+ ap.add_argument("--recursive", action="store_true")
1794
+ ap.add_argument("--json", action="store_true")
1795
+ ap.add_argument("--config", default=None, help="JSON 配置字符串或 .json 文件路径")
1796
+ args = ap.parse_args(argv)
1797
+
1798
+ cfg = DEFAULTS
1799
+ if args.config:
1800
+ raw = args.config
1801
+ if os.path.isfile(raw):
1802
+ with open(raw, "r", encoding="utf-8") as fh:
1803
+ raw = fh.read()
1804
+ cfg = merge_config(json.loads(raw))
1805
+
1806
+ results = []
1807
+ failed = False
1808
+ violations = 0
1809
+ for path in _collect(args.path, args.recursive):
1810
+ if not path.lower().endswith(".docx"):
1811
+ continue
1812
+ reason = skip_reason(path, cfg)
1813
+ if reason:
1814
+ results.append({
1815
+ "ok": True, "file": os.path.abspath(path), "mode": args.mode,
1816
+ "skipped": True, "skipReason": "正文含白名单关键词「%s」" % reason,
1817
+ "changed": False, "violations": 0, "rules": {}, "stats": {}, "warnings": [],
1818
+ })
1819
+ continue
1820
+ try:
1821
+ res = process(path, args.mode, cfg)
1822
+ except Exception as exc:
1823
+ import traceback
1824
+ res = {"ok": False, "file": os.path.abspath(path), "mode": args.mode,
1825
+ "error": "%s: %s" % (type(exc).__name__, exc),
1826
+ "trace": traceback.format_exc()[-1200:]}
1827
+ failed = True
1828
+ violations += res.get("violations", 0) or 0
1829
+ results.append(res)
1830
+
1831
+ payload = results[0] if len(results) == 1 else {"ok": not failed, "files": results,
1832
+ "count": len(results), "violations": violations}
1833
+ if args.json:
1834
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1835
+ else:
1836
+ for res in (results if len(results) > 1 else [results[0]]):
1837
+ if not res.get("ok"):
1838
+ print("[失败] %s\n %s" % (res.get("file"), res.get("error")))
1839
+ continue
1840
+ if res.get("skipped"):
1841
+ print("[已跳过] %s (%s)" % (res.get("file"), res.get("skipReason")))
1842
+ continue
1843
+ tag = "已规范化" if res.get("writeBack") else ("无需修改" if not res["changed"] else "存在偏差")
1844
+ print("[%s] %s (偏差 %d 处, %d ms)" % (tag, res["file"], res["violations"], res.get("elapsedMs", 0)))
1845
+ for rule, info in res["rules"].items():
1846
+ smp = info["samples"][0]
1847
+ print(" - %s ×%d 例: %s: %s → %s" % (rule, info["count"], smp["where"],
1848
+ smp["current"], smp["expected"]))
1849
+ for w in res["warnings"]:
1850
+ print(" ! " + w)
1851
+ if failed:
1852
+ return 1
1853
+ if args.mode == "check" and violations:
1854
+ return 2
1855
+ return 0
1856
+
1857
+
1858
+ if __name__ == "__main__":
1859
+ sys.exit(main())