在簿记簿末尾创建定义/定理索引

Create index of definitions / theorems at end of bookdown book

为了 reader 方便,我想在我的 bookdown 书的末尾包含一个用 markdown 编写的书正文定义的简单列表或索引。即使用自定义块创建的,如下所示:

```{definition, bar, echo=T}
A bar is defined here as a foo-like thing.
```

(我需要的是定义,但其他人可能喜欢定理列表等。不知道图表列表是否可以用同样的方式覆盖?)

感谢@yihui 我知道knitr::all_labels(engine == 'definition')是我的朋友

所以我可以在书末的任何地方这样做,通常是在结尾:

```{r comment="",results="asis",echo=FALSE}
knitr::all_labels(engine == 'definition') %>% unlist %>% paste0("\n\n","\@ref(def:",.,"): ",.,"\n\n",collapse="\n\n") %>% cat

```

打印这个:

1: bar

2: foobar

带有可点击的数字。没关系。但是,如果在每个标签之后也可以打印实际定义,那不是很好吗? (块的内容在 knitr::all_labels(engine == 'definition'))

中不可用

这是一个使用输出格式 bookdown::html_document2 的示例,它也应该适用于任何其他图书输出格式:

---
title: "Test Definitions"
output: bookdown::html_document2
---

```{r setup, include=FALSE}
def_list = list()
knitr::knit_hooks$set(engine = function(before, options) {
  if (before && options$engine == 'definition') {
    # collect definition terms from options$name
    def_list[[options$label]] <<- options$name
  }
  NULL
})
```

```{definition, d1, name='Foo'}
Foo is defined as ...
```

```{definition, d2, name='Bar'}
Bar is defined as ...
```

All definitions in this document:

```{r echo=FALSE, results='asis'}
def_list = unlist(def_list)
cat(sprintf('- \@ref(def:%s) %s', names(def_list), def_list), sep = '\n')
```

输出:

基本思路是使用chunk hook来收集定义标签和名字,最后打印出来。您不必使用块选项 name。它可以是任意选项,例如 term。选项 name 是特殊的,因为定义的名称将打印在输出中。如果你不喜欢那样,你可以使用,例如,term:

```{definition, d2, term='Bar'}
Bar is defined as ...
```

完美,所以加上一辉的建议,这也打印出了定义,不用费心名字,只需要标签就可以了:

```{definition, 'Bar',echo=T,cache=F}
Bar is defined as something
```

```{definition, 'Bar2',echo=T,cache=F}
Bar2 is defined as something else.
```

Here are all the definitions in this book.

```{r comment="",results="asis",echo=FALSE,cache=F}


for(x in knitr::all_labels(engine == 'definition')){
   paste0("\n\n","\@ref(def:",x,"): ",x,"\n\n>",knitr:::knit_code$get(x),collapse="\n\n") %>% cat
} 

```

... 产生这个:

这是本书中的所有定义。

1:酒吧

Bar is defined as something

2: 酒吧 2

Bar2 is defined as something else.