python-hwpx 6.10.0__py3-none-any.whl → 6.11.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.
hwpx/_document/fields.py CHANGED
@@ -440,6 +440,14 @@ def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
440
440
 
441
441
 
442
442
  def _iter_field_matches(doc: "HwpxDocument", accept: Any) -> list[dict[str, Any]]:
443
+ return _field_matches_in(doc, accept, _iter_content_paragraphs(doc))
444
+
445
+
446
+ def _field_matches_in(
447
+ doc: "HwpxDocument",
448
+ accept: Any,
449
+ paragraphs: Iterator[tuple[int, int, int, Any, HwpxOxmlParagraph, list[Any]]],
450
+ ) -> list[dict[str, Any]]:
443
451
  """The fields whose ``<hp:fieldBegin>`` *accept(ctrl, field_begin)* takes, in
444
452
  document order, with their text up to the matching ``<hp:fieldEnd>``."""
445
453
 
@@ -451,7 +459,7 @@ def _iter_field_matches(doc: "HwpxDocument", accept: Any) -> list[dict[str, Any]
451
459
  paragraph_element,
452
460
  paragraph,
453
461
  runs,
454
- ) in _iter_content_paragraphs(doc):
462
+ ) in paragraphs:
455
463
  for run_index, run in enumerate(runs):
456
464
  children = list(run)
457
465
  for child_index, child in enumerate(children):
@@ -526,6 +534,22 @@ def _iter_field_matches(doc: "HwpxDocument", accept: Any) -> list[dict[str, Any]
526
534
  return matches
527
535
 
528
536
 
537
+ def _refresh_form_field_match(doc: "HwpxDocument", match: Mapping[str, Any]) -> dict[str, Any]:
538
+ """Re-read the selected field after filling it, without rebuilding unrelated payloads.
539
+
540
+ Filling can remove nested fields or following paragraphs, but retains the selected begin and everything
541
+ before it. Its paragraph location and field index therefore stay valid. Read its runs and matching end
542
+ afresh: inserting text or collapsing a span can change their indices and the result's style snapshot.
543
+ """
544
+
545
+ paragraph = match["_paragraph"]
546
+ source = (match["section_index"], match["paragraph_index"], match["paragraph_index_in_section"],
547
+ paragraph.element, paragraph, [child for child in paragraph.element if _local_name(child) == "run"])
548
+ refreshed = _field_matches_in(doc, lambda ctrl, begin: begin is match["_field_begin"], iter((source,)))[0]
549
+ refreshed["index"] = match["index"]
550
+ return refreshed
551
+
552
+
529
553
  def _form_field_from_match(doc: "HwpxDocument", match: Mapping[str, Any]) -> FormField:
530
554
  """Build the public :class:`FormField` view from an internal match payload.
531
555
 
@@ -1230,7 +1254,7 @@ def fill_form_field(
1230
1254
 
1231
1255
  _clear_form_field_layout_cache(paragraph.element)
1232
1256
  paragraph.section.mark_dirty()
1233
- updated = _iter_form_field_matches(doc)[int(match["index"])]
1257
+ updated = _refresh_form_field_match(doc, match)
1234
1258
  after_style = _field_run_style_snapshot(
1235
1259
  doc,
1236
1260
  updated["_runs"],
@@ -0,0 +1,85 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """QName-aware, bounded byte edits for text after a table in its paragraph."""
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+
8
+ from lxml import etree
9
+
10
+ from .errors import HwpxValueError
11
+ from .opc.xml_utils import _XML_MARKUP, parse_xml
12
+ from .oxml.namespaces import tag_in_family, tag_local_name
13
+
14
+
15
+ @dataclass
16
+ class _Span:
17
+ start: int
18
+ close: int
19
+ end: int
20
+
21
+
22
+ def _element_spans(source: bytes, root: etree._Element) -> dict[etree._Element, _Span]:
23
+ """Bind the secure parsed elements to original bytes without serializing."""
24
+ elements = (node for node in root.iter() if isinstance(node.tag, str))
25
+ stack: list[etree._Element] = []
26
+ spans: dict[etree._Element, _Span] = {}
27
+ for markup in _XML_MARKUP.finditer(source):
28
+ token = markup.group()
29
+ if token.startswith((b"<!", b"<?")):
30
+ continue
31
+ if token.startswith(b"</"):
32
+ element = stack.pop()
33
+ spans[element].close, spans[element].end = markup.start(), markup.end()
34
+ else:
35
+ element = next(elements)
36
+ spans[element] = _Span(markup.start(), markup.end(), markup.end())
37
+ if not token.endswith(b"/>"):
38
+ stack.append(element)
39
+ if stack or next(elements, None) is not None:
40
+ raise HwpxValueError("could not bind paragraph XML to source bytes", context={"operation": "strip_trailing_table_text"})
41
+ return spans
42
+
43
+
44
+ def _is(element: etree._Element, local: str) -> bool:
45
+ return isinstance(element.tag, str) and tag_in_family(element.tag, "paragraph") and tag_local_name(element.tag) == local
46
+
47
+
48
+ def trailing_text_edits(
49
+ source: bytes, predicate: Callable[[str], bool],
50
+ ) -> list[tuple[int, int, bytes, str]]:
51
+ """Select at most the last direct table per wrapper; every scan is bounded."""
52
+ root = parse_xml(source)
53
+ spans = _element_spans(source, root)
54
+ edits: list[tuple[int, int, bytes, str]] = []
55
+ for paragraph in root.iter():
56
+ if not _is(paragraph, "p"):
57
+ continue
58
+ children = list(paragraph)
59
+ cache_index = next((i for i, child in enumerate(children) if _is(child, "linesegarray")), None)
60
+ if cache_index is None:
61
+ continue
62
+ candidate = None
63
+ for run_index, run in enumerate(children[:cache_index]):
64
+ if _is(run, "run"):
65
+ for table_index, table in enumerate(run):
66
+ if _is(table, "tbl"):
67
+ candidate = run_index, table_index, run, table
68
+ if candidate is None:
69
+ continue
70
+ run_index, table_index, run, table = candidate
71
+ following_runs = children[run_index + 1:cache_index]
72
+ if any(not _is(item, "run") or (item.text or "").strip() or (item.tail or "").strip()
73
+ for item in following_runs) or (table.tail or "").strip() or (run.tail or "").strip():
74
+ continue
75
+ texts = list(run)[table_index + 1:]
76
+ for item in following_runs:
77
+ texts.extend(item)
78
+ if not texts or any(not _is(item, "t") or len(item) or (item.tail or "").strip() for item in texts):
79
+ continue
80
+ text = "".join(item.text or "" for item in texts).strip()
81
+ if predicate(text):
82
+ original_run = spans[run]
83
+ closing_run = source[original_run.close:original_run.end]
84
+ edits.append((spans[table].end, spans[children[cache_index]].start, closing_run, text))
85
+ return edits
@@ -45,10 +45,13 @@ stable 편집 표면의 계약을 한 곳에 모았다. 아래 표의 실패 모
45
45
  - `preserve_format=False`면 글을 받은 run 하나만 `charPrIDRef="0"`이 된다.
46
46
  - 셀 문단의 줄 배치 캐시(`hp:linesegarray`)를 지워 한/글이 줄을 다시 나누게 한다.
47
47
 
48
- `split_paragraphs=True`면 셀 문단을 **다시 만든다**. 기존 문단은 모두 지워지고
49
- (안쪽 표를 담은 문단도 함께), 줄마다 run 하나짜리 새 문단이 새 id로 생긴다.
50
- 줄 `i`는 기존 `i`번째 문단(없으면 첫 문단)의 `paraPrIDRef`·`styleIDRef`·
48
+ `split_paragraphs=True`면 셀 자신의 글 문단을 **다시 만든다**. 그 문단은 모두
49
+ 지워지고, 줄마다 run 하나짜리 새 문단이 새 id로 첫 글 문단 자리에 생긴다. 줄 `i`는
50
+ 기존 `i`번째 글 문단(없으면 첫 글 문단)의 `paraPrIDRef`·`styleIDRef`·
51
51
  `pageBreak`·`columnBreak`·`merged`와 그 문단 첫 run의 `charPrIDRef`를 이어받는다.
52
+ 안쪽 표·개체(그림, 글상자, 컨트롤 등)를 담은 문단은 자리와 담은 것을 그대로 두고 그
53
+ 문단 자신의 글만 비운다. 글 문단이 없는 셀은 새 문단을 첫 개체 문단 앞에 두고, 그
54
+ 문단의 문단 모양을 쓴다.
52
55
 
53
56
  ### 셀 여백
54
57
 
@@ -18,10 +18,10 @@ Contract provenance: specs/054-equation-authoring/evidence/p0/equation-contract.
18
18
  from __future__ import annotations
19
19
 
20
20
  from .eqedit import (
21
- _RESERVED_WORDS,
22
21
  MAX_GROUP_DEPTH,
23
22
  MAX_SOURCE_LENGTH,
24
23
  EquationConversionError,
24
+ _needs_literal_quotes,
25
25
  )
26
26
  from .tokens import (
27
27
  ACCENTS,
@@ -118,7 +118,7 @@ _ENV_TO_EQEDIT: dict[str, str] = {
118
118
  "cases": "cases",
119
119
  }
120
120
 
121
- # Bare identifier runs that would collide with EqEdit vocabulary (``_RESERVED_WORDS``)
121
+ # Bare identifier runs that would collide with EqEdit vocabulary or font prefixes
122
122
  # must be quoted so Hancom keeps them literal (reserved-word protection).
123
123
 
124
124
  # ``~`` is a space in both: a LaTeX tie and EqEdit's normal space (``\,`` is the small one, `` ` ``).
@@ -314,7 +314,7 @@ class _LatexParser:
314
314
  raise UnsupportedLatexError(f"unsupported LaTeX escape: \\{char}")
315
315
 
316
316
  def _plain_token(self, token: str) -> str:
317
- if token.isalpha() and token in _RESERVED_WORDS:
317
+ if _needs_literal_quotes(token):
318
318
  # Reserved-word protection: keep the identifier literal in Hancom.
319
319
  return f'"{token}"'
320
320
  return token
hwpx/equation/eqedit.py CHANGED
@@ -23,8 +23,8 @@ Design notes (matches Hancom EqEdit grouping semantics):
23
23
  they are. ``bold`` makes only the next atom bold (italic bold, or upright
24
24
  bold after ``rm``), and a ``rm``/``it`` right after it uses it up. Letter runs
25
25
  read as ``\\mathrm``/``\\mathbf``/``\\boldsymbol`` so a switch never comes
26
- back as a word that re-authoring would draw as letters. A switch glued to
27
- the letters after it (``rmA``) stays one identifier, as before.
26
+ back as a word that re-authoring would draw as letters. A switch at the start
27
+ of a word also applies without a space (``rmA``), as observed in Hancom.
28
28
 
29
29
  Untrusted input is bounded by :data:`MAX_SOURCE_LENGTH` and
30
30
  :data:`MAX_GROUP_DEPTH`; exceeding either raises :class:`EquationConversionError`
@@ -53,7 +53,8 @@ MAX_GROUP_DEPTH = 64
53
53
  # Words EqEdit reads as symbols, structure or font switches. The writer quotes a bare identifier that collides
54
54
  # with one (``T_{int}`` → ``T _{"int"}``, ``e^{it}`` → ``e ^{"it"}``: a lone ``it`` in a superscript switches to
55
55
  # italic and draws nothing); the reader turns such a quoted word back into plain letters.
56
- _FONT_SWITCHES = frozenset({"rm", "it", "bold", "RM", "IT", "BOLD"})
56
+ _FONT_PREFIXES = ("bold", "Bold", "BOLD", "rm", "Rm", "RM", "it", "It", "IT")
57
+ _FONT_SWITCHES = frozenset(_FONT_PREFIXES)
57
58
  # Tokens that end the current atom: a font switch right before one switches and draws nothing.
58
59
  _ATOM_END = frozenset({"}", "&", "#", "RIGHT", "^", "_", "over", "atop", "choose"})
59
60
  _RESERVED_WORDS = (
@@ -104,6 +105,11 @@ def _lex_run(source: str, i: int, tokens: list[str], predicate: Any) -> int:
104
105
  return j
105
106
 
106
107
 
108
+ def _needs_literal_quotes(word: str) -> bool:
109
+ """Keep identifiers distinct from observed EqEdit words and font prefixes."""
110
+ return word.isalpha() and (word in _RESERVED_WORDS or word.startswith(_FONT_PREFIXES))
111
+
112
+
107
113
  def _tokenize(source: str) -> list[str]:
108
114
  tokens: list[str] = []
109
115
  i = 0
@@ -122,7 +128,13 @@ def _tokenize(source: str) -> list[str]:
122
128
  elif ch.isdigit() or ch == ".":
123
129
  i = _lex_run(source, i, tokens, lambda c: c.isdigit() or c == ".")
124
130
  elif ch.isalpha():
125
- i = _lex_run(source, i, tokens, str.isalpha)
131
+ for switch in _FONT_PREFIXES:
132
+ if source.startswith(switch, i):
133
+ tokens.append(switch)
134
+ i += len(switch)
135
+ break
136
+ else:
137
+ i = _lex_run(source, i, tokens, str.isalpha)
126
138
  else:
127
139
  # Any other single character (operators like + - = < > , ! ; :).
128
140
  tokens.append(ch)
@@ -413,7 +425,7 @@ class _Parser:
413
425
  return r"\{" if token == "LBRACE" else r"\}"
414
426
  if token.startswith('"') and token.endswith('"') and len(token) >= 2:
415
427
  literal = token[1:-1]
416
- if literal.isalpha() and literal in _RESERVED_WORDS:
428
+ if _needs_literal_quotes(literal):
417
429
  # A quoted reserved word is an identifier kept from turning into a symbol; Hancom draws it in
418
430
  # italic, as LaTeX draws plain letters. Upright text is the ``{rm "..." it}`` group.
419
431
  return self._styled(literal)
hwpx/equation/measure.py CHANGED
@@ -38,7 +38,7 @@ from __future__ import annotations
38
38
  from dataclasses import dataclass
39
39
  from typing import NamedTuple
40
40
 
41
- from .eqedit import MAX_GROUP_DEPTH, MAX_SOURCE_LENGTH, _tokenize
41
+ from .eqedit import _ATOM_END, _FONT_SWITCHES, MAX_GROUP_DEPTH, MAX_SOURCE_LENGTH, _tokenize
42
42
  from .tokens import (
43
43
  ACCENTS,
44
44
  BIG_OPERATORS,
@@ -133,7 +133,6 @@ _KEYWORD_GLYPHS = {
133
133
  #: Keyword names whose case picks the glyph: ``LINE``/``vert`` draw |, ``VERT`` draws a double bar.
134
134
  _CASED_KEYWORD_GLYPHS = {"LINE": _BAR, "vert": _BAR, "VERT": _DOUBLE_BAR}
135
135
  _LIMIT_WORDS = frozenset({"lim", "limsup", "liminf", "max", "min"})
136
- _FONT_WORDS = frozenset({"rm", "it", "bold"})
137
136
  _RELATIONS = frozenset({"=", "<", ">", "+", "-", "×", "÷"}) | frozenset(SYMBOL_OPERATORS)
138
137
  #: Hancom symbol names (any case) drawn with operator spacing.
139
138
  _SYMBOL_RELATIONS = frozenset({
@@ -273,7 +272,7 @@ def _token_width(token: str, upright: bool = False, sign: bool = False) -> float
273
272
 
274
273
  def _follows_operand(token: str, operand: bool) -> bool:
275
274
  """Whether a sign after *token* has an operand before it (*operand*: before *token*)."""
276
- if token.lower() in _FONT_WORDS:
275
+ if token in _FONT_SWITCHES:
277
276
  return operand
278
277
  return not (_is_operator(token) or token in ("(", "[", ","))
279
278
 
@@ -340,7 +339,14 @@ class _Measurer:
340
339
  return True
341
340
 
342
341
  def _atom(self, depth: int) -> _Box:
342
+ # A font switch is not the atom: ``x^rmA`` scripts the ``A`` as the converter
343
+ # reads it, so the switch applies and the next token is measured instead.
343
344
  token = self._next()
345
+ while token in _FONT_SWITCHES:
346
+ self._symbol(token)
347
+ if self._peek() is None or self._peek() in _ATOM_END:
348
+ return _Box(0.0, 0.0, 0.0)
349
+ token = self._next()
344
350
  return _Box(0.0, 0.0, 0.0) if token is None else self._dispatch(token, depth)
345
351
 
346
352
  def _group(self, depth: int) -> _Box:
@@ -399,7 +405,7 @@ class _Measurer:
399
405
  def _symbol(self, token: str, sign: bool = False) -> _Box:
400
406
  if token in FUNCTIONS or token.lower() in _LIMIT_WORDS:
401
407
  return _Box(_upright_word(token) + _FUNCTION_PAD, _ASCENT, _DESCENT)
402
- if token.lower() in _FONT_WORDS or token in ("of", "&"):
408
+ if token in _FONT_SWITCHES or token in ("of", "&"):
403
409
  if token.lower() in ("rm", "it"):
404
410
  self._upright = token.lower() == "rm"
405
411
  return _Box(0.0, 0.0, 0.0)