From 7126f8ca7a36b0ed1b900254627549ccfed138f3 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Tue, 6 Oct 2026 22:20:19 -0400 Subject: [PATCH 1/9] fix: detect Quarto renders from knitr's quarto.version option Quarto 1.9 no longer sets the QUARTO_VERSION environment variable in the R process it renders with, so is_quarto_render() returned FALSE under Quarto: the ggtibble chunk option stopped prefixing fig- to its labels and stopped using fig.subcap for multiple captions. Quarto still sets the knitr package option quarto.version, which knitr's own Quarto test reads, so check that as well as the environment variable. Co-Authored-By: Claude Opus 5.5 --- R/knitr_hook.R | 8 ++++++-- man/ggtibble-knitr-hook.Rd | 3 ++- tests/testthat/test-knitr_hook.R | 10 ++++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/R/knitr_hook.R b/R/knitr_hook.R index 9237d64..0ad9dea 100644 --- a/R/knitr_hook.R +++ b/R/knitr_hook.R @@ -13,7 +13,8 @@ #' form the chunk label is not auto-derived; set `label = ...` explicitly if #' you want a non-default label. #' -#' Under Quarto (detected via the `QUARTO_VERSION` environment variable) the +#' Under Quarto (detected via the knitr package option `quarto.version` or the +#' `QUARTO_VERSION` environment variable) the #' auto-derived label is prefixed with `"fig-"` so `@fig-...` cross-references #' work, and a multi-caption ggtibble is rendered using `fig.subcap` because #' Quarto's cross-reference resolver does not handle vector `fig.cap` on a @@ -114,8 +115,11 @@ is_empty_code <- function(code) { length(code) == 0 || all(trimws(paste(code, collapse = "")) == "") } +# Quarto sets the knitr package option `quarto.version` (knitr's own internal +# Quarto test reads it); older Quarto versions also set `QUARTO_VERSION`. is_quarto_render <- function() { - nzchar(Sys.getenv("QUARTO_VERSION", "")) + nzchar(Sys.getenv("QUARTO_VERSION", "")) || + !is.null(knitr::opts_knit$get("quarto.version")) } deduplicate_label <- function(base) { diff --git a/man/ggtibble-knitr-hook.Rd b/man/ggtibble-knitr-hook.Rd index a8a6b39..87997fe 100644 --- a/man/ggtibble-knitr-hook.Rd +++ b/man/ggtibble-knitr-hook.Rd @@ -30,7 +30,8 @@ form the chunk label is not auto-derived; set \code{label = ...} explicitly if you want a non-default label. } -Under Quarto (detected via the \code{QUARTO_VERSION} environment variable) the +Under Quarto (detected via the knitr package option \code{quarto.version} or the +\code{QUARTO_VERSION} environment variable) the auto-derived label is prefixed with \code{"fig-"} so \verb{@fig-...} cross-references work, and a multi-caption ggtibble is rendered using \code{fig.subcap} because Quarto's cross-reference resolver does not handle vector \code{fig.cap} on a diff --git a/tests/testthat/test-knitr_hook.R b/tests/testthat/test-knitr_hook.R index 8a4aa9c..14211c8 100644 --- a/tests/testthat/test-knitr_hook.R +++ b/tests/testthat/test-knitr_hook.R @@ -87,6 +87,16 @@ test_that("is_quarto_render reads QUARTO_VERSION", { }) }) +test_that("is_quarto_render reads knitr's quarto.version package option", { + withr::local_envvar(c(QUARTO_VERSION = "")) + old <- knitr::opts_knit$get("quarto.version") + withr::defer(knitr::opts_knit$set(quarto.version = old)) + knitr::opts_knit$set(quarto.version = numeric_version("1.9.37")) + expect_true(is_quarto_render()) + knitr::opts_knit$set(quarto.version = NULL) + expect_false(is_quarto_render()) +}) + test_that("deduplicate_label suffixes repeats", { reset_ggtibble_caches() withr::defer(reset_ggtibble_caches()) From e594a3a4cf487515040807640feda90f3ab38d24 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Tue, 6 Oct 2026 22:20:32 -0400 Subject: [PATCH 2/9] feat: footnote and label columns on ggtibble objects ggtibble() gains `footnote` and `label` arguments, glue specifications evaluated per row with the same glue_data() call as `caption`, giving `footnote` and `label` columns that are empty when not given. new_ggtibble() adds both columns as empty strings when absent, so as_ggtibble() from a gglist gets them too, and it refuses labels that repeat or that use characters other than letters, digits, hyphens, underscores, and dots, with classed errors naming the offenders. An outercol used only in `footnote` or `label` no longer triggers the unused-outercols warning. Co-Authored-By: Claude Opus 5.5 --- R/ggtibble.R | 89 +++++++++++++++++++++++++++---- tests/testthat/test-as_ggtibble.R | 11 ++++ tests/testthat/test-ggtibble.R | 81 ++++++++++++++++++++++++++-- 3 files changed, 167 insertions(+), 14 deletions(-) diff --git a/R/ggtibble.R b/R/ggtibble.R index e9d616f..48b6be2 100644 --- a/R/ggtibble.R +++ b/R/ggtibble.R @@ -11,7 +11,9 @@ ggplot2::ggplot #' #' @param data The data.frame to plot #' @param ... Passed to subsequent methods (usually passed to `gglist()`) -#' @return A data.frame with a column named "data_plot" with the data to plot, "figure" with the gglist, and "caption" with the captions +#' @return A data.frame with a column named "data_plot" with the data to plot, +#' "figure" with the gglist, "caption" with the captions, "footnote" with the +#' footnotes, and "label" with the figure labels #' @export ggtibble <- function(data, ...) { UseMethod("ggtibble") @@ -21,12 +23,21 @@ ggtibble <- function(data, ...) { #' @inheritParams ggplot2::ggplot #' @param outercols The columns to have outside the nesting #' @param caption The glue specification for creating the caption +#' @param footnote The glue specification for creating the footnote, a note +#' rendered under each figure and kept with it (see "Footnotes and labels" in +#' [knit_print.gglist()]). The default `""` gives no footnote. +#' @param label The glue specification for creating each figure's label, its +#' identifier for cross-references and the base name of its image file. +#' Labels must be unique and may contain only letters, digits, hyphens, +#' underscores, and dots. Under Quarto, start them with `fig-` so that +#' `@fig-...` cross-references resolve. The default `""` gives no label. #' @param labs Labels to add via `labs_glue()` #' @returns A `ggtibble` object which is a tibble with columns named "figure" #' which is a `gglist` object (a list of ggplots), "data_plot" which is the a #' list of data.frames making up the source data used for each individual -#' plot, "caption" which is the text to use for the plot caption, and all of -#' the `outercols` used for nesting. +#' plot, "caption" which is the text to use for the plot caption, "footnote" +#' which is the text to show under the plot, "label" which is the plot's +#' identifier, and all of the `outercols` used for nesting. #' @examples #' d_plot <- #' data.frame( @@ -48,28 +59,29 @@ ggtibble <- function(data, ...) { #' ggplot2::geom_line() #' knit_print(all_plots) #' @export -ggtibble.data.frame <- function(data, mapping = ggplot2::aes(), ..., outercols = group_vars(data), labs = list(), caption = "") { +ggtibble.data.frame <- function(data, mapping = ggplot2::aes(), ..., outercols = group_vars(data), labs = list(), caption = "", footnote = "", label = "") { if (!tibble::is_tibble(data)) { data <- tibble::as_tibble(as.data.frame(data)) } d_plot <- tidyr::nest(.data = data, data_plot = !tidyr::all_of(outercols)) d_plot$figure <- gglist(data = d_plot$data_plot, mapping = mapping, ...) - # Check that all `outercols` are used either in the `caption` or the `labs` - # Extract all expressions used in arguments that will be glued + # Check that all `outercols` are used in an argument that will be glued glued_expr <- unlist(lapply( - X = append(labs, list(caption)), FUN = extract_glue_expr + X = append(labs, list(caption, footnote, label)), FUN = extract_glue_expr )) unused_outercols <- unique(setdiff(outercols, glued_expr)) if (length(unused_outercols) > 0) { warning( - "The following `outercols` are not used in `caption` or `labs`: ", + "The following `outercols` are not used in `caption`, `footnote`, `label`, or `labs`: ", paste0("`", unused_outercols, "`", collapse = ", ") ) } d_plot$caption <- glue::glue_data(d_plot, caption) + d_plot$footnote <- glue::glue_data(d_plot, footnote) + d_plot$label <- glue::glue_data(d_plot, label) d_plot <- new_ggtibble(d_plot) if (length(labs) > 0) { d_plot$figure <- @@ -85,7 +97,9 @@ ggtibble.data.frame <- function(data, mapping = ggplot2::aes(), ..., outercols = #' Create a new `ggtibble` object #' #' @param x A data.frame with a column named "figure" and "caption", and where -#' the "figure" column is a ggtibble. +#' the "figure" column is a ggtibble. The "footnote" and "label" columns are +#' added as empty strings when absent. Non-empty labels must be unique and +#' may contain only letters, digits, hyphens, underscores, and dots. #' @returns The object with a ggtibble class #' @family New ggtibble objects #' @examples @@ -97,10 +111,67 @@ new_ggtibble <- function(x) { if (!inherits(x$figure, "gglist")) { x$figure <- new_gglist(x$figure) } + for (nm in setdiff(c("footnote", "label"), names(x))) { + x[[nm]] <- rep("", nrow(x)) + } + validate_ggtibble_labels(x$label) class(x) <- unique(c("ggtibble", class(x))) x } +#' Get a text column of a ggtibble, reading `NA` and a missing column as empty +#' +#' A ggtibble made before the "footnote" and "label" columns existed (for +#' example, one read back from a cache) lacks them, which reads as all empty. +#' +#' @param x A ggtibble +#' @param name The column name +#' @returns A character vector with one element per row of `x` +#' @noRd +ggtibble_text_column <- function(x, name) { + if (!(name %in% names(x))) { + return(rep("", nrow(x))) + } + ret <- as.character(x[[name]]) + ret[is.na(ret)] <- "" + ret +} + +#' Check figure labels for identifier syntax and uniqueness +#' +#' Empty and `NA` labels mean "no label" and are not checked. +#' +#' @param label A character vector of labels +#' @returns `label`, invisibly; an error of class +#' `ggtibble_error_label_invalid` or `ggtibble_error_label_duplicated` +#' otherwise +#' @noRd +validate_ggtibble_labels <- function(label) { + label <- as.character(label) + given <- label[!is.na(label) & nzchar(label)] + invalid <- unique(given[!grepl("^[A-Za-z0-9_.-]+$", given)]) + if (length(invalid) > 0) { + rlang::abort( + paste0( + "Each `label` may contain only letters, digits, hyphens, underscores, and dots; invalid: ", + paste0("`", invalid, "`", collapse = ", ") + ), + class = "ggtibble_error_label_invalid" + ) + } + duplicated_labels <- unique(given[duplicated(given)]) + if (length(duplicated_labels) > 0) { + rlang::abort( + paste0( + "Each `label` must be unique; duplicated: ", + paste0("`", duplicated_labels, "`", collapse = ", ") + ), + class = "ggtibble_error_label_duplicated" + ) + } + invisible(label) +} + #' @describeIn knit_print.gglist Print the plots in a `ggtibble` object #' @export knit_print.ggtibble <- function(x, ...) { diff --git a/tests/testthat/test-as_ggtibble.R b/tests/testthat/test-as_ggtibble.R index 04bfe54..e28aa0c 100644 --- a/tests/testthat/test-as_ggtibble.R +++ b/tests/testthat/test-as_ggtibble.R @@ -53,3 +53,14 @@ test_that("as_ggtibble handles an empty gglist", { test_that("as_ggtibble errors on unsupported classes", { expect_error(as_ggtibble(1), regexp = "No `as_ggtibble\\(\\)` method") }) + +test_that("as_ggtibble.gglist gives empty footnote and label columns", { + g <- new_gglist(stats::setNames( + list(ggplot2::ggplot(environment = emptyenv()), ggplot2::ggplot(environment = emptyenv())), + c("weight", "horsepower") + )) + gt <- as_ggtibble(g) + expect_equal(gt$footnote, c("", "")) + expect_equal(gt$label, c("", "")) + expect_named(as_ggtibble(new_gglist(list())), c("figure", "caption", "footnote", "label")) +}) diff --git a/tests/testthat/test-ggtibble.R b/tests/testthat/test-ggtibble.R index 277c0c3..05b6b87 100644 --- a/tests/testthat/test-ggtibble.R +++ b/tests/testthat/test-ggtibble.R @@ -1,14 +1,14 @@ test_that("ggtibble", { # Test length 1 v1 <- ggtibble(data.frame(A = 1, B = 2)) - expect_named(v1, expected = c("data_plot", "figure", "caption")) + expect_named(v1, expected = c("data_plot", "figure", "caption", "footnote", "label")) expect_length(v1$figure, 1) expect_equal(v1$data_plot[[1]], tibble::tibble(A = 1, B = 2)) expect_equal(v1$caption, "") # Test length >1 v2 <- ggtibble(data.frame(A = 1:2, B = 3:4), outercols = "A", labs = list(x = "{A}")) - expect_named(v2, expected = c("A", "data_plot", "figure", "caption")) + expect_named(v2, expected = c("A", "data_plot", "figure", "caption", "footnote", "label")) expect_length(v2$figure, 2) expect_equal( v2$data_plot, @@ -21,7 +21,7 @@ test_that("ggtibble", { # Test captioning v3 <- ggtibble(data.frame(A = 1:2, B = 3:4), outercols = "A", caption = "A is {A}") - expect_named(v3, expected = c("A", "data_plot", "figure", "caption")) + expect_named(v3, expected = c("A", "data_plot", "figure", "caption", "footnote", "label")) expect_length(v3$figure, 2) expect_equal( v3$data_plot, @@ -34,7 +34,7 @@ test_that("ggtibble", { # Test labels v4 <- ggtibble(data.frame(A = 1:2, B = 3:4), outercols = "A", labs = list(x = "A is {A}")) - expect_named(v4, expected = c("A", "data_plot", "figure", "caption")) + expect_named(v4, expected = c("A", "data_plot", "figure", "caption", "footnote", "label")) expect_length(v4$figure, 2) expect_equal( v4$data_plot, @@ -191,7 +191,7 @@ test_that("Check that all `outercols` are used either in the `caption` or the `l ) expect_warning( ggtibble(d_plot, ggplot2::aes(x = x, y = y), outercols = c("A", "B"), labs = list(x = "{A}")), - regexp = "The following `outercols` are not used in `caption` or `labs`: `B`", + regexp = "The following `outercols` are not used in `caption`, `footnote`, `label`, or `labs`: `B`", fixed = TRUE ) }) @@ -217,3 +217,74 @@ test_that("%+% works (#16)", { ggplot2::geom_line() expect_s3_class(all_plots %+% ggplot2::aes(y = B), "ggtibble") }) + +# footnote and label columns #### + +test_that("footnote and label columns are built from glue specifications per row", { + v <- ggtibble( + data.frame(A = c("x", "y"), B = 3:4), + outercols = "A", + caption = "Cap {A}", + footnote = "Note on {A}", + label = "fig-{A}" + ) + expect_equal(as.character(v$caption), c("Cap x", "Cap y")) + expect_equal(as.character(v$footnote), c("Note on x", "Note on y")) + expect_equal(as.character(v$label), c("fig-x", "fig-y")) +}) + +test_that("footnote and label default to empty strings", { + v <- ggtibble(data.frame(A = 1:2, B = 3:4), outercols = "A", caption = "{A}") + expect_equal(as.character(v$footnote), c("", "")) + expect_equal(as.character(v$label), c("", "")) +}) + +test_that("an outercol used only in `footnote` or `label` does not warn", { + d_plot <- data.frame(A = 1:2, B = c("u", "v"), x = 1) + expect_silent( + ggtibble(d_plot, outercols = c("A", "B"), caption = "{A}", footnote = "{B}") + ) + expect_silent( + ggtibble(d_plot, outercols = c("A", "B"), caption = "{A}", label = "lab-{B}") + ) +}) + +test_that("duplicated labels are refused with the duplicates named", { + expect_error( + ggtibble(data.frame(A = 1:3, B = c("a", "a", "b")), outercols = c("A", "B"), caption = "{A}", label = "{B}"), + regexp = "Each `label` must be unique; duplicated: `a`", + fixed = TRUE, + class = "ggtibble_error_label_duplicated" + ) +}) + +test_that("labels with characters outside letters, digits, hyphens, underscores, and dots are refused", { + expect_error( + ggtibble(data.frame(A = c("a b", "c:d", "ok_1.x-y")), outercols = "A", label = "{A}"), + regexp = "Each `label` may contain only letters, digits, hyphens, underscores, and dots; invalid: `a b`, `c:d`", + fixed = TRUE, + class = "ggtibble_error_label_invalid" + ) +}) + +test_that("validate_ggtibble_labels ignores empty and NA labels", { + expect_identical(validate_ggtibble_labels(c("", NA, "", "a")), c("", NA, "", "a")) + expect_identical(validate_ggtibble_labels(character()), character()) +}) + +test_that("new_ggtibble adds empty footnote and label columns and validates labels", { + v <- new_ggtibble(tibble::tibble(figure = list(ggplot2::ggplot(), ggplot2::ggplot()), caption = c("a", "b"))) + expect_named(v, c("figure", "caption", "footnote", "label")) + expect_equal(v$footnote, c("", "")) + expect_equal(v$label, c("", "")) + expect_error( + new_ggtibble(tibble::tibble(figure = list(ggplot2::ggplot()), caption = "a", label = "a/b")), + class = "ggtibble_error_label_invalid" + ) +}) + +test_that("ggtibble_text_column reads a missing column and NA as empty", { + x <- tibble::tibble(caption = c("a", NA)) + expect_equal(ggtibble_text_column(x, "caption"), c("a", "")) + expect_equal(ggtibble_text_column(x, "footnote"), c("", "")) +}) From db99ad7a61268f4b3672fc4cc1129e2c38c21b79 Mon Sep 17 00:00:00 2001 From: Bill Denney Date: Tue, 6 Oct 2026 22:20:52 -0400 Subject: [PATCH 3/9] feat: render footnotes and labels per output format A ggtibble with a footnote or a label on any row is now written by knit_print() as markdown, one figure at a time, so each figure carries its own identifier and its footnote stays with it: knitr's plot hook can give neither. One emitter serves every engine: - LaTeX (R Markdown and Quarto): the footnote is inside the float, after the caption, a line break, and in \footnotesize, with the plain caption as the short caption for the List of Figures; the label is the \label{}. Under Quarto a fig- labelled figure is a figure Div with fig-scap; otherwise the float is written as raw LaTeX around the caption markdown so pandoc still converts it. - Quarto to Typst: the figure Div and then the footnote in 0.9em text, both in one #block(breakable: false), as nca.reporter's report_print_figure() does; the footnote stays outside the Div so Quarto still treats the Div as a cross-referenceable figure. - HTML: a figure-footnote Div in a smaller font after the figure. - Word, other pandoc formats, and knitr markdown: a plain paragraph. Images are saved under the chunk's fig.path with its dev, fig.width, fig.height, and dpi, named after the label when there is one. Under Quarto an unlabelled figure gets fig-[-], so each row is its own numbered figure. The chunk needs results = "asis": the ggtibble chunk option sets it for an annotated ggtibble (and leaves fig.cap, fig.subcap, and the fig- chunk label off, since the figures carry their own ids), and knit_print() in a chunk without it is a classed error. A ggtibble without footnotes or labels takes the old path unchanged. knit_print.gglist()'s fig_suffix and filename handling move to helpers that the emitter reuses, and knitr::raw_block() and knitr::fig_path() build the raw fences and image paths. Co-Authored-By: Claude Opus 5.5 --- R/figure_emit.R | 326 ++++++++++++++++++++++ R/gglist.R | 80 +++++- R/ggtibble.R | 6 +- R/knitr_hook.R | 20 +- tests/testthat/test-figure_emit.R | 430 ++++++++++++++++++++++++++++++ tests/testthat/test-knitr_hook.R | 73 ++++- 6 files changed, 906 insertions(+), 29 deletions(-) create mode 100644 R/figure_emit.R create mode 100644 tests/testthat/test-figure_emit.R diff --git a/R/figure_emit.R b/R/figure_emit.R new file mode 100644 index 0000000..140fe4a --- /dev/null +++ b/R/figure_emit.R @@ -0,0 +1,326 @@ +# Figures with footnotes or labels are written as markdown by ggtibble itself +# rather than through knitr's plot hook: the hook cannot give each figure of a +# chunk its own identifier, nor put text between a figure and the next one +# inside one float or unbreakable block. + +#' Does a ggtibble carry a footnote or a label on any row? +#' +#' @param x A ggtibble +#' @returns `TRUE` or `FALSE` +#' @noRd +has_figure_annotations <- function(x) { + any(nzchar(ggtibble_text_column(x, "footnote"))) || + any(nzchar(ggtibble_text_column(x, "label"))) +} + +#' Print a ggtibble whose figures have footnotes or labels +#' +#' Within knitr, each figure is saved under the chunk's `fig.path` and written +#' as markdown for the output format (see "Footnotes and labels" in +#' [knit_print.gglist()]), so the chunk must have `results = "asis"`. Outside +#' knitr, each figure is printed and its footnote written after it. +#' +#' @inheritParams knit_print.gglist +#' @inheritParams knit_print.gg +#' @returns `x`, invisibly +#' @noRd +knit_print_annotated <- function(x, ..., filename = NULL, fig_suffix = NULL, float_barrier_after = 10, + width = 6, height = 4, units = "in") { + n <- nrow(x) + fig_suffix <- resolve_fig_suffix(fig_suffix, n = n, float_barrier_after = float_barrier_after) + filename <- resolve_knit_filenames(filename, n = n) + caption <- ggtibble_text_column(x, "caption") + footnote <- ggtibble_text_column(x, "footnote") + label <- validate_ggtibble_labels(ggtibble_text_column(x, "label")) + in_knitr <- isTRUE(getOption("knitr.in.progress")) + if (in_knitr) { + options <- knitr::opts_current$get() + if (!identical(options$results, "asis")) { + rlang::abort( + paste( + "A `ggtibble` with footnotes or labels is written as markdown,", + "so its chunk needs `results = \"asis\"` (the `ggtibble` chunk option sets it)." + ), + class = "ggtibble_error_results_not_asis" + ) + } + engine <- figure_output_engine() + quarto <- is_quarto_render() + device <- figure_device(options$dev) + id <- figure_ids(label, chunk_label = options$label, quarto = quarto) + } + for (idx in seq_len(n)) { + plot <- x$figure[[idx]] + if (is.null(plot)) next + if (!inherits(plot, "gg")) { + rlang::abort( + "Each figure of a `ggtibble` with footnotes or labels must be a single ggplot", + class = "ggtibble_error_figure_not_gg" + ) + } + if (!is.null(filename)) { + ggplot2::ggsave(filename = filename[[idx]], plot = plot, width = width, height = height, units = units) + } + if (in_knitr) { + path <- figure_image_path(label[idx], number = idx, ext = device$ext, options = options) + dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE) + ggplot2::ggsave( + filename = path, plot = plot, device = device$device, + width = options$fig.width, height = options$fig.height, units = "in", dpi = options$dpi + ) + cat( + figure_markdown( + engine = engine, path = path, caption = caption[idx], footnote = footnote[idx], + id = id[idx], quarto = quarto, fig_pos = options$fig.pos + ), + fig_suffix, + sep = "" + ) + } else { + print(plot) + if (nzchar(footnote[idx])) { + cat("\n\n", footnote[idx], "\n\n", sep = "") + } + } + } + invisible(x) +} + +#' Which kind of figure markup the document being knitted needs +#' +#' @returns One of `"latex"` (LaTeX through pandoc), `"rnw"` (LaTeX without +#' pandoc, as from an Rnw file), `"typst"`, `"html"`, `"pandoc"` (any other +#' pandoc format, such as docx), or `"markdown"` (knitr markdown with no +#' pandoc target) +#' @noRd +figure_output_engine <- function() { + to <- knitr::pandoc_to() + if (knitr::is_latex_output()) { + if (is.null(to)) "rnw" else "latex" + } else if (is.null(to)) { + "markdown" + } else if (identical(to, "typst")) { + "typst" + } else if (knitr::is_html_output(excludes = c("markdown", "gfm"))) { + "html" + } else { + "pandoc" + } +} + +#' The ggsave() device and file extension for a knitr `dev` chunk option +#' +#' @param dev The `dev` chunk option; only its first element is used +#' @returns A list with `device` (for [ggplot2::ggsave()]; `NULL` lets the +#' extension choose) and `ext` +#' @noRd +figure_device <- function(dev) { + dev <- if (length(dev) == 0) "png" else dev[[1]] + ext <- c( + png = "png", ragg_png = "png", pdf = "pdf", cairo_pdf = "pdf", svg = "svg", + svglite = "svg", jpeg = "jpeg", tiff = "tiff", bmp = "bmp", postscript = "eps" + ) + if (!(dev %in% names(ext))) { + rlang::abort( + paste0( + "The knitr `dev` chunk option \"", dev, "\" is not supported for a `ggtibble` with footnotes or labels; ", + "use one of: ", paste0("\"", names(ext), "\"", collapse = ", ") + ), + class = "ggtibble_error_device_unsupported" + ) + } + device <- if (identical(dev, "cairo_pdf")) grDevices::cairo_pdf else NULL + list(device = device, ext = ext[[dev]]) +} + +#' The identifier written for each figure +#' +#' A figure's label is its identifier. Under Quarto, a figure without a label +#' is given `fig-` (with `-` when the ggtibble has +#' more than one row) so that it is still a numbered, cross-referenceable +#' figure; elsewhere it has no identifier. +#' +#' @param label The labels, with `""` for none +#' @param chunk_label The knitr chunk label +#' @param quarto Is this a Quarto render? +#' @returns A character vector of identifiers, `NA` for none +#' @noRd +figure_ids <- function(label, chunk_label, quarto) { + id <- label + missing_id <- !nzchar(id) + if (quarto) { + base <- paste0("fig-", sub("^fig-", "", chunk_label)) + derived <- if (length(id) == 1) base else paste0(base, "-", seq_along(id)) + id[missing_id] <- derived[missing_id] + validate_ggtibble_labels(id) + } else { + id[missing_id] <- NA_character_ + } + id +} + +#' The image file path for one figure +#' +#' A labelled figure's image is named after its label; any other uses knitr's +#' usual `-` name. Both go through +#' [knitr::fig_path()], which makes the name safe for LaTeX. +#' +#' @param label The figure's label, `""` for none +#' @param number The figure's row number +#' @param ext The file extension +#' @param options The knitr chunk options +#' @returns A file path +#' @noRd +figure_image_path <- function(label, number, ext, options) { + if (nzchar(label)) { + options$label <- label + knitr::fig_path(ext, options = options, number = NULL) + } else { + knitr::fig_path(ext, options = options, number = number) + } +} + +#' Build the markdown for one figure, its caption, its footnote, and its id +#' +#' @param engine The output engine from `figure_output_engine()` +#' @param path The image path +#' @param caption,footnote The figure's caption and footnote (`""` for none); +#' markdown in them passes through +#' @param id The figure's identifier, `NA` for none +#' @param quarto Is this a Quarto render? +#' @param fig_pos The LaTeX float placement (the knitr `fig.pos` option) +#' @returns A single string +#' @noRd +figure_markdown <- function(engine, path, caption, footnote, id, quarto, fig_pos = "") { + quarto_figure <- quarto && !is.na(id) && startsWith(id, "fig-") + if (engine %in% c("latex", "rnw")) { + if (quarto_figure && engine == "latex") { + return(figure_div_markdown( + path = path, caption = latex_caption_markdown(caption, footnote), id = id, + scap = if (nzchar(footnote)) latex_flatten(caption) + )) + } + return(figure_latex_markdown( + path = path, caption = caption, footnote = footnote, id = id, + fig_pos = fig_pos, pandoc = engine == "latex" + )) + } + figure <- + if (quarto_figure) { + figure_div_markdown(path = path, caption = caption, id = id) + } else { + figure_image_markdown(path = path, caption = caption, id = if (engine != "markdown") id else NA) + } + if (!nzchar(footnote)) { + return(figure) + } + if (engine == "typst") { + # Keep the figure and its footnote together on one page. The footnote is + # outside the figure Div so that Quarto still sees the Div as a figure. + # knitr::raw_block() starts and ends its fence with a newline + paste0( + "\n", knitr::raw_block("#block(breakable: false)[", type = "typst"), + figure, + knitr::raw_block("#block(width: 100%, text(size: 0.9em)[", type = "typst"), "\n", + footnote, "\n\n", + knitr::raw_block("])\n]", type = "typst"), "\n" + ) + } else if (engine == "html") { + paste0(figure, "::: {.figure-footnote style=\"font-size: smaller;\"}\n", footnote, "\n:::\n\n") + } else { + paste0(figure, footnote, "\n\n") + } +} + +#' A Quarto figure Div: the image, then the caption as the Div's last paragraph +#' +#' @param scap The short caption for the LaTeX List of Figures, or `NULL` +#' @noRd +figure_div_markdown <- function(path, caption, id, scap = NULL) { + attrs <- paste0("#", id) + if (!is.null(scap)) { + attrs <- paste0(attrs, " fig-scap=\"", markdown_attr_escape(scap), "\"") + } + paste0("\n\n::: {", attrs, "}\n![](", path, ")\n\n", caption, "\n:::\n\n") +} + +#' A pandoc implicit figure: an image alone in its paragraph +#' @noRd +figure_image_markdown <- function(path, caption, id) { + attrs <- if (is.na(id)) "" else paste0("{#", id, "}") + paste0("\n\n![", caption, "](", path, ")", attrs, "\n\n") +} + +#' A LaTeX figure float written directly +#' +#' Through pandoc, the LaTeX commands are raw inlines and blocks around the +#' caption and footnote markdown, so pandoc still converts and escapes the +#' text. For an Rnw document (no pandoc) everything is LaTeX already. The +#' footnote goes inside the caption, after a line break and in +#' `\footnotesize`; the plain caption is the short caption, so the List of +#' Figures carries only the caption. +#' +#' @param pandoc Is the document going through pandoc? +#' @noRd +figure_latex_markdown <- function(path, caption, footnote, id, fig_pos, pandoc) { + caption <- latex_flatten(caption) + footnote <- latex_flatten(footnote) + pos <- if (length(fig_pos) == 1 && nzchar(fig_pos)) paste0("[", fig_pos, "]") else "" + begin <- paste0("\\begin{figure}", pos, "\n\\centering") + end <- "\\end{figure}" + caption_tex <- + if (nzchar(footnote)) { + paste0( + latex_inline("\\caption[{", pandoc), caption, latex_inline("}]{", pandoc), caption, + latex_inline("\\\\{\\footnotesize", pandoc), " ", footnote, latex_inline("}}", pandoc) + ) + } else { + paste0(latex_inline("\\caption{", pandoc), caption, latex_inline("}", pandoc)) + } + label_tex <- if (is.na(id)) "" else latex_inline(paste0("\\label{", id, "}"), pandoc) + graphic <- latex_inline(paste0("\\includegraphics{", path, "}"), pandoc) + if (pandoc) { + # knitr::raw_block() starts and ends its fence with a newline + paste0( + "\n", knitr::raw_block(begin, type = "latex"), "\n", + graphic, "\n\n", + caption_tex, label_tex, "\n", + knitr::raw_block(end, type = "latex"), "\n" + ) + } else { + paste0("\n\n", begin, "\n", graphic, "\n", caption_tex, label_tex, "\n", end, "\n\n") + } +} + +#' The caption paragraph of a Quarto figure Div for LaTeX: the caption, a line +#' break, and the footnote in `\footnotesize` +#' @noRd +latex_caption_markdown <- function(caption, footnote) { + caption <- latex_flatten(caption) + if (!nzchar(footnote)) { + return(caption) + } + paste0( + caption, latex_inline("\\\\{\\footnotesize", TRUE), " ", latex_flatten(footnote), + latex_inline("}", TRUE) + ) +} + +#' Mark a LaTeX fragment as a pandoc raw inline (unchanged without pandoc) +#' @noRd +latex_inline <- function(x, pandoc) { + if (pandoc) paste0("`", x, "`{=latex}") else x +} + +#' Join the lines of a caption or footnote, which LaTeX's `\caption` needs to be +#' a single paragraph +#' @noRd +latex_flatten <- function(x) { + gsub("[[:space:]]*\n[[:space:]]*", " ", x) +} + +#' Escape a value for a double-quoted pandoc attribute +#' @noRd +markdown_attr_escape <- function(x) { + gsub("([\"\\\\])", "\\\\\\1", x) +} diff --git a/R/gglist.R b/R/gglist.R index ace88a5..3f2974b 100644 --- a/R/gglist.R +++ b/R/gglist.R @@ -214,6 +214,41 @@ knitr::knit_print #' auto-suffix. Pass `fig_suffix` explicitly to override, or set #' `float_barrier_after = Inf` to disable the auto-suffix entirely. #' +#' @section Footnotes and labels: +#' +#' A `ggtibble` whose "footnote" or "label" column (see [ggtibble()]) is +#' non-empty on any row is written by `knit_print()` as markdown: each figure +#' is saved under the chunk's `fig.path` with the chunk's `dev`, `fig.width`, +#' `fig.height`, and `dpi`, and written with its caption, its footnote, and its +#' label as its identifier. The chunk therefore needs `results = "asis"`; the +#' `ggtibble` chunk option sets it, and calling `knit_print()` in a chunk +#' without it is an error. A `ggtibble` with no footnotes or labels renders +#' through the knitr plot hook exactly as before. +#' +#' Markdown in captions and footnotes passes through to pandoc. The footnote +#' never separates from its figure: +#' +#' | Output | Figure | Footnote | +#' |---|---|---| +#' | LaTeX (R Markdown and Quarto) | A figure float with `\label{