python-hwpx 6.9.0__py3-none-any.whl → 6.10.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
@@ -8,7 +8,15 @@ from typing import TYPE_CHECKING, Any, Iterator, Mapping, Sequence, cast
8
8
 
9
9
  from ..errors import HwpxStateError, HwpxValueError
10
10
  from ..objects.checkbox import CheckBox
11
- from ..objects.form_field import CellField, FieldLocation, FieldParameter, FormField, TextBoxField
11
+ from ..objects.form_field import (
12
+ Bookmark,
13
+ CellField,
14
+ FieldLocation,
15
+ FieldParameter,
16
+ FormField,
17
+ FormulaField,
18
+ TextBoxField,
19
+ )
12
20
  from ..objects.results import FieldFillResult
13
21
  from ..oxml import HwpxOxmlParagraph
14
22
  from ..oxml.namespaces import HP
@@ -386,8 +394,15 @@ def _form_field_payload(
386
394
  }
387
395
 
388
396
 
389
- def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
390
- matches: list[dict[str, Any]] = []
397
+ def _iter_content_paragraphs(
398
+ doc: "HwpxDocument",
399
+ ) -> Iterator[tuple[int, int, int, Any, HwpxOxmlParagraph, list[Any]]]:
400
+ """Every paragraph of the document in order, those in table cells and objects
401
+ included: section index, paragraph index (over all of them), index among the
402
+ section's own paragraphs (-1 for a nested one), the ``<hp:p>``, its view and
403
+ its runs. Memo bodies are not content, and a header/footer python-hwpx keeps
404
+ twice is walked once."""
405
+
391
406
  paragraph_index = 0
392
407
  for section_index, section in enumerate(doc.sections):
393
408
  direct_indexes = {
@@ -408,80 +423,106 @@ def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
408
423
 
409
424
  for paragraph_element in iter_content_paragraphs(section.element):
410
425
  paragraph = HwpxOxmlParagraph(paragraph_element, section)
411
- paragraph_index_in_section = direct_indexes.get(paragraph_element, -1)
412
- runs = [child for child in paragraph.element if _local_name(child) == "run"]
413
- for run_index, run in enumerate(runs):
414
- children = list(run)
415
- for child_index, child in enumerate(children):
416
- if _local_name(child) != "ctrl":
426
+ runs = [child for child in paragraph_element if _local_name(child) == "run"]
427
+ yield (
428
+ section_index,
429
+ paragraph_index,
430
+ direct_indexes.get(paragraph_element, -1),
431
+ paragraph_element,
432
+ paragraph,
433
+ runs,
434
+ )
435
+ paragraph_index += 1
436
+
437
+
438
+ def _iter_form_field_matches(doc: "HwpxDocument") -> list[dict[str, Any]]:
439
+ return _iter_field_matches(doc, _is_form_field_begin)
440
+
441
+
442
+ def _iter_field_matches(doc: "HwpxDocument", accept: Any) -> list[dict[str, Any]]:
443
+ """The fields whose ``<hp:fieldBegin>`` *accept(ctrl, field_begin)* takes, in
444
+ document order, with their text up to the matching ``<hp:fieldEnd>``."""
445
+
446
+ matches: list[dict[str, Any]] = []
447
+ for (
448
+ section_index,
449
+ paragraph_index,
450
+ paragraph_index_in_section,
451
+ paragraph_element,
452
+ paragraph,
453
+ runs,
454
+ ) in _iter_content_paragraphs(doc):
455
+ for run_index, run in enumerate(runs):
456
+ children = list(run)
457
+ for child_index, child in enumerate(children):
458
+ if _local_name(child) != "ctrl":
459
+ continue
460
+ for field_begin in child.findall(f"{_HP}fieldBegin"):
461
+ if not accept(child, field_begin):
417
462
  continue
418
- for field_begin in child.findall(f"{_HP}fieldBegin"):
419
- if not _is_form_field_begin(child, field_begin):
420
- continue
421
- end_position = _find_field_end_position(
422
- doc,
423
- runs,
424
- begin_run_index=run_index,
425
- begin_child_index=child_index,
426
- field_begin=field_begin,
427
- )
428
- end_run_index: int | None = None
429
- end_child_index: int | None = None
430
- span = None
431
- if end_position is not None:
432
- end_run_index, end_child_index, _field_end = end_position
433
- else:
434
- span = _find_field_end_in_following_paragraphs(paragraph_element, field_begin)
435
- text_nodes = _field_text_nodes(
463
+ end_position = _find_field_end_position(
464
+ doc,
465
+ runs,
466
+ begin_run_index=run_index,
467
+ begin_child_index=child_index,
468
+ field_begin=field_begin,
469
+ )
470
+ end_run_index: int | None = None
471
+ end_child_index: int | None = None
472
+ span = None
473
+ if end_position is not None:
474
+ end_run_index, end_child_index, _field_end = end_position
475
+ else:
476
+ span = _find_field_end_in_following_paragraphs(paragraph_element, field_begin)
477
+ text_nodes = _field_text_nodes(
478
+ doc,
479
+ runs,
480
+ begin_run_index=run_index,
481
+ begin_child_index=child_index,
482
+ end_run_index=end_run_index if span is None else len(runs) - 1,
483
+ end_child_index=end_child_index,
484
+ )
485
+ current_value = "".join(_text_node_value(node) for node in text_nodes)
486
+ if span is not None:
487
+ # the content goes on over paragraphs: their texts, one per line
488
+ end_paragraph, end_runs, span_run, span_child, middle = span
489
+ tail = _field_text_nodes(
436
490
  doc,
437
- runs,
438
- begin_run_index=run_index,
439
- begin_child_index=child_index,
440
- end_run_index=end_run_index if span is None else len(runs) - 1,
441
- end_child_index=end_child_index,
491
+ end_runs,
492
+ begin_run_index=0,
493
+ begin_child_index=-1,
494
+ end_run_index=span_run,
495
+ end_child_index=span_child,
442
496
  )
443
- current_value = "".join(_text_node_value(node) for node in text_nodes)
444
- if span is not None:
445
- # the content goes on over paragraphs: their texts, one per line
446
- end_paragraph, end_runs, span_run, span_child, middle = span
447
- tail = _field_text_nodes(
448
- doc,
449
- end_runs,
450
- begin_run_index=0,
451
- begin_child_index=-1,
452
- end_run_index=span_run,
453
- end_child_index=span_child,
454
- )
455
- current_value = "\n".join(
456
- [
457
- current_value,
458
- *(_run_texts([c for c in p if _local_name(c) == "run"]) for p in middle),
459
- "".join(_text_node_value(node) for node in tail),
460
- ]
461
- )
462
- payload = _form_field_payload(
463
- doc,
464
- index=len(matches),
465
- section_index=section_index,
466
- paragraph_index=paragraph_index,
467
- paragraph_index_in_section=paragraph_index_in_section,
468
- run_index=run_index,
469
- child_index=child_index,
470
- ctrl=child,
471
- field_begin=field_begin,
472
- current_value=current_value,
473
- has_end=end_position is not None or span is not None,
497
+ current_value = "\n".join(
498
+ [
499
+ current_value,
500
+ *(_run_texts([c for c in p if _local_name(c) == "run"]) for p in middle),
501
+ "".join(_text_node_value(node) for node in tail),
502
+ ]
474
503
  )
475
- payload["_paragraph"] = paragraph
476
- payload["_runs"] = runs
477
- payload["_begin_run_index"] = run_index
478
- payload["_begin_child_index"] = child_index
479
- payload["_end_run_index"] = end_run_index
480
- payload["_end_child_index"] = end_child_index
481
- payload["_text_nodes"] = text_nodes
482
- payload["_span"] = span
483
- matches.append(payload)
484
- paragraph_index += 1
504
+ payload = _form_field_payload(
505
+ doc,
506
+ index=len(matches),
507
+ section_index=section_index,
508
+ paragraph_index=paragraph_index,
509
+ paragraph_index_in_section=paragraph_index_in_section,
510
+ run_index=run_index,
511
+ child_index=child_index,
512
+ ctrl=child,
513
+ field_begin=field_begin,
514
+ current_value=current_value,
515
+ has_end=end_position is not None or span is not None,
516
+ )
517
+ payload["_paragraph"] = paragraph
518
+ payload["_runs"] = runs
519
+ payload["_begin_run_index"] = run_index
520
+ payload["_begin_child_index"] = child_index
521
+ payload["_end_run_index"] = end_run_index
522
+ payload["_end_child_index"] = end_child_index
523
+ payload["_text_nodes"] = text_nodes
524
+ payload["_span"] = span
525
+ matches.append(payload)
485
526
  return matches
486
527
 
487
528
 
@@ -494,17 +535,8 @@ def _form_field_from_match(doc: "HwpxDocument", match: Mapping[str, Any]) -> For
494
535
  ``field_type``) that 5.x exposed as separate dict keys (design §2.3).
495
536
  """
496
537
 
497
- location = FieldLocation(
498
- section_index=match["section_index"],
499
- paragraph_index=match["paragraph_index"],
500
- paragraph_index_in_section=match["paragraph_index_in_section"],
501
- run_index=match["run_index"],
502
- child_index=match["child_index"],
503
- )
504
- parameters = tuple(
505
- FieldParameter(name=parameter.get("name", ""), value=parameter.get("value", ""))
506
- for parameter in match.get("parameters", [])
507
- )
538
+ location = _match_location(match)
539
+ parameters = _match_parameters(match)
508
540
  field_begin = match["_field_begin"]
509
541
  editable = (field_begin.get("editable") or "").strip().lower() in {"1", "true"}
510
542
  return FormField(
@@ -536,6 +568,107 @@ def list_form_fields(doc: "HwpxDocument") -> tuple[FormField, ...]:
536
568
  return tuple(_form_field_from_match(doc, match) for match in _iter_form_field_matches(doc))
537
569
 
538
570
 
571
+ def _match_location(match: Mapping[str, Any]) -> FieldLocation:
572
+ return FieldLocation(
573
+ section_index=match["section_index"],
574
+ paragraph_index=match["paragraph_index"],
575
+ paragraph_index_in_section=match["paragraph_index_in_section"],
576
+ run_index=match["run_index"],
577
+ child_index=match["child_index"],
578
+ )
579
+
580
+
581
+ def _match_parameters(match: Mapping[str, Any]) -> tuple[FieldParameter, ...]:
582
+ return tuple(
583
+ FieldParameter(name=parameter.get("name", ""), value=parameter.get("value", ""))
584
+ for parameter in match.get("parameters", [])
585
+ )
586
+
587
+
588
+ def _field_type_is(field_type: str) -> Any:
589
+ def accept(_ctrl: Any, field_begin: Any) -> bool:
590
+ return (field_begin.get("type") or "").strip().upper() == field_type
591
+
592
+ return accept
593
+
594
+
595
+ def _cell_address(element: Any) -> tuple[int, int] | None:
596
+ """``(row, column)`` of the innermost table cell holding *element*, else ``None``."""
597
+
598
+ node = element.getparent()
599
+ while node is not None:
600
+ if _local_name(node) == "tc":
601
+ address = node.find(f"{_HP}cellAddr")
602
+ if address is None:
603
+ return None
604
+ try:
605
+ return int(address.get("rowAddr", "")), int(address.get("colAddr", ""))
606
+ except ValueError:
607
+ return None
608
+ node = node.getparent()
609
+ return None
610
+
611
+
612
+ def list_formula_fields(doc: "HwpxDocument") -> tuple[FormulaField, ...]:
613
+ """Return the table formulas Hancom saved (``fieldBegin type="FORMULA"``), in
614
+ document order, with the values Hancom wrote. Nothing is recomputed."""
615
+
616
+ formulas: list[FormulaField] = []
617
+ for match in _iter_field_matches(doc, _field_type_is("FORMULA")):
618
+ parameters = match["parameters"]
619
+ command = _field_parameter_value(parameters, "Command")
620
+ formulas.append(
621
+ FormulaField(
622
+ field_id=match["field_id"],
623
+ # Hancom also writes the formula as the head of its Command
624
+ # ("=SUM(A1:A3)??%g,;;6"); read it there when Formula is absent.
625
+ formula=_field_parameter_value(parameters, "Formula") or command.split("??", 1)[0],
626
+ result_format=_field_parameter_value(parameters, "ResultFormat"),
627
+ last_result=_field_parameter_value(parameters, "LastResult"),
628
+ command=command,
629
+ value=match["current_value"],
630
+ location=_match_location(match),
631
+ cell_address=_cell_address(match["_paragraph"].element),
632
+ parameters=_match_parameters(match),
633
+ element=match["_field_begin"],
634
+ )
635
+ )
636
+ return tuple(formulas)
637
+
638
+
639
+ def list_bookmarks(doc: "HwpxDocument") -> tuple[Bookmark, ...]:
640
+ """Return every bookmark in document order, in either form Hancom saves it
641
+ (see :class:`~hwpx.objects.Bookmark`), those in table cells and objects included."""
642
+
643
+ fields = {
644
+ match["_field_begin"]: match
645
+ for match in _iter_field_matches(doc, _field_type_is("BOOKMARK"))
646
+ }
647
+ bookmarks: list[Bookmark] = []
648
+ for section_index, paragraph_index, paragraph_index_in_section, _p, _view, runs in _iter_content_paragraphs(doc):
649
+ for run_index, run in enumerate(runs):
650
+ for child_index, child in enumerate(run):
651
+ if _local_name(child) != "ctrl":
652
+ continue
653
+ location = FieldLocation(
654
+ section_index=section_index,
655
+ paragraph_index=paragraph_index,
656
+ paragraph_index_in_section=paragraph_index_in_section,
657
+ run_index=run_index,
658
+ child_index=child_index,
659
+ )
660
+ for mark in child:
661
+ if mark.tag == f"{_HP}bookmark":
662
+ name = mark.get("name", "")
663
+ if name:
664
+ bookmarks.append(Bookmark(name, "point", "", location, mark))
665
+ elif mark in fields:
666
+ name = (mark.get("name") or "").strip()
667
+ if name:
668
+ bookmarks.append(Bookmark(name, "field", fields[mark]["current_value"], location, mark))
669
+ return tuple(bookmarks)
670
+
671
+
539
672
  def _named_cells(paragraphs: Any) -> Iterator[Any]:
540
673
  for paragraph in paragraphs:
541
674
  for table in paragraph.tables:
@@ -28,7 +28,7 @@ from ._base import _Namespace
28
28
 
29
29
  if TYPE_CHECKING:
30
30
  from ...form_fit.policy import FitPolicy
31
- from ...objects import CellField, CheckBox, FieldFillResult, FormField, TextBoxField
31
+ from ...objects import CellField, CheckBox, FieldFillResult, FormField, FormulaField, TextBoxField
32
32
  from ...oxml import HwpxOxmlParagraph, HwpxOxmlSection
33
33
 
34
34
  __all__ = ["FieldsNamespace"]
@@ -142,6 +142,22 @@ class FieldsNamespace(_Namespace):
142
142
 
143
143
  return _fields.fill_cell_fields(self._doc, value, name=name, index=index)
144
144
 
145
+ # -- 계산식 필드 -------------------------------------------------------
146
+
147
+ @property
148
+ def formulas(self) -> "tuple[FormulaField, ...]":
149
+ """한/글이 저장한 표 계산식(``fieldBegin type="FORMULA"``)을 문서 순서로. 본문 표와 그 칸
150
+ 안의 표를 본다.
151
+
152
+ 값은 한/글이 적은 그대로다. 다시 계산하지 않는다: ``formula``는 한/글 표기(``=SUM(?1:?3)``의
153
+ ``?`` 같은)를 그대로 두고, ``last_result``는 한/글이 마지막으로 계산한 값, ``value``는
154
+ 문서에 보이는 글이다. ``cell_address``는 계산식이 든 칸의 ``(행, 열)``이다.
155
+ """
156
+
157
+ from .. import fields as _fields
158
+
159
+ return _fields.list_formula_fields(self._doc)
160
+
145
161
  # -- 글상자 필드 -------------------------------------------------------
146
162
 
147
163
  @property
hwpx/_document/ns/refs.py CHANGED
@@ -15,6 +15,7 @@ from ._base import _Namespace
15
15
 
16
16
  if TYPE_CHECKING:
17
17
  from ...model import InlineObject, Paragraph, Section
18
+ from ...objects import Bookmark
18
19
 
19
20
  __all__ = ["RefsNamespace"]
20
21
 
@@ -25,6 +26,19 @@ class RefsNamespace(_Namespace):
25
26
  __slots__ = ()
26
27
  _path = "doc.refs"
27
28
 
29
+ @property
30
+ def bookmarks(self) -> "tuple[Bookmark, ...]":
31
+ """문서의 모든 책갈피를 문서 순서로. 표 칸과 개체 안의 것도 본다.
32
+
33
+ 한/글이 책갈피를 저장하는 두 형태를 함께 낸다: ``hp:bookmark``(``kind="point"``)와
34
+ ``fieldBegin type="BOOKMARK"``…``fieldEnd`` 짝(``kind="field"``). 필드 형태의 ``text``는
35
+ 시작과 끝 사이의 글이다(한/글은 흔히 사이를 비워 둔다).
36
+ """
37
+
38
+ from .. import fields as _fields
39
+
40
+ return _fields.list_bookmarks(self._doc)
41
+
28
42
  def add_bookmark(
29
43
  self,
30
44
  name: str,
@@ -493,6 +493,38 @@ class StylesNamespace(_Namespace, Mapping[str, "Style"]):
493
493
  def memo_shape(self, memo_shape_id_ref: "int | str | None") -> "MemoShape | None":
494
494
  return self._doc.oxml.memo_shape(memo_shape_id_ref)
495
495
 
496
+ @property
497
+ def numberings(self) -> dict[str, "GenericElement"]:
498
+ """번호 정의(`hh:numbering`) 목록(id 문자열 → `GenericElement`).
499
+
500
+ 첫 헤더의 `hh:refList/hh:numberings`를 읽는다. 문단 모양의
501
+ `hh:heading@idRef`(종류가 NUMBER·OUTLINE일 때)가 가리키는 정의다.
502
+ 헤더나 정의가 없으면 `{}`. 글머리표 정의는 :attr:`bullets`.
503
+ """
504
+
505
+ header = self._primary_header()
506
+ if header is None:
507
+ return {}
508
+ element = header._numberings_element()
509
+ if element is None:
510
+ return {}
511
+ from ...oxml.header import parse_numberings
512
+
513
+ parsed = parse_numberings(header._convert_to_lxml(element))
514
+ mapping: dict[str, "GenericElement"] = {}
515
+ for definition in parsed.numberings:
516
+ identifier = definition.attributes.get("id")
517
+ if identifier is not None:
518
+ mapping.setdefault(str(identifier), definition)
519
+ return mapping
520
+
521
+ def numbering(self, numbering_id_ref: "int | str | None") -> "GenericElement | None":
522
+ """id가 *numbering_id_ref*인 번호 정의. 없으면 `None`. 정수와 문자열을 모두 받는다."""
523
+
524
+ if numbering_id_ref is None:
525
+ return None
526
+ return self.numberings.get(str(numbering_id_ref).strip())
527
+
496
528
  # -- 서식 id 를 mint 하는 동사 -----------------------------------------
497
529
 
498
530
  def ensure_run(
@@ -517,6 +549,7 @@ class StylesNamespace(_Namespace, Mapping[str, "Style"]):
517
549
  emboss: bool | None = None,
518
550
  engrave: bool | None = None,
519
551
  base_char_pr_id: str | int | None = None,
552
+ font_by_lang: "Mapping[str, str] | None" = None,
520
553
  ) -> str:
521
554
  """요청한 글자 서식의 `charPr` id 를 보장하고 그 id 를 돌려준다.
522
555
 
@@ -529,6 +562,23 @@ class StylesNamespace(_Namespace, Mapping[str, "Style"]):
529
562
  DASH/DASH_DOT/DASH_DOT_DOT), `emboss`/`engrave` (양각/음각)는 6.3
530
563
  추가분이다. `script="sup"/"sub"`는 한컴처럼 `hh:supscript`/`hh:subscript`
531
564
  요소만 쓴다(요소가 글자를 줄이고 올리거나 내린다. `relSz`/`offset`은 그대로).
565
+
566
+ `font`는 모든 언어의 글꼴을, `font_by_lang`은 언어별 글꼴을 정한다.
567
+ `font_by_lang`은 언어(HANGUL·LATIN·HANJA·JAPANESE·OTHER·SYMBOL·USER,
568
+ 대소문자 무시) → 글꼴 이름 매핑이다. 예:
569
+ `ensure_run(font_by_lang={"HANGUL": "함초롬바탕", "LATIN": "Arial"})`.
570
+
571
+ - 언어마다 글꼴 id를 따로 매기므로, 각 글꼴을 그 언어 블록에 등록하고
572
+ (없으면 더한다) 그 블록의 id를 `fontRef`의 그 언어 속성에 쓴다.
573
+ - 이름을 대지 않은 언어는 기준 글자 모양의 `fontRef` 값을 그대로 둔다.
574
+ - `font`와 함께 주면 `font`를 먼저 모든 언어에 적용하고, `font_by_lang`이
575
+ 댄 언어만 그 글꼴로 바꾼다(`font_by_lang`이 이긴다).
576
+ - 기준 글자 모양은 바꾸지 않는다. 기준을 복사해 바꾼 결과와 내용이 같은
577
+ 글자 모양이 이미 있으면 그 id를, 없으면 새 id를 돌려준다.
578
+ - 아무 글꼴도 등록하기 전에 인자를 검사한다: 모르는 언어는
579
+ `style-font-lang-invalid`, 빈 글꼴 이름은 `style-font-face-empty`,
580
+ 매핑이 아니거나 문자열이 아닌 키·값, 대소문자만 다른 같은 언어 두 번은
581
+ `style-run-font-by-lang-invalid`(`HwpxValueError`).
532
582
  """
533
583
 
534
584
  return self._doc.oxml.ensure_run_style(
@@ -551,6 +601,7 @@ class StylesNamespace(_Namespace, Mapping[str, "Style"]):
551
601
  emboss=emboss,
552
602
  engrave=engrave,
553
603
  base_char_pr_id=base_char_pr_id,
604
+ font_by_lang=font_by_lang,
554
605
  )
555
606
 
556
607
  def ensure_border_fill(
@@ -669,6 +720,90 @@ class StylesNamespace(_Namespace, Mapping[str, "Style"]):
669
720
 
670
721
  return self._doc.oxml.ensure_numbering(kind=kind, levels=levels)
671
722
 
723
+ def ensure_paragraph_format(
724
+ self,
725
+ *,
726
+ base_para_pr_id: str | int | None = None,
727
+ alignment: str | None = None,
728
+ line_spacing_percent: int | float | None = None,
729
+ margins: Mapping[str, int] | None = None,
730
+ heading: Mapping[str, str | int] | None = None,
731
+ border: Mapping[str, str | int] | None = None,
732
+ break_setting: Mapping[str, bool] | None = None,
733
+ tab_pr_id_ref: str | None = None,
734
+ ) -> str:
735
+ """요청한 문단 모양의 `paraPr` id 를 보장하고 그 id 를 돌려준다.
736
+
737
+ :meth:`ensure_run` 의 문단 쪽 짝이다. 기준(`base_para_pr_id`, 없으면 첫
738
+ `paraPr`)을 복사해 요청한 값만 바꾸고, 내용이 같은 문단 모양이 있으면 그것을
739
+ 다시 쓴다. 문단에는 적용하지 않는다 — 돌려받은 id 를 문단의
740
+ `para_pr_id_ref` 나 :meth:`ensure_style` 의 `para_pr_id_ref` 에 넘긴다.
741
+ 사람 단위(mm·pt)로 문단에 바로 적용하려면 :meth:`apply_paragraph_format`.
742
+
743
+ 값은 OWPML 그대로다: `margins` 는 HWPUNIT(`left`·`right`·`intent`·`prev`·
744
+ `next`), `heading` 은 `hh:heading` 속성(`type`·`idRef`·`level`),
745
+ `break_setting` 은 `keep_with_next`·`keep_lines`·`page_break_before`·
746
+ `widow_orphan` 불리언이다. 헤더가 없으면
747
+ `HwpxStateError(code="document-header-missing")`.
748
+ """
749
+
750
+ return self._require_header().ensure_paragraph_format(
751
+ base_para_pr_id=base_para_pr_id,
752
+ alignment=alignment,
753
+ line_spacing_percent=line_spacing_percent,
754
+ margins=margins,
755
+ heading=heading,
756
+ border=border,
757
+ break_setting=break_setting,
758
+ tab_pr_id_ref=tab_pr_id_ref,
759
+ )
760
+
761
+ def ensure_style(
762
+ self,
763
+ name: str,
764
+ *,
765
+ style_type: str | None = None,
766
+ eng_name: str | None = None,
767
+ para_pr_id_ref: str | int | None = None,
768
+ char_pr_id_ref: str | int | None = None,
769
+ next_style_id_ref: str | int | None = None,
770
+ lang_id: int | None = None,
771
+ lock_form: bool | None = None,
772
+ ) -> str:
773
+ """이름이 *name* 인 스타일(`hh:style`)의 id 를 보장하고 돌려준다.
774
+
775
+ 한/글은 스타일을 이름으로 구별하므로 *name* 이 중복 제거의 열쇠다. 같은
776
+ 이름의 스타일이 있으면 새로 만들지 않고 그 id 를 돌려주며, `None` 이 아닌
777
+ 키워드만 그 스타일에 덮어쓴다. 없으면 새 id 로 만들고(`style_type` 기본
778
+ `"PARA"`), `hh:styles@itemCnt` 를 맞춘다. 같은 이름의 다른 스타일을 따로
779
+ 두고 싶으면 먼저 :meth:`names` 로 겹치지 않는 이름을 고른다.
780
+
781
+ `next_style_id_ref` 를 자기 자신으로 두려면 한 번 만든 뒤 돌려받은 id 로
782
+ 다시 부른다. 헤더가 없으면 `HwpxStateError(code="document-header-missing")`.
783
+ """
784
+
785
+ return self._require_header().ensure_style(
786
+ name,
787
+ style_type=style_type,
788
+ eng_name=eng_name,
789
+ para_pr_id_ref=para_pr_id_ref,
790
+ char_pr_id_ref=char_pr_id_ref,
791
+ next_style_id_ref=next_style_id_ref,
792
+ lang_id=lang_id,
793
+ lock_form=lock_form,
794
+ )
795
+
796
+ def _require_header(self) -> "HwpxOxmlHeader":
797
+ header = self._primary_header()
798
+ if header is None:
799
+ from ...errors import HwpxStateError
800
+
801
+ raise HwpxStateError(
802
+ "document does not contain any headers",
803
+ code="document-header-missing",
804
+ )
805
+ return header
806
+
672
807
  # -- 문단에 서식을 적용하는 동사 ---------------------------------------
673
808
 
674
809
  def apply_paragraph_format(
@@ -57,7 +57,7 @@
57
57
  | 글꼴 등록 | Create·Render-verified | `doc.styles.ensure_font`(6.8 트레인㉚ 등재, 코드는 2026-08-04 감사 §2 갭#1 이후 사이클에서 구현됐으나 캐파빌리티 미등재 상태였다). 실한컴 렌더 검증: `docs/openrate/report-v5.json` authored-fontface 스트라텀(lang 7블록 전부·substFont on/off 조합), macOS Hancom GUI 오라클 15/15 render_checked·0 render_failed — 실제로 참조된 fontRef까지 확인(선언만 하고 고아로 남기지 않음) |
58
58
  | 표 탐색 기반 채움(라벨 매칭 네비게이션) | Edit·Render-verified | `doc.tables.fill_by_path`/`.find_cell_by_label`(6.8 트레인㉚ 등재, 코드는 이전 사이클부터 존재). "양식 채움(byte-splice)" 영역과는 다른 메커니즘(byte-splice가 아니라 라벨 매칭 기반 구조적 셀 채움) — 혼동 주의. 실한컴 렌더 검증: `docs/openrate/report-v14.json` authored-tablenavfill 스트라텀(단일-홉 right/down 4건 + multi-hop `합계 > down > right` 1건), macOS Hancom GUI 오라클 5/5 render_checked·0 render_failed(2026-08-08 측정). **원장 라우팅은 없음** — 기존 `hp:tc`/`hp:t` 텍스트를 치환만 할 뿐 새 요소를 안 만든다(document-merge·mail-merge·find-replace와 같은 이유로 CAPABILITY_KEYWORDS 등록 요소 0개) — 등급 갱신은 이 산문과 report-v14.json 직접 인용으로만 |
59
59
  | 찾아바꾸기 | Edit·Render-verified | `doc.text.replace`/`.find_runs`(6.8 트레인㉚ 등재, 코드는 이전 사이클부터 존재). 실한컴 렌더 검증: `docs/openrate/report-v14.json` authored-findreplace 스트라텀(무제한 치환 + `char_pr_id_ref`로 좁힌 스타일 한정 치환 교대), macOS Hancom GUI 오라클 5/5 render_checked·0 render_failed(2026-08-08 측정). **원장 라우팅은 없음** — 기존 `hp:t` 텍스트만 치환할 뿐 새 요소를 안 만든다(document-merge·mail-merge·table-navigation-fill과 같은 이유) — 등급 갱신은 이 산문과 report-v14.json 직접 인용으로만 |
60
- | 하이퍼링크·책갈피 | Create·Render-verified | `doc.refs.add_hyperlink`/`.add_bookmark`(6.8 트레인㉚에서 "네이티브 목차(TOC)/상호참조" 영역에서 분리 — 그 영역의 Render-verified 근거는 TOC 구조·페이지 정합뿐이라 하이퍼링크·책갈피를 한 번도 독립적으로 커버한 적이 없었다, 편집기 표면 인벤토리 트레인㉙ 발견). **6.9 트레인㉜**: `docs/openrate/report-v12.json` authored-hyperlink-bookmark 스트라텀(북마크 생성 후 외부 URL/문서 내 `#앵커` 하이퍼링크 교대), macOS Hancom GUI 오라클 15/15 render_checked·0 render_failed(2026-08-07 측정) — 이 영역의 첫 독립 실한컴 판정. `hp:bookmark`는 요소 직접 등록(`by-openrate-corpus`), `hp:fieldBegin`(하이퍼링크 자신의 컨트롤)은 CLICKHERE/TOC/CROSSREF와 공유하는 저수준 요소라 여전히 요소 등록 없음 — 영역 등급만 실측으로 갱신, 원장 오염 경로는 그대로 차단 |
60
+ | 하이퍼링크·책갈피 | Create·Render-verified | `doc.refs.add_hyperlink`/`.add_bookmark`(6.8 트레인㉚에서 "네이티브 목차(TOC)/상호참조" 영역에서 분리 — 그 영역의 Render-verified 근거는 TOC 구조·페이지 정합뿐이라 하이퍼링크·책갈피를 한 번도 독립적으로 커버한 적이 없었다, 편집기 표면 인벤토리 트레인㉙ 발견). **6.9 트레인㉜**: `docs/openrate/report-v12.json` authored-hyperlink-bookmark 스트라텀(북마크 생성 후 외부 URL/문서 내 `#앵커` 하이퍼링크 교대), macOS Hancom GUI 오라클 15/15 render_checked·0 render_failed(2026-08-07 측정) — 이 영역의 첫 독립 실한컴 판정. `hp:bookmark`는 요소 직접 등록(`by-openrate-corpus`), `hp:fieldBegin`(하이퍼링크 자신의 컨트롤)은 CLICKHERE/TOC/CROSSREF와 공유하는 저수준 요소라 여전히 요소 등록 없음 — 영역 등급만 실측으로 갱신, 원장 오염 경로는 그대로 차단. 읽기: `doc.refs.bookmarks`가 한/글의 두 저장 형태(`hp:bookmark`·`hp:fieldBegin type="BOOKMARK"`)를 함께 나열한다(#579) |
61
61
  | 메일머지(placeholder 템플릿 배치 생성) | Edit·Render-verified | `hwpx.tools.mail_merge.merge_template_rows`(6.8 트레인㉛ 등재, 코드는 이전 사이클부터 존재 — 편집기 표면 인벤토리 트레인㉙·계층 판정 트레인㉚이 찾을 때까지 캐파빌리티·매트릭스 어디에도 등재가 없었다). `{{field}}`/`${field}`/`<<field>>` 세 플레이스홀더 문법을 지원하는 템플릿 1개 + 행 데이터(csv/json/시퀀스)로 문서 N개를 배치 생성 — 기존 `hp:t` 텍스트를 치환하는 것이라 새 요소를 만들지 않는다(Create가 아니라 Edit). `strict`/`fit_policy`/`value_sanitizer` 등 운영 옵션 다수. 실한컴 렌더 검증: `docs/openrate/report-v13.json` authored-mailmerge 스트라텀(세 플레이스홀더 문법 각각 겨냥하는 전용 템플릿으로 회전), macOS Hancom GUI 오라클 10/10 render_checked·0 render_failed(2026-08-08 측정) — 이 영역의 첫 독립 실한컴 판정 |
62
62
  | 메일머지 표시 필드 | Create(experimental) | `HwpxOxmlParagraph.add_mail_merge_field(name, cached_text=)`(`oxml/field_marks.py`, P4). 팀장 실한컴 GUI 프로브 gold(`tests/fixtures/gui_probes/mailmerge_display_fields.hwpx`, "도구 > 메일 머지 > 메일 머지 표시 달기"로 필드 2개 삽입) 역설계 — 위 「메일머지(placeholder 템플릿 배치 생성)」가 **기존 `hp:t` 텍스트를 치환**하는 Edit인 것과 달리 이쪽은 `hp:fieldBegin type="MAILMERGE"` 자체를 새로 만드는 Create다(그래서 별도 영역). DATE/PATH와 같은 단일 run 안 `ctrl(begin)`/`t`/`ctrl(end)` 배치에 더해 **끝에 빈 `hp:t`가 하나 더** 붙고(gold 2/2), `hp:fieldBegin`에 `metaTag` 속성이 **없다**(DATE/교정 부호/PATH gold는 셋 다 `metaTag=""`) — 필드 종류마다 실측이 갈리는 유일한 속성. `hp:parameters`(`cnt="5"`): `Fiexde=1`(**오타 철자가 실물·한컴 공식 문서 공통의 정본이라 정정 금지** — `trackchageConfig`·memo의 `NOMAL`과 같은 부류) · `Prop=8`(DATE/PATH와 같은 캐시 필드류 공유값) · `Command`/`FieldValue`가 둘 다 필드 이름 그대로 · `FieldType="USER_DEFINE"`. 캐시 텍스트 기본값 `{{이름}}`은 `hwpx.tools.mail_merge`가 인식하는 플레이스홀더 문법이라 이 필드로 저작한 템플릿이 그 배치 생성기에 그대로 물린다. gold의 두 필드는 `id`가 다른데 `fieldid`는 같은 값을 공유하나, 표본이 문서 하나뿐이라 채번 규칙을 역산할 근거가 없어 DATE/PATH와 같은 독립 난수를 쓴다. 실한컴 렌더 검증: `docs/openrate/report-v22.json` authored-mailmerge-field 스트라텀(단일/2필드/커스텀 캐시/**한글 필드명(경계)**/표 셀 안 필드, 5건), macOS Hancom GUI 오라클 5/5 render_checked·0 render_failed(2026-08-18 측정) |
63
63
  | 문서 끼워 넣기(문서 병합) | Create·Render-verified | `hwpx.tools.document_merge.append_document`/`.insert_document`(6.9 트레인㉝ v1, 6.10 트레인㊱ v2 — 편집기 표면 인벤토리 트레인㉙의 macOS 메뉴 전수 스캔이 찾은 신규 갭, "입력→문서 끼워 넣기…"). 다른 HWPX 문서의 본문을 연 문서에 끼워 넣는다 — 핵심은 헤더가 소유한 8개 공유 자원(charPr/paraPr/style/borderFill/tabPr/numbering·bullet/memoPr/fontfaces)을 원본에서 새 id로 복제해 재매핑하는 것이지 단순 복사가 아니다(그대로 복사하면 대상 문서의 기존 id를 조용히 가로챈다). 한컴 편집기 실측(팀장, 2026-08-07): "입력→문서 끼워 넣기…" 패널의 4개 고유 옵션(글자 모양 유지·스타일 유지·쪽 모양 유지·문단 모양 유지, 기본값 전부 해제=흡수)이 정책 축의 실측 근거. v2는 이 4축을 한컴과 같은 이름의 매개변수(`keep_character_shape`/`keep_style`/`keep_paragraph_shape`/`keep_page_shape`)로 노출한다 — 기본값은 v1의 기출하·실검증 동작과 동일(글자·스타일·문단 모양=유지, 쪽 모양=흡수), 반대 방향은 매핑 실측이 없어 typed 오류로 정직 거부(과설계 안 함). v2는 MEMO 병합도 지원한다(DEV-042): `hp:memogroup`은 절 레벨 형제라 원본의 모든 절에서 참조된 `hp:memo`를 찾아 복제, 새 메모 id 채번 후 body 문단 복제본과 같은 리스트로 묶어 기존 축1 재매핑(charPr/paraPr/style/memoShapeIDRef)에 그대로 태운다. 실측으로 찾은 결함 8건을 수정(v1 6건 + v2 2건): 스타일 자신의 기본 charPr/paraPr 누락, `HwpxOxmlDocument.char_properties` 캐시 미무효화, `linkListIDRef`/`linkListNextIDRef` 과잉거부(팀장 독립 검증 — 벤더드 코퍼스 5,891/5,891건이 전부 "0" 관용값인데 존재만으로 거부해 표가 든 모든 문서, 우리 자신의 `add_table` 산출물 포함, 병합이 불가능했다), 저장 경로 dirty-tracking 미설정(가장 심각 — `target_header.mark_dirty()`를 호출하지 않아 헤더에 새로 추가한 요소가 저장 시 조용히 누락되는데, 그림이 있는 병합만 우연히 `add_image`의 부수효과로 가려져 있었다), `hp:secPr` 제거가 통째 run을 지워 표·텍스트까지 함께 삭제(실코퍼스 표 문서에서 secPr·표·텍스트가 한 run에 공존, 수정 후 secPr만 개별 제거), 새 id 채번 순서가 프로세스마다 비결정적(`set` 순회를 `sorted()`로 교체), `check_id_integrity` 자신의 `memoShapeIDRef="0"` 오탐(fresh 문서의 secPr 스켈레톤 기본값을 memo_shapes 테이블이 채워지는 순간부터 댕글링으로 오판 — 병합과 무관한 사전 존재 결함, `id_integrity.py`의 `_ALLOWED_SENTINELS`로 수정), `hp:fieldEnd`의 `fieldid` 미재생성(원본 문서의 raw uuid4().hex 값이 복사된 내용에 그대로 남음 — v14 생성기 자체 결정성 검사로 발견, `begin_fieldid_map`으로 수정). `hp:connectLine`(스마트 연결선)·`chartIDRef`·실체인 `linkListIDRef`가 있으면 fail-closed 거부. 참조 무결성은 재발명하지 않고 기존 `hwpx.tools.id_integrity.check_id_integrity`로 검증(설계 문서: `docs/2026-08-08-document-merge-contract.md`). 실한컴 렌더 검증: `docs/openrate/report-v13.json` authored-docmerge 스트라텀(v1, 10건 중 4건이 표 포함 — 위 결함 셋이 전부 표 병합에서 터졌던 형태를 정면으로 겨냥), macOS Hancom GUI 오라클 10/10 render_checked·0 render_failed(2026-08-08 측정). v2(4축 매개변수+MEMO 병합)는 `docs/openrate/report-v14.json` authored-docmerge2 스트라텀(단일 메모/센티널 기본값/대상 기존 memogroup 합류/표 동반 4갈래, 4축 기본값 명시통과 호출), macOS Hancom GUI 오라클 5/5 render_checked·0 render_failed(2026-08-08 측정)로 검증 완료. 6.15: 클론 경로 감사(속성-클론 중첩 참조 앨리어싱 수리, `b81713e`)의 후속으로 v20(`cross-real-merge`, 우리 자신이 생성한 문서가 아니라 실한컴이 저장한 문서끼리 병합 — v13의 성긴 헤더로는 이 앨리어싱 결함이 애초에 안 보였을 것이라는 지적)을 실행: 실 문서 3종 쌍방향 병합·중간 삽입 3건·필드 보유 소스 2종·3단 연쇄 병합 12건, macOS Hancom GUI 오라클 12/12 render_checked·0 render_failed(2026-08-12 측정) — 앨리어싱 수리 후 재현이 사라졌음을 실 소스로 재확인. 세 버전 모두 같은 스트라텀 그룹(document_merge)이라 원장 라우팅은 여전히 없음(위 산문 근거만) |
@@ -278,6 +278,9 @@ class _LatexParser:
278
278
  # ``bold`` alone keeps the letters italic and ``rm`` goes on past its braces: upright bold, then
279
279
  # italic again for what follows.
280
280
  return f"{{rm {{bold {{{self._group_or_atom(depth)}}}}} it}}"
281
+ if token == "\\boldsymbol":
282
+ # ``bold`` thickens only the next atom and keeps the letters italic, as ``\boldsymbol`` does.
283
+ return f"{{bold {{{self._group_or_atom(depth)}}}}}"
281
284
  if token == "\\begin":
282
285
  return self._environment(depth)
283
286
  if token == "\\left":