Skip to content

Instantly share code, notes, and snippets.

@debruine
Last active April 15, 2022 12:19
Show Gist options
  • Save debruine/b6533b5f393c5c00586557618a206a3b to your computer and use it in GitHub Desktop.
Save debruine/b6533b5f393c5c00586557618a206a3b to your computer and use it in GitHub Desktop.
Replace figure captions in r chunk headers in Rmd files with text captions
# replace figure captions like:
#
# ```{r myfigure, fig.cap = "This is my figure."}
#
# with text captions like this:
#
# (ref:myfigurelab) This is my figure.
#
# ```{r myfigure, fig.cap = "(ref:myfigurelab)"}
# https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html#text-references
# get the files to search
files <- list.files(pattern = "\\.Rmd", full.names = TRUE)
names(files) <- basename(files)
# set the directory to save in (don't overwrite -- this is experimental)
newdir <- "new_Rmds"
if (!dir.exists(newdir)) dir.create(newdir)
# iterate over files
for (f in files) {
# find r chunk lines with figure captions
# only finds " captions, not ' -- fix this later
lines <- readLines(f)
figcaps <- which(grepl("^```\\{r.*fig\\.cap\\s*=\\s*\"[^ref:]", lines))
figcaps <- rev(figcaps)
for (l in figcaps) {
# read a line with a figcap
x <- lines[l]
# extract the original fig.cap and chunk name
orig_figcap <- stringr::str_extract(x, "fig\\.cap\\s*=\\s*\".+\"")
chunkname <- stringr::str_extract(x, "^```\\{r,?\\s+[^(,| )]+")
# make the label and new figure caption for the r chunk
label <- gsub("^```\\{r,?\\s+", "", chunkname)
label <- paste0(label, "lab")
new_r_figcap <- paste0("fig.cap=\"(ref:", label, ")\"")
# make the new r chunk header and caption
new_r <- gsub(orig_figcap, new_r_figcap, x, fixed = TRUE)
newcap <- gsub("fig\\.cap\\s*=\\s*\"", "", orig_figcap)
newcap <- gsub("\"$", "", newcap)
newcap <- paste0("(ref:", label, ") ", newcap)
# replace the old r chunk header with the caption and new chunk header
lines[l] <- paste0("\n\n", newcap, "\n\n", new_r)
}
# write new file
write(lines, file.path(newdir, basename(f)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment