Create an index of definitions / theorems at the end of bookdown book

For reader convenience, I would like to include at the end of my markdown book a simple list or index of definitions from the body of the book. those. created using custom blocks, for example:

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

(My need for definitions, but others may like lists of theorems, etc. Don't know if lists of numbers and tables can be covered equally?)

Thanks @yihui, I know that knitr::all_labels(engine == 'definition')my friend.

Therefore, I can do this anywhere at the end of the book, usually at the end:

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

```

What prints this:

1: bar

2: foobar

With numeric numbers. This is normal. But would it be nice if, after each label, the actual definition could also be printed? (The contents of the blocks are not available in knitr :: all_labels (engine == 'definition'))

+4
2

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')
```

:

definition list

, . chunk name. , , term. name , . , , , term:

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

, , Yihui, , , :

```{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:

2: Bar2

Bar2 .

0

Source: https://habr.com/ru/post/1661548/


All Articles