在 bookdown book 的末尾创建几个索引定义/定理

Create several indices definitions / theorems at end of bookdown book

这个 对我有用,但只适用于一个索引列表。每当我尝试添加另一个列表(例如,对于定理)时,只有在设置垃圾中最后定义的列表才有效。

可能是我没有适配knit_hooks$set()正确:

---
title: "Create several lists"
output: bookdown::html_document2
---

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

thm_list = list()
knitr::knit_hooks$set(engine = function(before, options) {
    if (before && options$engine == 'theorem') {
    # collect theorem terms from options$name
    thm_list[[options$label]] <<- options$name
    }
    NULL
}) 
```

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


```{theorem, t1, name='My first theorem'}
First theorem ...
```

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

```{theorem, t2, name='My second theorem'}
Second theorem ...
```

---

**All definitions:**

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

**All theorems:**

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

输出:

问题是您重置了挂钩。因此,您应该设置挂钩 once 来处理两个列表,如下所示:

---
title: "Create several lists"
output: bookdown::html_document2
---

```{r setup, include=FALSE}
def_list = list()
thm_list = list()
knitr::knit_hooks$set(engine = function(before, options) {
    if ( before ) {
        if ( options$engine == "theorem" ) {
            thm_list[[options$label]] <<- options$name
        } else if ( options$engine == "definition" ) {
            def_list[[options$label]] <<- options$name
        }
    }
    NULL
}) 
```

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


```{theorem, t1, name='My first theorem'}
First theorem ...
```

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

```{theorem, t2, name='My second theorem'}
Second theorem ...
```

---

**All definitions:**

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

**All theorems:**

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

然后你得到你想要的输出: