代码注解

概述

Quarto 中的代码块和可执行代码单元格可以包含基于行的注释。基于行的注释提供了一种为代码行附加解释的方法,就像脚注一样。

例如,这段代码使用注释以浅显的语言描述了 R dplyr 管道中的步骤:

library(tidyverse)
library(palmerpenguins)
1penguins |>
2  mutate(
    bill_ratio = bill_depth_mm / bill_length_mm,
    bill_area  = bill_depth_mm * bill_length_mm
  )
1
Take penguins, and then,
2
add new columns for the bill ratio and bill area.

默认 HTML 注释样式在代码块下方的列表中显示注释。单击列表中的注释编号会突出显示代码中的相关行。其他 HTML styles 隐藏注释,当用户悬停或选择标记时在工具提示中显示它们,如 Revealjs 演示文稿的此示例所示:

format: revealjs

PDF 格式还允许注释、编号以及在代码下方显示注释文本。在其他格式中,例如 Word 和 GitHub Markdown,注释是用注释文本适用的代码行(或多行代码)来标记的。

Screenshot of output in PDF format showing code annotation.

``` r
library(tidyverse)
library(palmerpenguins)
penguins |>
  mutate(
    bill_ratio = bill_depth_mm / bill_length_mm,
    bill_area  = bill_depth_mm * bill_length_mm
  )
```

Line 3  
Take `penguins`, and then,

Lines 4-7  
add new columns for the bill ratio and bill area.

要将代码注释添加到代码块,您需要添加两件事:代码单元格中特殊格式的代码注释,以及代码单元格下方包含注释文本的有序列表。阅读Annotation Syntax了解更多内容。

code-annotations选项控制注释在 HTML 格式(below(默认)hoverselect)中的显示方式,以及在所有格式中的显示方式,是否禁用注释(false),或者是否应从输出中删除注释(none)。

注释语法

代码单元的注释由两个相关元素组成:

  1. 每个带注释的行都应以注释(使用代码单元的语言注释字符)结尾,后跟一个空格,然后是用尖括号括起来的注释编号(例如 #<2>)。如果注释跨越多行,您可以重复注释编号。

  2. 紧随代码单元格之后出现的有序列表,其中包含每个注释的内容。有序列表中的每个编号项目将对应于具有相同注释编号的代码行。

例如,概述中的注释是通过以下内容生成的:

```r
library(tidyverse)
library(palmerpenguins)
penguins |>                                      # <1>
  mutate(                                        # <2>
    bill_ratio = bill_depth_mm / bill_length_mm, # <2>
    bill_area  = bill_depth_mm * bill_length_mm  # <2>
  )                                              # <2>
```
1. Take `penguins`, and then,
2. add new columns for the bill ratio and bill area.

注释式样

对于 HTML 输出,您可以使用文档选项设置三种注释样式code-annotations:

below

默认情况下(或如果code-annotations: below指定),代码注释 文本将显示在代码单元格下方。

hover

当用户将鼠标悬停在一行代码的注释标记上时,将显示代码注释文本。

select

当用户单击注释标记(选择它)时,将显示代码注释文本。再次单击注释标记即可消除注释文本。

例如,要将显示样式设置为悬停,完整的四开本文件将为:

---
code-annotations: hover
---

```r
library(tidyverse)
library(palmerpenguins)
penguins |>                                      # <1>
  mutate(                                        # <2>
    bill_ratio = bill_depth_mm / bill_length_mm, # <2>
    bill_area  = bill_depth_mm * bill_length_mm  # <2>
  )                                              # <2>
```
1. Take `penguins`, and then,
2. add new columns for the bill ratio and bill area.

删除注释 | Removing

对于某些格式,您可能更愿意从输出中删除注释。在这种情况下,您可以设置code-annotations: none,这将从代码中删除注释注释并抑制包含注释文本的有序列表的输出。

禁用注释 | Disabling

code-annotations: false您可以通过在文档中包含该选项来禁用代码注释。这将停止代码注释的处理,并让您的代码(包括注释注释)和原始有序列表保持原样。