caption
caption
¶
Captions — a label, a self-renumbering sequence field, and a cross-reference target.
Everything a caption is built from already existed: Paragraph.add_field(), the SEQ
builder in docx.fields, REF for the reference, and bookmarks. What was missing
was the one call that puts them together, because assembling one by hand means:
- insert a paragraph in the "Caption" style
- add the literal label text and separator
- add a
SEQ Figure \* ARABICfield - wrap the whole thing in a bookmark with a
_Ref-prefixed name and an unused id - remember that name so a later
REFfield can point at it
Step 4 is the one people get wrong. Word's own cross-reference dialogue offers only
targets whose bookmark name follows the _Ref convention, so a caption bookmarked with
an arbitrary name is invisible in it — the caption works, and the user cannot reference
it from the UI.
Caption
¶
Caption(
paragraph: Paragraph, bookmark_name: str, label: str
)
A caption paragraph, carrying the bookmark name a cross-reference points at.
Returned by Document.add_caption. It is a thin wrapper over the paragraph; paragraph is the Paragraph itself for any further formatting.
Source code in src/docx/caption.py
bookmark_name
property
¶
The bookmark name a cross-reference to this caption uses:
Generated in Word's own _Ref shape, so Word's cross-reference dialogue offers
this caption as a target. That shape also means the bookmark does not appear in
Document.bookmarks, which leaves out the ones Word maintains for
itself; Bookmarks.iter_all reaches it.
text
property
¶
The caption's text as the document currently reads it.
The number is a SEQ field, so it shows only once Word has computed it; before
that this reads as the label and the caption text with the number missing.
number
property
¶
The number Word last computed for this caption, or None.
A SEQ field's result is cached in the document, so this reads back after a
round trip through Word. It is None for a caption this library has just
written, which has no cached result yet.
next_ref_bookmark_name
¶
next_ref_bookmark_name(document_element: object) -> str
A _Ref-prefixed bookmark name unused in the document.
Word derives its own from a timestamp; a counter is used here instead, since a timestamp would make the same document generate different bytes on each run and byte-reproducible output is something this library keeps.
Source code in src/docx/caption.py
add_caption
¶
add_caption(
container: object,
label: str,
text: str = "",
*,
style: str | None = "Caption",
separator: str = " ",
restart_at_heading_level: int | None = None,
before: Paragraph | None = None,
) -> Caption
Build a caption paragraph in container; see Document.add_caption.
Source code in src/docx/caption.py
caption_bookmark_names
¶
caption_bookmark_names(
document_element: object,
) -> tuple[str, ...]
Every _Ref-prefixed bookmark name in the document, in document order.