[This question was posed in a Quarto discussion, but they deemed it not a Quarto problem. I'm hoping to get some help here.]
I'm writing a book with multiple chapters and wish to generate a packages.bib file at
the end containing citations for all the packages that were loaded via library()
while the book is compiled by "Render book". I know how to do this for a vignette, but not
for a multi-chapter quarto book.
In vignettes I use the following to automatically generate a packages.bib file for all
the packages used, so that I can easily cite them as needed:
In the preamble I list a few packages which may be referred to in the text, but not
actually loaded by library()
# packages to be cited here. Code at the end automatically updates packages.bib
.to.cite <- c("nnet", "geomtextpath")
Then, at the end, just before ## References I use this chunk to join .to.cite with .packages() and write this out using knitr::write_bib():
```{r write-bib, echo = FALSE}
# write a packages.bib file of the packages (.packages()) that have been used here
pkgs <- unique(c(.to.cite, .packages()))
knitr::write_bib(pkgs, file = here::here("vignettes", "packages.bib"))
```
Maybe you can do a similar process but differently. Quarto books differs by the fact R will be run for each file separatly. So you can't store your package list in a R value in the session. You need to store it on disk or any persistent storage.
Now at the end of each .qmd, you could add a chunk that would store the loaded package, and other packages in a file on disk, and at the end produce the bib file. Maybe you could produce the bib file each time, and append to it too (There are packages to read and write bib file like CRAN - Package rbibutils or CRAN - Package bibtex) .
Though the order of execution matters. By "at the end" it could be