Skip to content

Instantly share code, notes, and snippets.

@grimbough
Created October 19, 2022 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grimbough/6014ec0a5aeeac49487536db68074dfb to your computer and use it in GitHub Desktop.
Save grimbough/6014ec0a5aeeac49487536db68074dfb to your computer and use it in GitHub Desktop.
Adding anchor links to equations in Quarto
## expects to be passed HTML that has already been read with readLines()
insert_anchor_JS <- function(lines) {
## we'll look for this JavaScript entry in the html
pattern <- "const anchorJS = new window.AnchorJS();"
## this is the new JavaScript to insert
insert <- " const anchorJS_eq = new window.AnchorJS();
anchorJS_eq.options = {
placement: 'left',
class: 'eq-link',
icon: icon
};
anchorJS_eq.add('.anchored-eq');"
## Look for the existing JS line, and if we find it
## insert the new JS before the original declaration
line <- grep(pattern = pattern, x = lines, fixed = TRUE)
if(length(line) == 1) {
lines[line] <- paste(insert, lines[line], sep = "\n")
}
return(lines)
}
## input is the path to an HTML file
add_equation_links <- function(input) {
## read HTML file and add the second AnchorJS declaration
lines <- readLines(input, warn = FALSE) |>
insert_anchor_JS()
## find all spans that have an equation identifier
equation_lines <- grep(x = lines, "span.*eq-")
## iterate over equation lines and add the new class
for(j in seq_along(equation_lines)) {
## extract only the equation id from the line
equation_id <- sub(lines[equation_lines[j]],
pattern = ".*(eq-[[:alnum:]]*).*",
replacement = "\\1")
## create a new span with additional class and data-anchor-id attributes
new_line <- sub(x = lines[equation_lines[j]],
pattern = "span",
replacement = sprintf('span class="anchored-eq" data-anchor-id="%s"', equation_id))
## replace the old equation line
lines[equation_lines[j]] <- new_line
}
## overwrite the input HTML file
writeLines(text = lines, con = input)
}
html_files <- list.files(path = Sys.getenv("QUARTO_PROJECT_OUTPUT_DIR"),
pattern = ".html",
full.names = TRUE)
invisible(lapply(html_files, FUN = add_equation_links))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment