docx_plus.publishing.toc¶
Table of Contents via the TOC complex field. The instruction
string is assembled from the levels, hyperlink, and
page_numbers kwargs to match what Word's "Insert → Table of
Contents" UI produces. Word populates the visible body of the TOC
on next open; call
docx_plus.fields.mark_fields_dirty before
saving so the recalculation actually fires.
Architecture walkthrough: ARCHITECTURE.md §7.10.
docx_plus.publishing.toc ¶
Table of Contents — TOC complex field.
A TOC in Word is a single complex field whose instruction text
encodes which heading levels to include, whether entries are
hyperlinks, and a handful of other display switches. Word populates
the visible body of the TOC on next open (or when the user presses
F9) — see docx_plus.fields.mark_fields_dirty.
This module imports only from docx_plus.core (SPEC §9.1).
add_toc ¶
add_toc(
paragraph: Paragraph,
*,
levels: tuple[int, int] = (1, 3),
hyperlink: bool = True,
page_numbers: bool = True,
additional_styles: Sequence[tuple[str, int]] | None = None,
) -> etree._Element
Append a Table of Contents complex field to paragraph.
Emits a TOC field whose instruction text matches what Word's
"Insert → Table of Contents" UI produces. The field has no visible
result until Word populates it; for that to happen on next open,
call :func:docx_plus.fields.mark_fields_dirty before saving.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paragraph
|
Paragraph
|
A python-docx :class: |
required |
levels
|
tuple[int, int]
|
Inclusive |
(1, 3)
|
hyperlink
|
bool
|
When |
True
|
page_numbers
|
bool
|
When |
True
|
additional_styles
|
Sequence[tuple[str, int]] | None
|
Optional sequence of |
None
|
Returns:
| Type | Description |
|---|---|
_Element
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
from docx import Document from docx_plus.publishing import add_toc from docx_plus.fields import mark_fields_dirty doc = Document() add_toc(doc.add_paragraph(), levels=(1, 2), ... additional_styles=[("Caption", 4)]) mark_fields_dirty(doc)