docx_plus.bookmarks.anchor¶
Paired <w:bookmarkStart> / <w:bookmarkEnd> body markers with a
shared w:id and a human-readable w:name. Cross-references key off
the name. python-docx provides no abstraction for bookmarks; this
module fills the gap, validating names against Word's rules
([A-Za-z_][A-Za-z0-9_]{0,39}) so silently broken cross-references
become impossible.
Architecture walkthrough: ARCHITECTURE.md §7.8.
docx_plus.bookmarks.anchor ¶
Bookmark anchoring — body-side <w:bookmarkStart> / <w:bookmarkEnd>.
A bookmark is a pair of empty marker elements with a shared w:id and
a human-readable w:name. python-docx provides no abstraction for
either, so this module fills the gap with :func:add_bookmark and
:func:delete_bookmark. Cross-references key off the bookmark name,
which is what REF / PAGEREF field instructions accept.
This module imports only from docx_plus.core and the sibling
docx_plus.bookmarks.registry (SPEC §9.1).
BookmarkRef
dataclass
¶
Handle for an inserted bookmark.
Attributes:
| Name | Type | Description |
|---|---|---|
bookmark_id |
int
|
The |
name |
str
|
The |
start_element |
_Element
|
The |
end_element |
_Element
|
The |
add_bookmark ¶
add_bookmark(
target: BookmarkTarget,
name: str,
*,
id_registry: BookmarkIdRegistry | None = None,
) -> BookmarkRef
Anchor a bookmark to a run, paragraph, or run range.
Writes a paired <w:bookmarkStart> / <w:bookmarkEnd>
bracketing the target. The bookmark id is minted from
id_registry (or a fresh one if not supplied). The name is
validated against Word's bookmark name rules: it must start with a
letter or underscore, contain only letters, digits, and underscores,
and be at most 40 characters long.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
BookmarkTarget
|
Where the bookmark anchors. Same shapes as
:func: |
required |
name
|
str
|
Bookmark name. Must match
|
required |
id_registry
|
BookmarkIdRegistry | None
|
Pre-existing registry to share across an editing session. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
BookmarkRef
|
class: |
BookmarkRef
|
elements. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For invalid names, empty paragraph targets, or unsupported target shapes. |
Example
from docx import Document from docx_plus.bookmarks import add_bookmark doc = Document() p = doc.add_paragraph("Section 1 intro") ref = add_bookmark(p, "section_1_intro")
Source code in docx_plus/bookmarks/anchor.py
delete_bookmark ¶
Remove every bookmark with the given name from doc.
Idempotent — removing a missing bookmark is a no-op. Removing by
name (not id) matches the cross-reference key, so a stale name
referenced by a REF field can be cleared with a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc
|
Document
|
A python-docx Document. |
required |
name
|
str
|
Bookmark name to remove. Matches case-sensitively. |
required |