python-hwpx 6.11.0__py3-none-any.whl → 6.12.0__py3-none-any.whl

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 (65) hide show
  1. hwpx/_document/_legacy.py +2 -2
  2. hwpx/_document/headings.py +5 -7
  3. hwpx/_document/layout.py +43 -3
  4. hwpx/_document/ns/fields.py +1 -1
  5. hwpx/_document/ns/tables.py +7 -1
  6. hwpx/_document/ns/text.py +79 -0
  7. hwpx/_document/persistence.py +20 -0
  8. hwpx/_document/text_blocks.py +385 -0
  9. hwpx/body_patch.py +172 -32
  10. hwpx/capabilities.py +46 -9
  11. hwpx/data/contract_docs/support-matrix.md +11 -7
  12. hwpx/document.py +49 -12
  13. hwpx/equation/authoring.py +2 -0
  14. hwpx/equation/eqedit.py +5 -1
  15. hwpx/equation/mathml.py +24 -2
  16. hwpx/errors.py +20 -3
  17. hwpx/form_fit/_glyph_table.json.gz +0 -0
  18. hwpx/form_fit/_glyph_table.py +52 -12000
  19. hwpx/hwp5/package.py +31 -2
  20. hwpx/hwp5/summary.py +27 -2
  21. hwpx/ingest/base.py +7 -1
  22. hwpx/ingest/hwpx_converter.py +153 -2
  23. hwpx/layout/_page_measure.py +3009 -0
  24. hwpx/layout/line_cache.py +33 -2
  25. hwpx/layout/pages.py +130 -2931
  26. hwpx/objects/checkbox.py +1 -1
  27. hwpx/opc/package.py +110 -32
  28. hwpx/opc/xml_utils.py +19 -1
  29. hwpx/oxml/_paragraph_text_edit.py +51 -1
  30. hwpx/oxml/document_parts.py +3 -1
  31. hwpx/oxml/drop_cap.py +11 -1
  32. hwpx/oxml/header_part.py +51 -18
  33. hwpx/oxml/paragraph.py +35 -1
  34. hwpx/oxml/run.py +13 -1
  35. hwpx/oxml/section.py +143 -4
  36. hwpx/oxml/simple_parts.py +23 -1
  37. hwpx/oxml/table.py +37 -4
  38. hwpx/oxml/table_merge.py +85 -1
  39. hwpx/oxml/table_sizes.py +37 -0
  40. hwpx/oxml/table_structure.py +10 -3
  41. hwpx/patch.py +77 -9
  42. hwpx/table_patch.py +66 -73
  43. hwpx/templates.py +66 -0
  44. hwpx/tools/archive_cli.py +6 -13
  45. hwpx/tools/document_viewer.py +2 -2
  46. hwpx/tools/exporter.py +34 -3
  47. hwpx/tools/format_rules.py +530 -0
  48. hwpx/tools/layout_preview.py +60 -5
  49. hwpx/tools/mail_merge.py +24 -1
  50. hwpx/tools/markdown_export.py +64 -7
  51. hwpx/tools/markdown_import.py +473 -0
  52. hwpx/tools/object_finder.py +3 -2
  53. hwpx/tools/package_validator.py +12 -2
  54. hwpx/tools/recover.py +5 -1
  55. hwpx/tools/repair.py +9 -12
  56. hwpx/tools/table_navigation.py +53 -36
  57. hwpx/tools/text_extractor.py +44 -1
  58. hwpx/tools/toc_fidelity.py +4 -1
  59. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/METADATA +16 -3
  60. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/RECORD +65 -60
  61. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/entry_points.txt +1 -0
  62. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/WHEEL +0 -0
  63. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/licenses/LICENSE +0 -0
  64. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/licenses/NOTICE +0 -0
  65. {python_hwpx-6.11.0.dist-info → python_hwpx-6.12.0.dist-info}/top_level.txt +0 -0
hwpx/_document/_legacy.py CHANGED
@@ -1361,7 +1361,7 @@ class _LegacyFacade:
1361
1361
  break
1362
1362
  return replacements
1363
1363
 
1364
- @_moved("doc.fields.check_box(...).checked")
1364
+ @_moved("doc.fields.set_check_box")
1365
1365
  def set_check_box(
1366
1366
  self,
1367
1367
  checked: bool,
@@ -1721,7 +1721,7 @@ class _LegacyFacade:
1721
1721
  border_width=border_width,
1722
1722
  )
1723
1723
 
1724
- @_moved("doc.styles.style")
1724
+ @_moved("doc.styles.get")
1725
1725
  def style(self, style_id_ref: int | str | None) -> Style | None:
1726
1726
  """Return the style definition referenced by *style_id_ref*."""
1727
1727
 
@@ -170,13 +170,11 @@ def bind_outline_level(
170
170
  from . import layout as _layout
171
171
 
172
172
  _check_level(level)
173
- target = paragraph.element
174
- for index, candidate in enumerate(document.paragraphs):
175
- if candidate.element is target:
176
- _layout.set_paragraph_format(
177
- document, paragraph_index=index, outline_level=level
178
- )
179
- return
173
+ # The paragraph itself is the target: looking its index up in the list of every body paragraph,
174
+ # and resolving that index back, made a run of headings quadratic.
175
+ if _layout._body_indexes(document, [paragraph])[0] is not None:
176
+ _layout.set_paragraph_format(document, paragraphs=[paragraph], outline_level=level)
177
+ return
180
178
  # 방금 만든 문단이라 항상 찾힌다. 못 찾으면 조용히 넘어가는 대신 말한다 —
181
179
  # 개요 수준이 빠진 문단은 "번호가 안 붙는 제목"이라 무음 실패가 가장 나쁘다.
182
180
  raise HwpxLookupError( # pragma: no cover - 방어
hwpx/_document/layout.py CHANGED
@@ -232,6 +232,48 @@ def _resolve_paragraph_objects(
232
232
  return resolved
233
233
 
234
234
 
235
+ def _body_indexes(
236
+ doc: "HwpxDocument", objects: Sequence[HwpxOxmlParagraph]
237
+ ) -> list[int | None]:
238
+ """Where each paragraph object sits in ``doc.paragraphs``; ``None`` for one outside the body.
239
+
240
+ A few objects are placed by counting the paragraphs before them in their section, which reads
241
+ no other paragraph; wrapping every body paragraph to place one made a run of single-paragraph
242
+ calls (a heading per call) quadratic. Many objects, or plain ElementTree elements, go through
243
+ the list of body paragraphs once.
244
+ """
245
+
246
+ elements: list[Any] = [paragraph.element for paragraph in objects]
247
+ if len(elements) > 8 or not all(hasattr(element, "itersiblings") for element in elements):
248
+ body_index = {paragraph.element: index for index, paragraph in enumerate(doc.paragraphs)}
249
+ return [body_index.get(element) for element in elements]
250
+
251
+ section_roots: list[Any] = [section.element for section in doc.sections]
252
+ starts: list[int] = [] # body index of each section's first paragraph, filled as far as needed
253
+
254
+ def start_of(section_position: int) -> int:
255
+ while len(starts) <= section_position:
256
+ previous = len(starts) - 1
257
+ starts.append(
258
+ 0 if previous < 0
259
+ else starts[previous] + sum(1 for _ in section_roots[previous].iterchildren("{*}p"))
260
+ )
261
+ return starts[section_position]
262
+
263
+ indexes: list[int | None] = []
264
+ for element in elements:
265
+ parent = element.getparent()
266
+ position = next(
267
+ (index for index, root in enumerate(section_roots) if root is parent), None
268
+ )
269
+ if position is None or not isinstance(element.tag, str) or element.tag.rsplit("}", 1)[-1] != "p":
270
+ indexes.append(None)
271
+ continue
272
+ before = sum(1 for _ in element.itersiblings("{*}p", preceding=True))
273
+ indexes.append(start_of(position) + before)
274
+ return indexes
275
+
276
+
235
277
  def set_paragraph_format(
236
278
  doc: "HwpxDocument",
237
279
  *,
@@ -376,9 +418,7 @@ def set_paragraph_format(
376
418
  suggestion="Pass only one.",
377
419
  )
378
420
  objects = _resolve_paragraph_objects(doc, paragraphs)
379
- body = doc.paragraphs
380
- body_index = {paragraph.element: index for index, paragraph in enumerate(body)}
381
- targets = [(body_index.get(paragraph.element), paragraph) for paragraph in objects]
421
+ targets = list(zip(_body_indexes(doc, objects), objects))
382
422
  else:
383
423
  targets = list(_resolve_paragraph_targets(doc,
384
424
  paragraph_index=paragraph_index,
@@ -15,7 +15,7 @@
15
15
  id 별칭은 `field_id` 하나로, 위치 5키는 `location` 하나로 접혔다.
16
16
 
17
17
  `CheckBox.checked` 가 쓰기 가능한 속성이므로 `set_check_box` 는 사실상
18
- `doc.fields.check_box(...).checked = False` 로 대체된다. 5.x 이름은 shim 으로
18
+ `doc.fields.check_boxes[i].checked = False` 로 대체된다. 5.x 이름은 shim 으로
19
19
  살아 있고, 이 네임스페이스에도 같은 이름을 남겨 이주 중 양쪽이 겹치게 했다.
20
20
  """
21
21
 
@@ -35,7 +35,13 @@ class TablesNamespace(_Namespace):
35
35
 
36
36
  @property
37
37
  def all(self) -> list["Table"]:
38
- """문서의 모든 표를 문서 순서로."""
38
+ """본문 문단에 바로 놓인 표를 문서 순서로.
39
+
40
+ 표 칸 안의 표, 머리말·꼬리말·각주·미주·글상자 안의 표는 들어 있지 않다.
41
+ 칸 안의 표는 그 칸에서(``cell.tables``), 글까지 모두
42
+ 훑으려면 ``doc.text.blocks()``를 쓴다. ``len(doc.tables)``와
43
+ ``for table in doc.tables``도 같은 범위다.
44
+ """
39
45
 
40
46
  tables: list["Table"] = []
41
47
  for paragraph in self._doc.paragraphs:
hwpx/_document/ns/text.py CHANGED
@@ -20,7 +20,9 @@ from ._base import _Namespace
20
20
 
21
21
  if TYPE_CHECKING:
22
22
  from ...objects.highlight import Highlight
23
+ from ...tools.markdown_import import MarkdownStyle
23
24
  from ...oxml import HwpxOxmlParagraph, HwpxOxmlRun
25
+ from ..text_blocks import TextBlock, TextChangeReport, TextOutline
24
26
 
25
27
  __all__ = ["TextNamespace"]
26
28
 
@@ -122,6 +124,22 @@ class TextNamespace(_Namespace):
122
124
 
123
125
  return _persistence.export_html(self._doc, **kwargs)
124
126
 
127
+ # -- 가져오기 ----------------------------------------------------------
128
+
129
+ def append_markdown(self, markdown: str, *, style: "MarkdownStyle | None" = None) -> None:
130
+ """*markdown* 을 마지막 구역 끝에 문단·목록·표로 덧붙인다.
131
+
132
+ ``hwpx.tools.markdown_import.from_markdown`` 과 같은 부분 집합(제목 ``#``~``####``,
133
+ 문단, ``-``/``1.`` 목록, ``|`` 표, ``**굵게**``/``*기울임*``)을 쓴다.
134
+ 새 문단은 앞 문단의 서식을 물려받지 않는다. 모르는 Markdown 은 평문으로
135
+ 쓰고 오류를 내지 않는다. *style* 은
136
+ :class:`hwpx.tools.markdown_import.MarkdownStyle`.
137
+ """
138
+
139
+ from ...tools.markdown_import import append_markdown
140
+
141
+ append_markdown(self._doc, markdown, style=style)
142
+
125
143
  # -- 순회·검색 ---------------------------------------------------------
126
144
 
127
145
  def runs(self) -> Iterator["HwpxOxmlRun"]:
@@ -154,6 +172,67 @@ class TextNamespace(_Namespace):
154
172
  )
155
173
  ]
156
174
 
175
+ # -- id 붙은 글 덩어리 ---------------------------------------------------
176
+
177
+ def blocks(self) -> Iterator["TextBlock"]:
178
+ """본문 문단과 표 칸 문단(칸 안 표 포함)을 문서 순서대로, 안정적인 id와 함께 내놓는다.
179
+
180
+ id는 위치로 정해진다: ``s0p16`` (0번 구역의 16번 본문 문단, 번호는 0부터), ``s0p16t0r3c0q0`` (그 문단의 0번 표,
181
+ 3행 0열 칸의 0번 문단), 칸 안 표는 ``…q0t0r1c1q0`` 처럼 이어진다. 행·열은 칸의 주소라
182
+ 병합 칸은 대표 칸에서 한 번만 나온다. 저장·재열기 뒤에도 같고, 앞쪽에 문단·표·칸을
183
+ 넣거나 지울 때만 바뀐다. 머리말·꼬리말·각주·메모·글상자는 포함하지 않는다.
184
+ """
185
+
186
+ from ..text_blocks import iter_text_blocks
187
+
188
+ return iter_text_blocks(self._doc)
189
+
190
+ def outline(
191
+ self,
192
+ *,
193
+ max_chars: int = 8000,
194
+ max_items: int | None = None,
195
+ max_block_chars: int = 200,
196
+ after: str | None = None,
197
+ ) -> "TextOutline":
198
+ """글자가 있는 덩어리를 ``{"id", "where", "text"}`` 목록으로, 글자 예산 안에서 돌려준다.
199
+
200
+ 빈 문단은 빼고, 탭·줄 바꿈은 공백으로, 제어 문자는 지운다. *max_block_chars* 보다 긴
201
+ 덩어리는 앞부분만 남기고 ``…`` 로 끝낸다(``"truncated": True``). *max_chars* 는 각 항목의
202
+ id·위치·글자를 센다. 예산이나 *max_items* 가 다하면 항목 단위로 멈추고 ``complete`` 가
203
+ ``False``, ``next_after`` 가 마지막 id다 — 다음 쪽은 ``after=next_after`` 로 읽는다. 한 쪽에는 예산보다 큰 항목이라도 적어도 하나가 들어간다.
204
+ ``to_text()`` 는 한 줄에 한 항목인 가장 짧은 프롬프트 형태다.
205
+ """
206
+
207
+ from ..text_blocks import outline
208
+
209
+ return outline(
210
+ self._doc,
211
+ max_chars=max_chars,
212
+ max_items=max_items,
213
+ max_block_chars=max_block_chars,
214
+ after=after,
215
+ )
216
+
217
+ def apply_changes(
218
+ self,
219
+ changes: "dict[str, str]",
220
+ *,
221
+ check_overflow: bool = True,
222
+ ) -> "TextChangeReport":
223
+ """``{id: 새 글}`` 을 한 번에 적용하고 id마다 결과를 보고한다.
224
+
225
+ 모든 id를 먼저 찾은 뒤 쓴다. 없는 id는 ``unknown_ids`` 로 보고하고 나머지는 적용한다.
226
+ 한 런 안에서 끝나는 바꿈은 런과 컨트롤을 모두 지키고, 서식이 다른 런에 걸치거나 탭·줄
227
+ 바꿈을 넣는 바꿈은 문단 첫 런의 서식으로 쓴다(``rewritten``). *check_overflow* 면 바뀐 칸을
228
+ 전후로 재어, 칸이 품는 줄보다 많이(그리고 전보다 많이) 필요할 것으로 추정되는 칸을
229
+ ``overflow`` 에 넣는다 — 렌더가 아니라 form-fit 측정기의 추정이다.
230
+ """
231
+
232
+ from ..text_blocks import apply_text_changes
233
+
234
+ return apply_text_changes(self._doc, changes, check_overflow=check_overflow)
235
+
157
236
  # -- 치환 --------------------------------------------------------------
158
237
 
159
238
  def replace(
@@ -435,6 +435,7 @@ def save_report(
435
435
  before=before,
436
436
  edit_mask=edit_mask,
437
437
  ledger=ledger,
438
+ open_safety=_serialize_open_safety(doc, archive_bytes),
438
439
  reference_document=doc,
439
440
  source_label="document.save_report",
440
441
  )
@@ -475,6 +476,25 @@ def to_bytes(
475
476
  return data
476
477
 
477
478
 
479
+ def _serialize_open_safety(doc: "HwpxDocument", archive_bytes: bytes) -> OpenSafetyReport | None:
480
+ """The open-safety verdict the package's save reached for exactly *archive_bytes*, in the form
481
+ the SavePipeline composes from its own run; ``None`` when the package did not validate these
482
+ bytes (the pipeline then validates them itself).
483
+
484
+ The same validation of the same bytes gives the same report, so ``save_report`` hands the
485
+ pipeline this one instead of running it a second time.
486
+ """
487
+
488
+ package = doc._package
489
+ report = getattr(package, "_verified_archive_report", None)
490
+ digest = getattr(package, "_verified_archive_digest", None)
491
+ if report is None or digest is None or not report.ok:
492
+ return None
493
+ if digest != hashlib.sha256(archive_bytes).digest():
494
+ return None
495
+ return OpenSafetyReport(ok=report.ok, summary=report.summary, detail=report.to_dict())
496
+
497
+
478
498
  def _to_bytes_raw(
479
499
  doc: "HwpxDocument",
480
500
  *,
@@ -0,0 +1,385 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Text blocks with stable ids — read a short list, write changes back by id.
3
+
4
+ A *text block* is one paragraph of the body or of a table cell (nested tables
5
+ included), in document order. Its id is positional::
6
+
7
+ s0p16 section 0, body paragraph 16
8
+ s0p16t0r3c0q0 … its table 0, the cell at row 3 / column 0, cell paragraph 0
9
+ s0p16t0r3c0q0t0r1c1q0 … a table nested in that cell paragraph
10
+
11
+ ``r``/``c`` are the cell's own address (``hp:cellAddr``), so a merged cell
12
+ appears once, at its anchor. Ids survive save and reopen; they change only
13
+ when paragraphs, tables or cells are inserted or removed before them.
14
+
15
+ This is the engine side of the "the model reads a short list and writes
16
+ changes, code assembles the document" workflow: :func:`outline` makes the
17
+ budgeted list, :func:`apply_text_changes` puts the answers back.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ import unicodedata
24
+ from dataclasses import dataclass, field, replace
25
+ from typing import TYPE_CHECKING, Any, Iterator, Mapping
26
+
27
+ if TYPE_CHECKING:
28
+ from ..document import HwpxDocument
29
+ from ..oxml import HwpxOxmlParagraph, HwpxOxmlTableCell
30
+
31
+ __all__ = [
32
+ "TextBlock",
33
+ "TextChangeReport",
34
+ "TextOutline",
35
+ "apply_text_changes",
36
+ "iter_text_blocks",
37
+ "outline",
38
+ ]
39
+
40
+ _WHITESPACE_RE = re.compile(r"\s+")
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class TextBlock:
45
+ """One body or table-cell paragraph with its stable id."""
46
+
47
+ id: str
48
+ #: Human-readable position, e.g. ``"본문 17문단"`` or ``"표2 4행 1열"``.
49
+ location: str
50
+ paragraph: "HwpxOxmlParagraph"
51
+ #: The table cell holding the paragraph, ``None`` for a body paragraph.
52
+ cell: "HwpxOxmlTableCell | None" = None
53
+
54
+ @property
55
+ def text(self) -> str:
56
+ return self.paragraph.text
57
+
58
+ @property
59
+ def in_table(self) -> bool:
60
+ return self.cell is not None
61
+
62
+
63
+ def _cells_in_order(table: Any) -> list[tuple[int, int, Any]]:
64
+ """Each physical cell once (a merged cell at its anchor), row by row, with its address.
65
+
66
+ The address is the cell's ``hp:cellAddr``. A table where a cell has none, or
67
+ two cells share one, is addressed by physical position instead (row element,
68
+ cell element within it) so its ids stay unique.
69
+ """
70
+
71
+ cells = [(row_index, cell_index, cell) for row_index, row in enumerate(table.rows) for cell_index, cell in enumerate(row.cells)]
72
+ addresses = [cell.address if cell._addr_element() is not None else None for _r, _c, cell in cells]
73
+ if None in addresses or len(set(addresses)) != len(addresses):
74
+ return cells
75
+ return [(row, col, cell) for (row, col), (_r, _c, cell) in zip(addresses, cells)] # type: ignore[misc]
76
+
77
+
78
+ def _walk_cell_tables(
79
+ paragraph: "HwpxOxmlParagraph",
80
+ prefix: str,
81
+ where: str,
82
+ table_numbers: list[int] | None,
83
+ ) -> Iterator[TextBlock]:
84
+ for table_index, table in enumerate(paragraph.tables):
85
+ if table_numbers is not None:
86
+ table_numbers[0] += 1
87
+ label = f"표{table_numbers[0]}"
88
+ else:
89
+ label = f"{where} 안 표{table_index + 1}"
90
+ for row, col, cell in _cells_in_order(table):
91
+ cell_prefix = f"{prefix}t{table_index}r{row}c{col}"
92
+ cell_where = f"{label} {row + 1}행 {col + 1}열"
93
+ for cell_paragraph_index, cell_paragraph in enumerate(cell.paragraphs):
94
+ block_id = f"{cell_prefix}q{cell_paragraph_index}"
95
+ yield TextBlock(block_id, cell_where, cell_paragraph, cell)
96
+ yield from _walk_cell_tables(cell_paragraph, block_id, cell_where, None)
97
+
98
+
99
+ def iter_text_blocks(document: "HwpxDocument") -> Iterator[TextBlock]:
100
+ """Yield every body paragraph and table-cell paragraph in document order.
101
+
102
+ Top-level tables are numbered in document order across sections (``표1``,
103
+ ``표2``…); a nested table is named inside its cell (``표2 1행 1열 안 표1``).
104
+ Headers, footers, notes, memos and text boxes are not included.
105
+ """
106
+
107
+ sections = document.sections
108
+ table_numbers = [0]
109
+ for section_index, section in enumerate(sections):
110
+ section_label = f"{section_index + 1}구역 " if len(sections) > 1 else ""
111
+ for paragraph_index, paragraph in enumerate(section.paragraphs):
112
+ block_id = f"s{section_index}p{paragraph_index}"
113
+ yield TextBlock(block_id, f"{section_label}본문 {paragraph_index + 1}문단", paragraph)
114
+ yield from _walk_cell_tables(paragraph, block_id, "", table_numbers)
115
+
116
+
117
+ # --------------------------------------------------------------------------- #
118
+ # outline: the budgeted short list
119
+ # --------------------------------------------------------------------------- #
120
+ class TextOutline(list): # type: ignore[type-arg]
121
+ """``list[dict]`` of ``{"id", "where", "text"}`` items, plus paging facts.
122
+
123
+ It is a plain list for JSON (``json.dumps`` writes the items only); the
124
+ attributes say whether the budget cut it short and where to resume.
125
+ """
126
+
127
+ #: ``True`` when every non-empty block fit in the budget.
128
+ complete: bool
129
+ #: Pass as ``after=`` to read the next page; ``None`` when complete.
130
+ next_after: str | None
131
+ #: Non-empty blocks after the ``after`` cursor, listed or not.
132
+ total: int
133
+
134
+ def __init__(self, items: list[dict[str, Any]], *, complete: bool, next_after: str | None, total: int):
135
+ super().__init__(items)
136
+ self.complete = complete
137
+ self.next_after = next_after
138
+ self.total = total
139
+
140
+ def to_text(self) -> str:
141
+ """One line per item — ``[id] where: text`` — the cheapest prompt form."""
142
+
143
+ lines = [f"[{item['id']}] {item['where']}: {item['text']}" for item in self]
144
+ if not self.complete:
145
+ lines.append(f"… {self.total - len(self)} more (after={self.next_after})")
146
+ return "\n".join(lines)
147
+
148
+
149
+ def _clean(text: str) -> str:
150
+ """Tabs and line breaks become spaces; other control characters go."""
151
+
152
+ text = "".join(" " if ch in "\t\n\r" else ch for ch in text if ch in "\t\n\r" or unicodedata.category(ch) != "Cc")
153
+ return _WHITESPACE_RE.sub(" ", text).strip()
154
+
155
+
156
+ def outline(
157
+ document: "HwpxDocument",
158
+ *,
159
+ max_chars: int = 8000,
160
+ max_items: int | None = None,
161
+ max_block_chars: int = 200,
162
+ after: str | None = None,
163
+ ) -> TextOutline:
164
+ """The non-empty text blocks as a short list that fits *max_chars*.
165
+
166
+ Empty paragraphs are left out, tabs and line breaks become spaces and
167
+ control characters are dropped, and a block longer than *max_block_chars*
168
+ keeps its start and ends with ``…`` (its item gets ``"truncated": True``).
169
+ *max_chars* counts each item's id, location and text. When the budget or
170
+ *max_items* runs out the outline stops at a whole item: ``complete`` is
171
+ ``False`` and ``next_after`` is the last id listed, to pass as *after* for
172
+ the next page. A page always holds at least one item, even one larger than
173
+ *max_chars*.
174
+ """
175
+
176
+ from ..errors import HwpxLookupError, HwpxValueError
177
+
178
+ for name, value in (("max_chars", max_chars), ("max_block_chars", max_block_chars), ("max_items", max_items)):
179
+ if value is not None and value < 1:
180
+ raise HwpxValueError(
181
+ f"{name} must be >= 1",
182
+ code="text-outline-budget",
183
+ context={name: value},
184
+ suggestion="Pass a positive budget, or leave max_items unset for no item cap.",
185
+ )
186
+
187
+ items: list[dict[str, Any]] = []
188
+ used = 0
189
+ total = 0
190
+ full = False
191
+ seen_cursor = after is None
192
+ for block in iter_text_blocks(document):
193
+ if not seen_cursor:
194
+ seen_cursor = block.id == after
195
+ continue
196
+ text = _clean(block.text)
197
+ if not text:
198
+ continue
199
+ total += 1
200
+ if full:
201
+ continue
202
+ item: dict[str, Any] = {"id": block.id, "where": block.location, "text": text}
203
+ if len(text) > max_block_chars:
204
+ item["text"] = text[: max_block_chars - 1].rstrip() + "…"
205
+ item["truncated"] = True
206
+ cost = len(block.id) + len(block.location) + len(item["text"])
207
+ # A page always holds one item, so paging moves on even when a single
208
+ # item is larger than the whole budget.
209
+ if items and (used + cost > max_chars or (max_items is not None and len(items) >= max_items)):
210
+ full = True
211
+ continue
212
+ used += cost
213
+ items.append(item)
214
+ if after is not None and not seen_cursor:
215
+ raise HwpxLookupError(
216
+ f"unknown text block id: {after!r}",
217
+ code="text-block-unknown",
218
+ context={"after": after},
219
+ suggestion="Pass the next_after of the previous page, or an id from doc.text.blocks().",
220
+ )
221
+ complete = len(items) == total
222
+ return TextOutline(
223
+ items,
224
+ complete=complete,
225
+ next_after=None if complete or not items else items[-1]["id"],
226
+ total=total,
227
+ )
228
+
229
+
230
+ # --------------------------------------------------------------------------- #
231
+ # apply_text_changes: write answers back by id
232
+ # --------------------------------------------------------------------------- #
233
+ @dataclass(slots=True)
234
+ class TextChangeReport:
235
+ """What :func:`apply_text_changes` did with each id."""
236
+
237
+ changed: list[str] = field(default_factory=list)
238
+ #: Ids the document does not have (nothing was written for them).
239
+ unknown_ids: list[str] = field(default_factory=list)
240
+ #: Ids whose text was already the requested text.
241
+ unchanged: list[str] = field(default_factory=list)
242
+ #: Changed ids whose runs could not all be kept: the edit crossed runs of
243
+ #: different formatting, or added a tab or line break. The new text took the
244
+ #: paragraph's first run's formatting.
245
+ rewritten: list[str] = field(default_factory=list)
246
+ #: Cells whose new text is estimated to need more lines than the cell holds,
247
+ #: so the row would grow: ``{"id", "where", "lines", "lineBudget",
248
+ #: "linesBefore", "confidence"}``. An estimate from the form-fit measurer,
249
+ #: not a render.
250
+ overflow: list[dict[str, Any]] = field(default_factory=list)
251
+ warnings: list[str] = field(default_factory=list)
252
+
253
+ @property
254
+ def ok(self) -> bool:
255
+ """``True`` when every id was known and no cell is estimated to overflow."""
256
+
257
+ return not self.unknown_ids and not self.overflow
258
+
259
+ def to_dict(self) -> dict[str, Any]:
260
+ return {
261
+ "ok": self.ok,
262
+ "changed": list(self.changed),
263
+ "unknownIds": list(self.unknown_ids),
264
+ "unchanged": list(self.unchanged),
265
+ "rewritten": list(self.rewritten),
266
+ "overflow": [dict(entry) for entry in self.overflow],
267
+ "warnings": list(self.warnings),
268
+ }
269
+
270
+
271
+ def _write(paragraph: "HwpxOxmlParagraph", value: str) -> bool:
272
+ """Write *value*; return ``True`` when the runs had to be rewritten."""
273
+
274
+ from ..errors import HwpxValueError
275
+
276
+ if "\t" not in value and "\n" not in value:
277
+ try:
278
+ paragraph.set_text_preserving_runs(value)
279
+ return False
280
+ except HwpxValueError:
281
+ pass
282
+ paragraph.text = value
283
+ return True
284
+
285
+
286
+ def _cell_lines(cell: Any, texts: list[str]) -> tuple[int, int | None, str]:
287
+ """Estimated lines of *texts* (one per cell paragraph) and the cell's budget."""
288
+
289
+ from ..form_fit.measure import measure, resolve_slot_metrics
290
+
291
+ # The same document handle set_cell_text(fit=...) measures with.
292
+ document = getattr(getattr(cell.table.paragraph, "section", None), "document", None)
293
+ slot = resolve_slot_metrics(cell, document, max_lines=1)
294
+ wide = replace(slot, max_lines=100_000)
295
+ lines = 0
296
+ confidence = "high"
297
+ for text in texts:
298
+ for line in text.split("\n"):
299
+ if not line:
300
+ lines += 1
301
+ continue
302
+ measured = measure(line, wide)
303
+ lines += max(1, measured.lines)
304
+ if measured.confidence != "high":
305
+ confidence = "low"
306
+ return lines, slot.height_lines(), confidence
307
+
308
+
309
+ def apply_text_changes(
310
+ document: "HwpxDocument",
311
+ changes: Mapping[str, str],
312
+ *,
313
+ check_overflow: bool = True,
314
+ ) -> TextChangeReport:
315
+ """Replace the text of each block id in *changes* and report per id.
316
+
317
+ Every id is resolved before anything is written, so an unknown id never
318
+ leaves a half-applied batch behind it: unknown ids are reported and the
319
+ rest is applied. A change that stays inside one run keeps every run and
320
+ control (:meth:`~hwpx.oxml.HwpxOxmlParagraph.set_text_preserving_runs`);
321
+ one that crosses differently formatted runs or adds a tab or line break
322
+ is written into the first run (``rewritten``). With *check_overflow*,
323
+ each changed cell is measured before and after: a cell estimated to need
324
+ more lines than it holds, and more than it needed before, is listed in
325
+ ``overflow``.
326
+ """
327
+
328
+ report = TextChangeReport()
329
+ wanted = {str(key): "" if value is None else str(value) for key, value in changes.items()}
330
+ blocks: dict[str, TextBlock] = {}
331
+ pending = set(wanted)
332
+ if pending:
333
+ for block in iter_text_blocks(document):
334
+ if block.id in pending:
335
+ blocks[block.id] = block
336
+ pending.discard(block.id)
337
+ if not pending:
338
+ break
339
+ report.unknown_ids = [key for key in wanted if key not in blocks]
340
+
341
+ # Measure the touched cells before writing.
342
+ before: dict[int, tuple[Any, str, int, int | None]] = {}
343
+ if check_overflow:
344
+ for key, block in blocks.items():
345
+ cell = block.cell
346
+ if cell is None or id(cell.element) in before or wanted[key] == block.text:
347
+ continue
348
+ try:
349
+ lines, budget, _confidence = _cell_lines(cell, [p.text for p in cell.paragraphs])
350
+ except Exception as error: # measuring must never block the edit
351
+ report.warnings.append(f"{key}: overflow not measured ({type(error).__name__})")
352
+ continue
353
+ # The room is the cell as authored: an auto-growing row measured after
354
+ # the write would count the new text into its own budget.
355
+ before[id(cell.element)] = (cell, key, lines, budget)
356
+
357
+ for key in wanted:
358
+ block = blocks.get(key)
359
+ if block is None:
360
+ continue
361
+ if block.text == wanted[key]:
362
+ report.unchanged.append(key)
363
+ continue
364
+ if _write(block.paragraph, wanted[key]):
365
+ report.rewritten.append(key)
366
+ report.changed.append(key)
367
+
368
+ for cell, key, lines_before, budget in before.values():
369
+ try:
370
+ lines, _budget_after, confidence = _cell_lines(cell, [p.text for p in cell.paragraphs])
371
+ except Exception as error: # pragma: no cover - measured once already
372
+ report.warnings.append(f"{key}: overflow not measured ({type(error).__name__})")
373
+ continue
374
+ if budget is not None and lines > budget and lines > lines_before:
375
+ report.overflow.append(
376
+ {
377
+ "id": key,
378
+ "where": blocks[key].location,
379
+ "lines": lines,
380
+ "lineBudget": budget,
381
+ "linesBefore": lines_before,
382
+ "confidence": confidence,
383
+ }
384
+ )
385
+ return report