通过 Rmarkdown 添加 MS Word 评论

Add a MS Word Comment via Rmarkdown

有没有办法通过 R markdown 文件添加 MS Word "Comment"?我正在使用 reference_docx,并且熟悉添加自定义样式...但还没有弄清楚如何让评论像这样显示在旁边:

澄清一下:我想在我的纯文本 Rmd 文件中添加一个标签(或其他东西?),这样当我 "knit" 生成的 MS Word 文档有一个呈现的评论。

Markdown(和RMarkdown)用于纯文本写作。因此,您不能像在word中那样添加评论(并且可以在屏幕的某个地方弹出)。

不过,您可以在 RMarkdown 中添加纯文本注释,在渲染到 Docx 后,您可以在 Word 中看到普通的文字注释(它也适用于从 Word 到 RMarkdown)。

有关详细信息,请参阅 redoc library

实际上,这是可能的。是的,Markdown(和 RMarkdown)是用于纯文本写作的,但它们是使用 pandoc 翻译的。所以我用谷歌搜索并找到了以下代码,效果很好:

---
title: "test"
output:
  word_document: default
---

This text contains a [This is the comment]{.comment-start id="0" author="Johannes G." date="2020-01-13T10:12:00Z"}comment.[]{.comment-end id="0"}.

这会在编织成其他格式时造成一些混乱,因此您可能需要考虑改用 R 函数:

```{r echo=FALSE}
word_comment <- function(comment, highlight = "") {
  if (isTRUE(knitr:::pandoc_to() == "docx")) {
    paste0('[', comment, ']{.comment-start id="0" author="Johannes G."',
           'date="2020-01-13T10:12:00Z"}', highlight, '[]{.comment-end id="0"}')
  }
}
```

This text contains a `r word_comment("This is the comment", "comment.")`.

代码可能可以改进,但我找不到创建评论的块的文档,所以目前它工作得很好。

我想扩展@JBGruber 的精彩回答:

此代码适用于 html 和单词作为输出:

```{css, echo=FALSE}
span.comment-start{
    background: #e0f3db;
}
span.comment-end{
    background: #e0f3db;
}
span.comment-start::after{
    content: " (" attr(author) ", " attr(date) ") [";
}
span.comment-end::before{
    content: "]"
}
span.comment-text{
    background: #fdbb84;
}

```

```{r, echo=FALSE}
commentN <- 0
cmt <- function(txt, cm, author, date = "2021-01-01", comN = commentN){
  cmt_str <- paste0('<span class="comment-text">[',cm,']{.comment-start id="', comN, '" author="', author, '" date="', date, '"}', txt, '[]{.comment-end id="',commentN,'"}</span>')
  assign("commentN", commentN + 1, envir = .GlobalEnv)
  return(cmt_str)
}
```

并且您可以通过调用

在文本中添加评论
`r cmt("Text to be commented", "The comment itself", "myName", "Date")`