paleolimbot / rbbt

R Interface to the Better BiBTex Zotero Connector
145 stars 26 forks source link

Easy way to update several `.Rmd` or `.qmd` files #45

Closed danielvartan closed 1 year ago

danielvartan commented 1 year ago

Hi,

First, awesome package!

Is there an easy way to update a project's references file (e.g., references.json) when dealing with several .Rmd or .qmd (e.g., when writing a Quarto book)? The only way I could figure out how to do this was running the chunk and the function below.

I thought of using rbbt::bbt_update_bib(), but that would require a manual input of the file path.


.qmd chunk

library(here)
source(here::here("R/bbt_write_quarto_bib.R"))

bbt_write_quarto_bib(
  bib_file = here::here("references.json"), 
  dir = here::here(c("", "qmd")),
  pattern = "\\.qmd$"
  )

bbt_write_quarto_bib.R

require(checkmate, quietly = TRUE)
require(rbbt, quietly = TRUE)
require(stringr, quietly = TRUE)

bbt_write_quarto_bib <- function(bib_file, dir, pattern = "\\.qmd$") {
  checkmate::assert_string(bib_file)
  checkmate::assert_path_for_output(bib_file, overwrite = TRUE)
  checkmate::assert_character(dir)
  for (i in dir) checkmate::assert_directory_exists(i)
  checkmate::assert_string(pattern)

  keys <-
    dir |>
    lapply(function(x) {
      setdiff(
        list.files(x, full.names = TRUE),
        list.dirs(x, recursive = FALSE, full.names = TRUE)
      ) |>
        stringr::str_subset(pattern)
    }) |>
    unlist() |>
    rbbt::bbt_detect_citations() |>
    sort()

  keys <- keys[!keys %in% bbt_types]

  keys <-
    ifelse(
      stringr::str_detect(keys, "\\d", negate = TRUE),
      paste0(keys, "_"),
      keys
    ) |>
    stringr::str_subset("^fig-|^sec-", negate = TRUE)

  rbbt::bbt_write_bib(
    path = bib_file,
    keys = keys,
    overwrite = TRUE
    )

  invisible(NULL)
}

bbt_types <- c(
  "article", "booklet", "conference", "inbook", "incollection", "inproceedings",
  "manual", "mastersthesis", "misc", "phdthesis", "proceedings", "techreport",
  "unpublished"
)
paleolimbot commented 1 year ago

The chunk you have there is more or less what I would have suggested! It may be hard to generalize as something that would live in this package; however, if you're game to prepare a PR that includes tests I am happy to review it!

danielvartan commented 1 year ago

Thanks for the response @paleolimbot . :)

I will prepare a PR with a suggestion for a function like that.

I found that it's better to run a pre-render script with that function while developing Quarto books.