MCPcopy Index your code
hub / github.com/python-openxml/python-docx / CT_Comments

Class CT_Comments

src/docx/oxml/comments.py:18–88  ·  view source on GitHub ↗

`w:comments` element, the root element for the comments part. Simply contains a collection of `w:comment` elements, each representing a single comment. Each contained comment is identified by a unique `w:id` attribute, used to reference the comment from the document text. The offset of

Source from the content-addressed store, hash-verified

16
17
18class CT_Comments(BaseOxmlElement):
19 """`w:comments` element, the root element for the comments part.
20
21 Simply contains a collection of `w:comment` elements, each representing a single comment. Each
22 contained comment is identified by a unique `w:id` attribute, used to reference the comment
23 from the document text. The offset of the comment in this collection is arbitrary; it is
24 essentially a _set_ implemented as a list.
25 """
26
27 # -- type-declarations to fill in the gaps for metaclass-added methods --
28 comment_lst: list[CT_Comment]
29
30 comment = ZeroOrMore("w:comment")
31
32 def add_comment(self) -> CT_Comment:
33 """Return newly added `w:comment` child of this `w:comments`.
34
35 The returned `w:comment` element is the minimum valid value, having a `w:id` value unique
36 within the existing comments and the required `w:author` attribute present but set to the
37 empty string. It's content is limited to a single run containing the necessary annotation
38 reference but no text. Content is added by adding runs to this first paragraph and by
39 adding additional paragraphs as needed.
40 """
41 next_id = self._next_available_comment_id()
42 comment = cast(
43 CT_Comment,
44 parse_xml(
45 f'<w:comment {nsdecls("w")} w:id="{next_id}" w:author="">'
46 f" <w:p>"
47 f" <w:pPr>"
48 f' <w:pStyle w:val="CommentText"/>'
49 f" </w:pPr>"
50 f" <w:r>"
51 f" <w:rPr>"
52 f' <w:rStyle w:val="CommentReference"/>'
53 f" </w:rPr>"
54 f" <w:annotationRef/>"
55 f" </w:r>"
56 f" </w:p>"
57 f"</w:comment>"
58 ),
59 )
60 self.append(comment)
61 return comment
62
63 def get_comment_by_id(self, comment_id: int) -> CT_Comment | None:
64 """Return the `w:comment` element identified by `comment_id`, or |None| if not found."""
65 comment_elms = self.xpath(f"(./w:comment[@w:id='{comment_id}'])[1]")
66 return comment_elms[0] if comment_elms else None
67
68 def _next_available_comment_id(self) -> int:
69 """The next available comment id.
70
71 According to the schema, this can be any positive integer, as big as you like, and the
72 default mechanism is to use `max() + 1`. However, if that yields a value larger than will
73 fit in a 32-bit signed integer, we take a more deliberate approach to use the first
74 ununsed integer starting from 0.
75 """

Callers

nothing calls this directly

Calls 1

ZeroOrMoreClass · 0.90

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…