audit-e2w 0.0.0-stage → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +114 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
  7. package/excel_word/README.md +380 -0
  8. package/excel_word/qoder_engine.py +438 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/align.py +154 -0
  13. package/excel_word/wesync/api.py +840 -0
  14. package/excel_word/wesync/backup_history.py +65 -0
  15. package/excel_word/wesync/changelog.py +58 -0
  16. package/excel_word/wesync/cli.py +173 -0
  17. package/excel_word/wesync/commands/__init__.py +8 -0
  18. package/excel_word/wesync/commands/blank_cmd.py +250 -0
  19. package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
  20. package/excel_word/wesync/commands/clear_cmd.py +48 -0
  21. package/excel_word/wesync/commands/export_cmd.py +220 -0
  22. package/excel_word/wesync/commands/marks_cmd.py +152 -0
  23. package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
  24. package/excel_word/wesync/commands/writeback_cmd.py +513 -0
  25. package/excel_word/wesync/config.py +96 -0
  26. package/excel_word/wesync/console.py +78 -0
  27. package/excel_word/wesync/docx_blank.py +156 -0
  28. package/excel_word/wesync/docx_bookmarks.py +287 -0
  29. package/excel_word/wesync/docx_columns.py +257 -0
  30. package/excel_word/wesync/docx_edit.py +77 -0
  31. package/excel_word/wesync/docx_grid.py +212 -0
  32. package/excel_word/wesync/docx_marks.py +291 -0
  33. package/excel_word/wesync/docx_meta.py +157 -0
  34. package/excel_word/wesync/docx_newtable.py +220 -0
  35. package/excel_word/wesync/docx_placeholders.py +161 -0
  36. package/excel_word/wesync/docx_rows.py +67 -0
  37. package/excel_word/wesync/errors.py +5 -0
  38. package/excel_word/wesync/excel_blocks.py +543 -0
  39. package/excel_word/wesync/excel_export.py +136 -0
  40. package/excel_word/wesync/excel_marks.py +193 -0
  41. package/excel_word/wesync/excel_totals.py +53 -0
  42. package/excel_word/wesync/fsops.py +214 -0
  43. package/excel_word/wesync/gui/__init__.py +34 -0
  44. package/excel_word/wesync/gui/__main__.py +6 -0
  45. package/excel_word/wesync/gui/app.py +399 -0
  46. package/excel_word/wesync/gui/manual.py +68 -0
  47. package/excel_word/wesync/gui/pages/__init__.py +31 -0
  48. package/excel_word/wesync/gui/pages/_page.py +89 -0
  49. package/excel_word/wesync/gui/pages/batch_page.py +423 -0
  50. package/excel_word/wesync/gui/pages/blank_page.py +465 -0
  51. package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
  52. package/excel_word/wesync/gui/pages/export_page.py +88 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +429 -0
  54. package/excel_word/wesync/gui/pages/help_page.py +92 -0
  55. package/excel_word/wesync/gui/pages/history_page.py +145 -0
  56. package/excel_word/wesync/gui/pages/marks_page.py +178 -0
  57. package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
  58. package/excel_word/wesync/gui/resources.py +22 -0
  59. package/excel_word/wesync/gui/runner.py +74 -0
  60. package/excel_word/wesync/gui/store.py +34 -0
  61. package/excel_word/wesync/gui/theme.py +100 -0
  62. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +20 -0
  64. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  65. package/excel_word/wesync/gui/widgets/logpane.py +110 -0
  66. package/excel_word/wesync/gui/widgets/nav.py +39 -0
  67. package/excel_word/wesync/report_format.py +1577 -0
  68. package/excel_word/wesync/sort_rules.py +244 -0
  69. package/excel_word/wesync/valuefmt.py +462 -0
  70. package/package.json +49 -4
  71. package/qoder_plugins/audit-toolbox/README.md +156 -0
  72. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,77 @@
1
+ """Word 单元格写入:替换文字但保留 run 格式、段落数量与单元格属性。"""
2
+
3
+ import copy
4
+ from docx.oxml import OxmlElement
5
+ from docx.oxml.ns import qn
6
+ from .docx_grid import cell_text
7
+
8
+
9
+ def _remove_text_nodes(p_el) -> None:
10
+ for t in list(p_el.findall(qn("w:r"))):
11
+ p_el.remove(t)
12
+ for hl in list(p_el.findall(qn("w:hyperlink"))):
13
+ p_el.remove(hl)
14
+
15
+
16
+ def _set_paragraph_text(p_el, text: str, fallback_rpr=None) -> None:
17
+ """写入段落文本,保留第一个 run 的格式。"""
18
+ runs = p_el.findall(qn("w:r"))
19
+ for hl in list(p_el.findall(qn("w:hyperlink"))):
20
+ p_el.remove(hl)
21
+ if runs:
22
+ keep = runs[0]
23
+ for extra in runs[1:]:
24
+ p_el.remove(extra)
25
+ texts = keep.findall(qn("w:t"))
26
+ for idx, node in enumerate(texts):
27
+ if idx == 0:
28
+ node.text = text
29
+ node.set(qn("xml:space"), "preserve")
30
+ else:
31
+ keep.remove(node)
32
+ if not texts:
33
+ node = OxmlElement("w:t")
34
+ node.text = text
35
+ node.set(qn("xml:space"), "preserve")
36
+ keep.append(node)
37
+ return
38
+
39
+ rpr = None
40
+ pPr = p_el.find(qn("w:pPr"))
41
+ if pPr is not None:
42
+ rpr = pPr.find(qn("w:rPr"))
43
+ if rpr is None:
44
+ rpr = fallback_rpr
45
+ run = OxmlElement("w:r")
46
+ if rpr is not None:
47
+ run.append(copy.deepcopy(rpr))
48
+ node = OxmlElement("w:t")
49
+ node.text = text
50
+ node.set(qn("xml:space"), "preserve")
51
+ run.append(node)
52
+ p_el.append(run)
53
+
54
+
55
+ def set_cell_text(tc, text: str, fallback_rpr=None) -> bool:
56
+ """把单元格文本设为 text(\n 表示多段),保留格式。返回是否发生改动。"""
57
+ if tc is None:
58
+ return False
59
+ if cell_text(tc) == text:
60
+ return False
61
+ segments = text.split("\n") if text != "" else [""]
62
+ paras = tc.findall(qn("w:p"))
63
+ if not paras:
64
+ node = OxmlElement("w:p")
65
+ tc.append(node)
66
+ paras = [node]
67
+ while len(paras) > len(segments):
68
+ extra = paras.pop()
69
+ tc.remove(extra)
70
+ while len(paras) < len(segments):
71
+ clone = copy.deepcopy(paras[-1])
72
+ _remove_text_nodes(clone)
73
+ paras[-1].addnext(clone)
74
+ paras = tc.findall(qn("w:p"))
75
+ for p_el, segment in zip(paras, segments):
76
+ _set_paragraph_text(p_el, segment, fallback_rpr)
77
+ return True
@@ -0,0 +1,212 @@
1
+ """Word 表格网格层:解析 tblGrid/gridSpan/vMerge,得到网格坐标、合并区、边框与对齐、单元格文本。"""
2
+
3
+ import copy
4
+ from docx.oxml.ns import qn
5
+ from docx.table import Table
6
+ from docx.text.paragraph import Paragraph
7
+ from .config import BORDER_MAP, JC_MAP, VA_MAP
8
+
9
+
10
+ class GridPos:
11
+ """表格网格中的一个位置。owner=True 表示该位置是单元格的真实起点。"""
12
+
13
+ __slots__ = ("tc", "owner", "vmerge", "span")
14
+
15
+ def __init__(self, tc, owner: bool, vmerge: str | None, span: int = 1):
16
+ self.tc = tc
17
+ self.owner = owner
18
+ self.vmerge = vmerge
19
+ self.span = span
20
+
21
+
22
+ def body_items(doc) -> list[tuple[str, object]]:
23
+ """按文档顺序返回正文中的段落与表格。"""
24
+ items: list[tuple[str, object]] = []
25
+ for child in doc.element.body.iterchildren():
26
+ tag = child.tag.split("}")[1]
27
+ if tag == "p":
28
+ items.append(("p", Paragraph(child, doc)))
29
+ elif tag == "tbl":
30
+ items.append(("tbl", Table(child, doc)))
31
+ return items
32
+
33
+
34
+ def parse_tc_props(tc):
35
+ tcPr = tc.find(qn("w:tcPr"))
36
+ span = 1
37
+ vmerge = None
38
+ if tcPr is not None:
39
+ grid_span = tcPr.find(qn("w:gridSpan"))
40
+ if grid_span is not None:
41
+ try:
42
+ span = max(1, int(grid_span.get(qn("w:val"), "1")))
43
+ except (TypeError, ValueError):
44
+ span = 1
45
+ vm = tcPr.find(qn("w:vMerge"))
46
+ if vm is not None:
47
+ vmerge = "restart" if vm.get(qn("w:val")) == "restart" else "continue"
48
+ return span, vmerge
49
+
50
+
51
+ def build_cellmap(tbl):
52
+ """返回 (trs, cellmap, ncols)。cellmap[r][c] 为 GridPos 或 None。"""
53
+ trs = tbl.findall(qn("w:tr"))
54
+ grid = tbl.find(qn("w:tblGrid"))
55
+ ncols = len(grid.findall(qn("w:gridCol"))) if grid is not None else 0
56
+ ncols = max(ncols, 1)
57
+ cellmap: list[list[GridPos | None]] = []
58
+ for tr in trs:
59
+ row: list[GridPos | None] = [None] * ncols
60
+ col = 0
61
+ for tc in tr.findall(qn("w:tc")):
62
+ span, vmerge = parse_tc_props(tc)
63
+ while col < len(row) and row[col] is not None:
64
+ col += 1
65
+ if col + span > len(row):
66
+ row.extend([None] * (col + span - len(row)))
67
+ if vmerge == "continue":
68
+ for k in range(span):
69
+ row[col + k] = GridPos(None, False, "continue")
70
+ else:
71
+ for k in range(span):
72
+ row[col + k] = GridPos(tc, k == 0, vmerge, span)
73
+ col += span
74
+ cellmap.append(row)
75
+ ncols = max([len(row) for row in cellmap] + [ncols])
76
+ for row in cellmap:
77
+ row.extend([None] * (ncols - len(row)))
78
+ return trs, cellmap, ncols
79
+
80
+
81
+ def compute_merges(cellmap) -> list[tuple[int, int, int, int]]:
82
+ """返回 (起始行, 起始列, 行跨度, 列跨度)。"""
83
+ merges = []
84
+ for r, row in enumerate(cellmap):
85
+ for c, pos in enumerate(row):
86
+ if pos is None or not pos.owner:
87
+ continue
88
+ colspan = pos.span
89
+ rowspan = 1
90
+ if pos.vmerge == "restart":
91
+ rr = r + 1
92
+ while rr < len(cellmap):
93
+ nxt = cellmap[rr][c]
94
+ if nxt is None or nxt.vmerge != "continue":
95
+ break
96
+ rowspan += 1
97
+ rr += 1
98
+ merges.append((r, c, rowspan, colspan))
99
+ return merges
100
+
101
+
102
+ def cell_text(tc) -> str:
103
+ if tc is None:
104
+ return ""
105
+ parts = []
106
+ for p in tc.findall(qn("w:p")):
107
+ parts.append("".join(t.text or "" for t in p.iter(qn("w:t"))))
108
+ return "\n".join(parts)
109
+
110
+
111
+ def para_text(p) -> str:
112
+ return "".join(t.text or "" for t in p.iter(qn("w:t")))
113
+
114
+
115
+ def text_grid(tbl, cellmap) -> list[list[str]]:
116
+ grid = []
117
+ for row in cellmap:
118
+ grid.append([cell_text(pos.tc) if (pos is not None and pos.owner) else None for pos in row])
119
+ return grid
120
+
121
+
122
+ def header_rows(trs) -> set[int]:
123
+ result = set()
124
+ for idx, tr in enumerate(trs):
125
+ trPr = tr.find(qn("w:trPr"))
126
+ if trPr is not None and trPr.find(qn("w:tblHeader")) is not None:
127
+ result.add(idx)
128
+ return result
129
+
130
+
131
+ def cell_alignment(tc) -> tuple[str, str, bool]:
132
+ horizontal = "left"
133
+ for p in tc.findall(qn("w:p")):
134
+ pPr = p.find(qn("w:pPr"))
135
+ if pPr is None:
136
+ continue
137
+ jc = pPr.find(qn("w:jc"))
138
+ if jc is not None:
139
+ horizontal = JC_MAP.get(jc.get(qn("w:val")), "left")
140
+ break
141
+ vertical = "top"
142
+ tcPr = tc.find(qn("w:tcPr"))
143
+ if tcPr is not None:
144
+ va = tcPr.find(qn("w:vAlign"))
145
+ if va is not None:
146
+ vertical = VA_MAP.get(va.get(qn("w:val")), "top")
147
+ multiline = "\n" in cell_text(tc)
148
+ return horizontal, vertical, multiline
149
+
150
+
151
+ def table_borders(tbl) -> dict[str, str | None]:
152
+ """读取表级边框,作为 Excel 边框的默认值。"""
153
+ default = {"top": "thin", "bottom": "thin", "left": None, "right": None, "insideH": "dotted", "insideV": "dotted"}
154
+ tblPr = tbl.find(qn("w:tblPr"))
155
+ if tblPr is None:
156
+ return default
157
+ borders = tblPr.find(qn("w:tblBorders"))
158
+ if borders is None:
159
+ return default
160
+ result = dict(default)
161
+ for side in ("top", "left", "bottom", "right", "insideH", "insideV"):
162
+ el = borders.find(qn(f"w:{side}"))
163
+ if el is None:
164
+ continue
165
+ val = el.get(qn("w:val"))
166
+ if val in (None, "nil", "none"):
167
+ result[side] = None
168
+ else:
169
+ result[side] = BORDER_MAP.get(val, "thin")
170
+ return result
171
+
172
+
173
+ def explicit_borders(tc) -> dict[str, str | None]:
174
+ result: dict[str, str | None] = {}
175
+ tcPr = tc.find(qn("w:tcPr"))
176
+ if tcPr is None:
177
+ return result
178
+ borders = tcPr.find(qn("w:tcBorders"))
179
+ if borders is None:
180
+ return result
181
+ for side in ("top", "left", "bottom", "right"):
182
+ el = borders.find(qn(f"w:{side}"))
183
+ if el is None:
184
+ continue
185
+ val = el.get(qn("w:val"))
186
+ result[side] = None if val in (None, "nil", "none") else BORDER_MAP.get(val, "thin")
187
+ return result
188
+
189
+
190
+ def position_sides(borders: dict, r: int, c: int, nrows: int, ncols: int) -> dict[str, str | None]:
191
+ return {
192
+ "top": borders["top"] if r == 0 else borders["insideH"],
193
+ "bottom": borders["bottom"] if r == nrows - 1 else borders["insideH"],
194
+ "left": borders["left"] if c == 0 else borders["insideV"],
195
+ "right": borders["right"] if c == ncols - 1 else borders["insideV"],
196
+ }
197
+
198
+
199
+ def para_first_run_rpr(p_el):
200
+ """取段落第一个 run 的 rPr(没有 run 时退回段落标记的 rPr)。"""
201
+ if p_el is None:
202
+ return None
203
+ for run in p_el.findall(qn("w:r")):
204
+ rPr = run.find(qn("w:rPr"))
205
+ if rPr is not None:
206
+ return copy.deepcopy(rPr)
207
+ pPr = p_el.find(qn("w:pPr"))
208
+ if pPr is not None:
209
+ rPr = pPr.find(qn("w:rPr"))
210
+ if rPr is not None:
211
+ return copy.deepcopy(rPr)
212
+ return None
@@ -0,0 +1,291 @@
1
+ """高亮标记层:把 Word 里的高亮文字识别成“标记”,并做可定位、可写回的锚点。
2
+
3
+ 约定:
4
+ * 高亮(``w:highlight``,任意颜色)视为“待处理位置”的输入标记;
5
+ * 每个标记(同一段落内连续的高亮 run 合并为一个)用一个不可见书签 ``MRK_0001`` 定位;
6
+ * 书签只做锚点,不修改任何文字;同步写回时才按 Excel 内容替换文字并去掉高亮。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass, field
13
+
14
+ from docx.oxml import OxmlElement
15
+ from docx.oxml.ns import qn
16
+ from docx.opc.constants import RELATIONSHIP_TYPE as RT
17
+
18
+ from .docx_bookmarks import bookmark_names, next_bookmark_id
19
+
20
+ MARK_PREFIX = "MRK_"
21
+ MARK_NAME_RE = re.compile(rf"^{MARK_PREFIX}\d{{4}}$")
22
+
23
+
24
+ @dataclass
25
+ class Mark:
26
+ """一个高亮标记。"""
27
+
28
+ index: int # 1 基序号(导出为 M01、M02…)
29
+ p_el: object # 所在段落元素
30
+ children: list = field(default_factory=list) # 组成该标记的段落子元素(run 或 hyperlink)
31
+ runs: list = field(default_factory=list) # 组成该标记的 run 列表
32
+ bookmark: str = "" # 锚点书签名(MRK_xxxx)
33
+ text: str = "" # 标记当前文字
34
+ context: str = "" # 所在段落文本(截断,便于在 Excel 里辨认)
35
+ location: str = "" # 位置描述:正文 第N段 / 表N
36
+
37
+
38
+ def _highlight_val(r_el) -> str | None:
39
+ rPr = r_el.find(qn("w:rPr"))
40
+ if rPr is None:
41
+ return None
42
+ hl = rPr.find(qn("w:highlight"))
43
+ if hl is None:
44
+ return None
45
+ return hl.get(qn("w:val"))
46
+
47
+
48
+ def run_highlighted(r_el) -> bool:
49
+ return _highlight_val(r_el) not in (None, "none")
50
+
51
+
52
+ def _payload_run(r_el) -> bool:
53
+ """单个 run 元素是否是高亮标记的一部分。"""
54
+ return r_el.tag == qn("w:r") and run_highlighted(r_el)
55
+
56
+
57
+ def _payload_of_child(child) -> list:
58
+ """把一个段落子元素(run 或 hyperlink)转成“标记 run 列表”;不是标记则返回空。"""
59
+ if child.tag == qn("w:r"):
60
+ return [child] if _payload_run(child) else []
61
+ if child.tag == qn("w:hyperlink"):
62
+ runs = [r for r in child.iter(qn("w:r"))]
63
+ if runs and all(_payload_run(r) for r in runs):
64
+ return runs
65
+ return []
66
+
67
+
68
+ def _run_texts(runs: list) -> str:
69
+ return "".join("".join(t.text or "" for t in r.iter(qn("w:t"))) for r in runs)
70
+
71
+
72
+ def _bookmark_ranges_in_paragraph(p_el, prefix: str = "") -> list[tuple[str, int, int]]:
73
+ """返回段落内的书签范围 ``[(名字, 起始子元素下标, 结束子元素下标)]``。"""
74
+ children = list(p_el.iterchildren())
75
+ starts: dict[str, tuple[str, int]] = {}
76
+ ranges: list[tuple[str, int, int]] = []
77
+ for index, child in enumerate(children):
78
+ if child.tag == qn("w:bookmarkStart"):
79
+ name = child.get(qn("w:name")) or ""
80
+ if not prefix or name.startswith(prefix):
81
+ starts[child.get(qn("w:id"))] = (name, index)
82
+ elif child.tag == qn("w:bookmarkEnd"):
83
+ key = child.get(qn("w:id"))
84
+ if key in starts:
85
+ name, start = starts.pop(key)
86
+ ranges.append((name, start, index))
87
+ return ranges
88
+
89
+
90
+ def _scan_paragraph(p_el, location: str, marks: list[Mark]) -> None:
91
+ children = list(p_el.iterchildren())
92
+ existing = {start: name for name, start, _end in _bookmark_ranges_in_paragraph(p_el, MARK_PREFIX)}
93
+ paragraph_text = "".join(t.text or "" for t in p_el.iter(qn("w:t"))).strip()
94
+
95
+ group: list = []
96
+ group_start = 0
97
+ for index, child in enumerate(children):
98
+ payload = _payload_of_child(child)
99
+ if payload:
100
+ if not group:
101
+ group_start = index
102
+ group.append((child, payload))
103
+ continue
104
+ if group:
105
+ _emit_mark(p_el, children, group, group_start, index - 1, location, paragraph_text, existing, marks)
106
+ group = []
107
+ if group:
108
+ _emit_mark(p_el, children, group, group_start, len(children) - 1, location, paragraph_text, existing, marks)
109
+
110
+
111
+ def _emit_mark(p_el, children, group, start_index, end_index, location, paragraph_text, existing, marks) -> None:
112
+ runs: list = []
113
+ for _child, payload in group:
114
+ runs.extend(payload)
115
+ if not runs:
116
+ return
117
+ mark = Mark(
118
+ index=len(marks) + 1,
119
+ p_el=p_el,
120
+ children=[child for child, _payload in group],
121
+ runs=runs,
122
+ text=_run_texts(runs),
123
+ context=paragraph_text[:80],
124
+ location=location,
125
+ )
126
+ # 复用已经存在的 MRK_ 书签(重复导出时保持稳定)
127
+ name = existing.get(start_index - 1)
128
+ if name:
129
+ mark.bookmark = name
130
+ marks.append(mark)
131
+
132
+
133
+ def find_marks(doc) -> list[Mark]:
134
+ """按文档顺序找出所有高亮标记(正文段落与表格单元格内的段落都算)。"""
135
+ marks: list[Mark] = []
136
+ for p_el, location in iter_paragraph_locations(doc):
137
+ _scan_paragraph(p_el, location, marks)
138
+ return marks
139
+
140
+
141
+ def iter_paragraph_locations(doc):
142
+ """按文档顺序产出 ``(段落元素, 位置描述)``;表格内段落标为“表N”,其余标为“正文 第N段”。"""
143
+ para_no = 0
144
+ table_no = 0
145
+ for child in doc.element.body.iterchildren():
146
+ tag = child.tag.split("}")[1]
147
+ if tag == "p":
148
+ para_no += 1
149
+ yield child, f"正文 第{para_no}段"
150
+ elif tag == "tbl":
151
+ table_no += 1
152
+ for p_el in child.iter(qn("w:p")):
153
+ yield p_el, f"表{table_no}"
154
+
155
+
156
+ def processed_marks(doc, pending: set[str]) -> list[dict]:
157
+ """找出“已处理”的标记:书签仍在文档里,但该处已不再带高亮(通常是同步过)。"""
158
+ result: list[dict] = []
159
+ for p_el, location in iter_paragraph_locations(doc):
160
+ for name, start, end in _bookmark_ranges_in_paragraph(p_el, MARK_PREFIX):
161
+ if not name or name in pending:
162
+ continue
163
+ children = list(p_el.iterchildren())[start + 1 : end]
164
+ text = "".join(
165
+ "".join(t.text or "" for t in child.iter(qn("w:t"))) for child in children
166
+ )
167
+ result.append({"bookmark": name, "text": text.strip(), "location": location})
168
+ return result
169
+
170
+
171
+ def ensure_mark_bookmarks(doc, marks: list[Mark]) -> int:
172
+ """给还没有书签的标记插入 ``MRK_xxxx`` 锚点,返回新建数量。"""
173
+ existing = bookmark_names(doc.element.body)
174
+ numbers = [int(name[len(MARK_PREFIX):]) for name in existing if MARK_NAME_RE.match(name)]
175
+ next_no = (max(numbers) + 1) if numbers else 1
176
+ bookmark_id = next_bookmark_id(doc)
177
+ created = 0
178
+ for mark in marks:
179
+ if mark.bookmark:
180
+ continue
181
+ name = f"{MARK_PREFIX}{next_no:04d}"
182
+ while name in existing:
183
+ next_no += 1
184
+ name = f"{MARK_PREFIX}{next_no:04d}"
185
+ next_no += 1
186
+ start = OxmlElement("w:bookmarkStart")
187
+ start.set(qn("w:id"), str(bookmark_id))
188
+ start.set(qn("w:name"), name)
189
+ end = OxmlElement("w:bookmarkEnd")
190
+ end.set(qn("w:id"), str(bookmark_id))
191
+ first = mark.children[0]
192
+ last = mark.children[-1]
193
+ first.addprevious(start)
194
+ last.addnext(end)
195
+ mark.bookmark = name
196
+ existing.add(name)
197
+ bookmark_id += 1
198
+ created += 1
199
+ return created
200
+
201
+
202
+ def mark_payload_by_bookmark(doc, name: str):
203
+ """按书签名找标记:返回 ``(段落元素, 标记子元素列表, run 列表)``;找不到返回 None。"""
204
+ for p_el in doc.element.body.iter(qn("w:p")):
205
+ for range_name, start, end in _bookmark_ranges_in_paragraph(p_el):
206
+ if range_name != name:
207
+ continue
208
+ children = list(p_el.iterchildren())[start + 1 : end]
209
+ runs: list = []
210
+ for child in children:
211
+ if child.tag == qn("w:r"):
212
+ runs.append(child)
213
+ elif child.tag == qn("w:hyperlink"):
214
+ runs.extend(child.iter(qn("w:r")))
215
+ return p_el, children, runs
216
+ return None
217
+
218
+
219
+ def _remove_highlight(r_el) -> None:
220
+ rPr = r_el.find(qn("w:rPr"))
221
+ if rPr is None:
222
+ return
223
+ hl = rPr.find(qn("w:highlight"))
224
+ if hl is not None:
225
+ rPr.remove(hl)
226
+
227
+
228
+ def apply_mark_change(
229
+ part, p_el, children: list, runs: list, new_text: str, link: str, keep_highlight: bool = False
230
+ ) -> str:
231
+ """把标记写回:替换文字(保留格式)、按需加超链接、去掉高亮。
232
+
233
+ ``keep_highlight=True`` 时保留该处高亮(便于复核),其余行为相同。
234
+ 返回 ``changed`` / ``unchanged`` / ``deleted``。
235
+ """
236
+ if not runs:
237
+ return "deleted"
238
+ current_text = _run_texts(runs)
239
+ target_text = new_text if new_text != "" else current_text
240
+ if new_text == "" and link == "":
241
+ return "unchanged"
242
+
243
+ # 先看当前是否已经是超链接、指向哪里(用于幂等判断)
244
+ existing_link = ""
245
+ for child in children:
246
+ if child.tag == qn("w:hyperlink"):
247
+ rel_id = child.get(qn("r:id"))
248
+ rel = part.rels.get(rel_id) if rel_id else None
249
+ existing_link = rel.target_ref if rel is not None else ""
250
+ break
251
+
252
+ highlight_pending = (not keep_highlight) and any(run_highlighted(r) for r in runs)
253
+ changed = current_text != target_text or (link or "") != (existing_link or "") or highlight_pending
254
+ if not changed:
255
+ return "unchanged"
256
+
257
+ # 解开已有超链接,改由第一个 run 承载文字
258
+ for child in list(children):
259
+ if child.tag == qn("w:hyperlink"):
260
+ for r in list(child.iter(qn("w:r"))):
261
+ if r.getparent() is child:
262
+ child.addprevious(r)
263
+ p_el.remove(child)
264
+ runs = [r for r in runs if r.getparent() is not None]
265
+ if not runs:
266
+ return "deleted"
267
+
268
+ keep = runs[0]
269
+ texts = keep.findall(qn("w:t"))
270
+ for index, node in enumerate(texts):
271
+ node.text = target_text if index == 0 else ""
272
+ node.set(qn("xml:space"), "preserve")
273
+ if not texts:
274
+ node = OxmlElement("w:t")
275
+ node.text = target_text
276
+ node.set(qn("xml:space"), "preserve")
277
+ keep.append(node)
278
+ if not keep_highlight:
279
+ _remove_highlight(keep)
280
+ for extra in runs[1:]:
281
+ parent = extra.getparent()
282
+ if parent is not None:
283
+ parent.remove(extra)
284
+
285
+ if link:
286
+ hyperlink = OxmlElement("w:hyperlink")
287
+ hyperlink.set(qn("r:id"), part.relate_to(link, RT.HYPERLINK, is_external=True))
288
+ hyperlink.set(qn("w:history"), "1")
289
+ keep.addprevious(hyperlink)
290
+ hyperlink.append(keep)
291
+ return "changed"