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

Method add_comment

src/docx/comments.py:35–75  ·  view source on GitHub ↗

Add a new comment to the document and return it. The comment is added to the end of the comments collection and is assigned a unique comment-id. If `text` is provided, it is added to the comment. This option provides for the common case where a comment contains a mo

(self, text: str = "", author: str = "", initials: str | None = "")

Source from the content-addressed store, hash-verified

33 return len(self._comments_elm.comment_lst)
34
35 def add_comment(self, text: str = "", author: str = "", initials: str | None = "") -> Comment:
36 """Add a new comment to the document and return it.
37
38 The comment is added to the end of the comments collection and is assigned a unique
39 comment-id.
40
41 If `text` is provided, it is added to the comment. This option provides for the common
42 case where a comment contains a modest passage of plain text. Multiple paragraphs can be
43 added using the `text` argument by separating their text with newlines (`"\\\\n"`).
44 Between newlines, text is interpreted as it is in `Document.add_paragraph(text=...)`.
45
46 The default is to place a single empty paragraph in the comment, which is the same
47 behavior as the Word UI when you add a comment. New runs can be added to the first
48 paragraph in the empty comment with `comments.paragraphs[0].add_run()` to adding more
49 complex text with emphasis or images. Additional paragraphs can be added using
50 `.add_paragraph()`.
51
52 `author` is a required attribute, set to the empty string by default.
53
54 `initials` is an optional attribute, set to the empty string by default. Passing |None|
55 for the `initials` parameter causes that attribute to be omitted from the XML.
56 """
57 comment_elm = self._comments_elm.add_comment()
58 comment_elm.author = author
59 comment_elm.initials = initials
60 comment_elm.date = dt.datetime.now(dt.timezone.utc)
61 comment = Comment(comment_elm, self._comments_part)
62
63 if text == "":
64 return comment
65
66 para_text_iter = iter(text.split("\n"))
67
68 first_para_text = next(para_text_iter)
69 first_para = comment.paragraphs[0]
70 first_para.add_run(first_para_text)
71
72 for s in para_text_iter:
73 comment.add_paragraph(text=s)
74
75 return comment
76
77 def get(self, comment_id: int) -> Comment | None:
78 """Return the comment identified by `comment_id`, or |None| if not found."""

Calls 3

add_paragraphMethod · 0.95
CommentClass · 0.85
add_runMethod · 0.80