python-hwpx 6.9.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.
Files changed (38) hide show
  1. hwpx/_document/fields.py +242 -85
  2. hwpx/_document/ns/fields.py +17 -1
  3. hwpx/_document/ns/refs.py +14 -0
  4. hwpx/_document/ns/styles.py +135 -0
  5. hwpx/_trailing_table_text.py +85 -0
  6. hwpx/data/contract_docs/mutation-semantics.md +6 -3
  7. hwpx/data/contract_docs/support-matrix.md +1 -1
  8. hwpx/equation/authoring.py +6 -3
  9. hwpx/equation/eqedit.py +103 -8
  10. hwpx/equation/measure.py +10 -4
  11. hwpx/errors.py +2 -0
  12. hwpx/form_fit/_glyph_table.py +6084 -1012
  13. hwpx/form_fit/measure.py +511 -56
  14. hwpx/layout/line_cache.py +216 -72
  15. hwpx/layout/pages.py +1115 -236
  16. hwpx/objects/__init__.py +3 -1
  17. hwpx/objects/form_field.py +73 -3
  18. hwpx/oxml/_document_primitives.py +60 -73
  19. hwpx/oxml/document_parts.py +9 -5
  20. hwpx/oxml/header_fonts.py +66 -2
  21. hwpx/oxml/paragraph.py +16 -3
  22. hwpx/oxml/section.py +18 -4
  23. hwpx/oxml/table.py +30 -7
  24. hwpx/oxml/table_structure.py +50 -3
  25. hwpx/patch.py +248 -0
  26. hwpx/table_patch.py +467 -86
  27. hwpx/tools/doc_diff.py +15 -2
  28. hwpx/tools/markdown_export.py +15 -4
  29. hwpx/tools/package_validator.py +47 -6
  30. hwpx/tools/repair.py +123 -3
  31. python_hwpx-6.11.0.dist-info/METADATA +256 -0
  32. {python_hwpx-6.9.0.dist-info → python_hwpx-6.11.0.dist-info}/RECORD +37 -36
  33. {python_hwpx-6.9.0.dist-info → python_hwpx-6.11.0.dist-info}/WHEEL +1 -1
  34. python_hwpx-6.9.0.dist-info/METADATA +0 -252
  35. {python_hwpx-6.9.0.dist-info → python_hwpx-6.11.0.dist-info}/entry_points.txt +0 -0
  36. {python_hwpx-6.9.0.dist-info → python_hwpx-6.11.0.dist-info}/licenses/LICENSE +0 -0
  37. {python_hwpx-6.9.0.dist-info → python_hwpx-6.11.0.dist-info}/licenses/NOTICE +0 -0
  38. {python_hwpx-6.9.0.dist-info → python_hwpx-6.11.0.dist-info}/top_level.txt +0 -0
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,83 +423,133 @@ 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
+ 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]]:
451
+ """The fields whose ``<hp:fieldBegin>`` *accept(ctrl, field_begin)* takes, in
452
+ document order, with their text up to the matching ``<hp:fieldEnd>``."""
453
+
454
+ matches: list[dict[str, Any]] = []
455
+ for (
456
+ section_index,
457
+ paragraph_index,
458
+ paragraph_index_in_section,
459
+ paragraph_element,
460
+ paragraph,
461
+ runs,
462
+ ) in paragraphs:
463
+ for run_index, run in enumerate(runs):
464
+ children = list(run)
465
+ for child_index, child in enumerate(children):
466
+ if _local_name(child) != "ctrl":
467
+ continue
468
+ for field_begin in child.findall(f"{_HP}fieldBegin"):
469
+ if not accept(child, field_begin):
417
470
  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(
471
+ end_position = _find_field_end_position(
472
+ doc,
473
+ runs,
474
+ begin_run_index=run_index,
475
+ begin_child_index=child_index,
476
+ field_begin=field_begin,
477
+ )
478
+ end_run_index: int | None = None
479
+ end_child_index: int | None = None
480
+ span = None
481
+ if end_position is not None:
482
+ end_run_index, end_child_index, _field_end = end_position
483
+ else:
484
+ span = _find_field_end_in_following_paragraphs(paragraph_element, field_begin)
485
+ text_nodes = _field_text_nodes(
486
+ doc,
487
+ runs,
488
+ begin_run_index=run_index,
489
+ begin_child_index=child_index,
490
+ end_run_index=end_run_index if span is None else len(runs) - 1,
491
+ end_child_index=end_child_index,
492
+ )
493
+ current_value = "".join(_text_node_value(node) for node in text_nodes)
494
+ if span is not None:
495
+ # the content goes on over paragraphs: their texts, one per line
496
+ end_paragraph, end_runs, span_run, span_child, middle = span
497
+ tail = _field_text_nodes(
422
498
  doc,
423
- runs,
424
- begin_run_index=run_index,
425
- begin_child_index=child_index,
426
- field_begin=field_begin,
499
+ end_runs,
500
+ begin_run_index=0,
501
+ begin_child_index=-1,
502
+ end_run_index=span_run,
503
+ end_child_index=span_child,
427
504
  )
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(
436
- 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,
442
- )
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,
505
+ current_value = "\n".join(
506
+ [
507
+ current_value,
508
+ *(_run_texts([c for c in p if _local_name(c) == "run"]) for p in middle),
509
+ "".join(_text_node_value(node) for node in tail),
510
+ ]
474
511
  )
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
512
+ payload = _form_field_payload(
513
+ doc,
514
+ index=len(matches),
515
+ section_index=section_index,
516
+ paragraph_index=paragraph_index,
517
+ paragraph_index_in_section=paragraph_index_in_section,
518
+ run_index=run_index,
519
+ child_index=child_index,
520
+ ctrl=child,
521
+ field_begin=field_begin,
522
+ current_value=current_value,
523
+ has_end=end_position is not None or span is not None,
524
+ )
525
+ payload["_paragraph"] = paragraph
526
+ payload["_runs"] = runs
527
+ payload["_begin_run_index"] = run_index
528
+ payload["_begin_child_index"] = child_index
529
+ payload["_end_run_index"] = end_run_index
530
+ payload["_end_child_index"] = end_child_index
531
+ payload["_text_nodes"] = text_nodes
532
+ payload["_span"] = span
533
+ matches.append(payload)
485
534
  return matches
486
535
 
487
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
+
488
553
  def _form_field_from_match(doc: "HwpxDocument", match: Mapping[str, Any]) -> FormField:
489
554
  """Build the public :class:`FormField` view from an internal match payload.
490
555
 
@@ -494,17 +559,8 @@ def _form_field_from_match(doc: "HwpxDocument", match: Mapping[str, Any]) -> For
494
559
  ``field_type``) that 5.x exposed as separate dict keys (design §2.3).
495
560
  """
496
561
 
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
- )
562
+ location = _match_location(match)
563
+ parameters = _match_parameters(match)
508
564
  field_begin = match["_field_begin"]
509
565
  editable = (field_begin.get("editable") or "").strip().lower() in {"1", "true"}
510
566
  return FormField(
@@ -536,6 +592,107 @@ def list_form_fields(doc: "HwpxDocument") -> tuple[FormField, ...]:
536
592
  return tuple(_form_field_from_match(doc, match) for match in _iter_form_field_matches(doc))
537
593
 
538
594
 
595
+ def _match_location(match: Mapping[str, Any]) -> FieldLocation:
596
+ return FieldLocation(
597
+ section_index=match["section_index"],
598
+ paragraph_index=match["paragraph_index"],
599
+ paragraph_index_in_section=match["paragraph_index_in_section"],
600
+ run_index=match["run_index"],
601
+ child_index=match["child_index"],
602
+ )
603
+
604
+
605
+ def _match_parameters(match: Mapping[str, Any]) -> tuple[FieldParameter, ...]:
606
+ return tuple(
607
+ FieldParameter(name=parameter.get("name", ""), value=parameter.get("value", ""))
608
+ for parameter in match.get("parameters", [])
609
+ )
610
+
611
+
612
+ def _field_type_is(field_type: str) -> Any:
613
+ def accept(_ctrl: Any, field_begin: Any) -> bool:
614
+ return (field_begin.get("type") or "").strip().upper() == field_type
615
+
616
+ return accept
617
+
618
+
619
+ def _cell_address(element: Any) -> tuple[int, int] | None:
620
+ """``(row, column)`` of the innermost table cell holding *element*, else ``None``."""
621
+
622
+ node = element.getparent()
623
+ while node is not None:
624
+ if _local_name(node) == "tc":
625
+ address = node.find(f"{_HP}cellAddr")
626
+ if address is None:
627
+ return None
628
+ try:
629
+ return int(address.get("rowAddr", "")), int(address.get("colAddr", ""))
630
+ except ValueError:
631
+ return None
632
+ node = node.getparent()
633
+ return None
634
+
635
+
636
+ def list_formula_fields(doc: "HwpxDocument") -> tuple[FormulaField, ...]:
637
+ """Return the table formulas Hancom saved (``fieldBegin type="FORMULA"``), in
638
+ document order, with the values Hancom wrote. Nothing is recomputed."""
639
+
640
+ formulas: list[FormulaField] = []
641
+ for match in _iter_field_matches(doc, _field_type_is("FORMULA")):
642
+ parameters = match["parameters"]
643
+ command = _field_parameter_value(parameters, "Command")
644
+ formulas.append(
645
+ FormulaField(
646
+ field_id=match["field_id"],
647
+ # Hancom also writes the formula as the head of its Command
648
+ # ("=SUM(A1:A3)??%g,;;6"); read it there when Formula is absent.
649
+ formula=_field_parameter_value(parameters, "Formula") or command.split("??", 1)[0],
650
+ result_format=_field_parameter_value(parameters, "ResultFormat"),
651
+ last_result=_field_parameter_value(parameters, "LastResult"),
652
+ command=command,
653
+ value=match["current_value"],
654
+ location=_match_location(match),
655
+ cell_address=_cell_address(match["_paragraph"].element),
656
+ parameters=_match_parameters(match),
657
+ element=match["_field_begin"],
658
+ )
659
+ )
660
+ return tuple(formulas)
661
+
662
+
663
+ def list_bookmarks(doc: "HwpxDocument") -> tuple[Bookmark, ...]:
664
+ """Return every bookmark in document order, in either form Hancom saves it
665
+ (see :class:`~hwpx.objects.Bookmark`), those in table cells and objects included."""
666
+
667
+ fields = {
668
+ match["_field_begin"]: match
669
+ for match in _iter_field_matches(doc, _field_type_is("BOOKMARK"))
670
+ }
671
+ bookmarks: list[Bookmark] = []
672
+ for section_index, paragraph_index, paragraph_index_in_section, _p, _view, runs in _iter_content_paragraphs(doc):
673
+ for run_index, run in enumerate(runs):
674
+ for child_index, child in enumerate(run):
675
+ if _local_name(child) != "ctrl":
676
+ continue
677
+ location = FieldLocation(
678
+ section_index=section_index,
679
+ paragraph_index=paragraph_index,
680
+ paragraph_index_in_section=paragraph_index_in_section,
681
+ run_index=run_index,
682
+ child_index=child_index,
683
+ )
684
+ for mark in child:
685
+ if mark.tag == f"{_HP}bookmark":
686
+ name = mark.get("name", "")
687
+ if name:
688
+ bookmarks.append(Bookmark(name, "point", "", location, mark))
689
+ elif mark in fields:
690
+ name = (mark.get("name") or "").strip()
691
+ if name:
692
+ bookmarks.append(Bookmark(name, "field", fields[mark]["current_value"], location, mark))
693
+ return tuple(bookmarks)
694
+
695
+
539
696
  def _named_cells(paragraphs: Any) -> Iterator[Any]:
540
697
  for paragraph in paragraphs:
541
698
  for table in paragraph.tables:
@@ -1097,7 +1254,7 @@ def fill_form_field(
1097
1254
 
1098
1255
  _clear_form_field_layout_cache(paragraph.element)
1099
1256
  paragraph.section.mark_dirty()
1100
- updated = _iter_form_field_matches(doc)[int(match["index"])]
1257
+ updated = _refresh_form_field_match(doc, match)
1101
1258
  after_style = _field_run_style_snapshot(
1102
1259
  doc,
1103
1260
  updated["_runs"],
@@ -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(