diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml index fcbff56..859030d 100644 --- a/.github/workflows/test-coverage.yaml +++ b/.github/workflows/test-coverage.yaml @@ -18,6 +18,8 @@ jobs: steps: - uses: actions/checkout@v6 + - uses: r-lib/actions/setup-pandoc@v2 + - uses: r-lib/actions/setup-r@v2 - uses: r-lib/actions/setup-r-dependencies@v2 diff --git a/DESCRIPTION b/DESCRIPTION index 425be9c..38d3c6e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: ggtibble Title: Create Tibbles and Lists of 'ggplot' Figures for Reporting -Version: 1.0.4 +Version: 1.0.4.9000 Authors@R: person("Bill", "Denney", email="wdenney@humanpredictions.com", role=c("aut", "cre"), comment=c(ORCID="0000-0002-5759-428X")) Description: @@ -26,7 +26,7 @@ Imports: dplyr, ggplot2, glue, - knitr, + knitr (>= 1.31), purrr, rlang, tibble, @@ -36,4 +36,4 @@ URL: https://humanpred.github.io/ggtibble/, https://github.com/humanpred/ggtibbl BugReports: https://github.com/humanpred/ggtibble/issues Language: en-US VignetteBuilder: knitr -Config/roxygen2/version: 8.0.0 +Config/roxygen2/version: 8.1.0 diff --git a/NEWS.md b/NEWS.md index c00fa3e..7fcb282 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,28 @@ +# ggtibble (development version) + +* `ggtibble()` gains `footnote` and `label` arguments, glue specifications + evaluated per row like `caption`, giving `footnote` and `label` columns + (empty when not given, including from `as_ggtibble()`). A footnote is + markdown rendered under its figure: inside the figure float after the + caption in LaTeX (with the plain caption as the List of Figures entry), in + one unbreakable block with the figure Div in Quarto Typst, as a smaller + `figure-footnote` Div directly after the figure in HTML, and as a plain + paragraph directly after the figure in Word and plain markdown. In LaTeX + and Typst it cannot be separated from its figure by a page break; in Word it + can, and it is in the body text size. A label is the figure's own + identifier (`\label{}` in LaTeX, the figure Div or image id in Quarto and + pandoc output) and part of its image file name. Labels must be unique + (ignoring case) and use only letters, digits, hyphens, underscores, and + dots, and a figure id may appear only once in a document. Under Quarto, a + label without the `fig-` prefix gives a warning, since `@` references to it + do not resolve. A ggtibble without footnotes or labels renders as before. +* `ggsave()` on a `ggtibble` without `filename` names each file after its + label. +* Quarto renders are detected again with current Quarto versions, which no + longer set the `QUARTO_VERSION` environment variable, so the `ggtibble` + chunk option once more prefixes `fig-` to its labels and uses `fig.subcap` + for multiple captions under Quarto. + # ggtibble 1.0.4 * `gglist` objects may now nest: a `gglist` element of a `gglist` is allowed, diff --git a/R/figure_emit.R b/R/figure_emit.R new file mode 100644 index 0000000..a6dafa5 --- /dev/null +++ b/R/figure_emit.R @@ -0,0 +1,493 @@ +# 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) + ids <- figure_ids(label, chunk_label = options$label, quarto = quarto) + id <- ids$id + register_document_ids(id, derived = ids$derived, chunk_label = options$label) + if (quarto) { + warn_quarto_labels_not_fig(label, chunk_label = options$label) + } + paths <- vapply( + X = seq_len(n), + FUN = function(idx) figure_image_path(label[idx], number = idx, ext = device$ext, options = options), + FUN.VALUE = "" + ) + check_figure_paths(paths, chunk_label = options$label) + } + 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 <- paths[idx] + 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 list of `id`, a character vector of identifiers (`NA` for none), +#' and `derived`, whether each id was derived from the chunk label +#' @noRd +figure_ids <- function(label, chunk_label, quarto) { + id <- label + derived <- !nzchar(id) + if (quarto) { + base <- paste0("fig-", sub("^fig-", "", chunk_label)) + from_chunk <- if (length(id) == 1) base else paste0(base, "-", seq_along(id)) + id[derived] <- from_chunk[derived] + clash <- unique(id[derived & id %in% id[!derived]]) + if (length(clash) > 0) { + rlang::abort( + paste0( + "The figure id ", paste0("`", clash, "`", collapse = ", "), + ", derived from the chunk label `", chunk_label, "` for a figure without a label, ", + "is also a `label` of the ggtibble; figure ids must be unique" + ), + class = "ggtibble_error_label_duplicated" + ) + } + } else { + id[derived] <- NA_character_ + derived[] <- FALSE + } + list(id = id, derived = derived) +} + +#' The knitr::knit() call that is knitting the current document +#' +#' Its frame identifies one knitting run, so ids recorded in an earlier run (for +#' example one that stopped with an error before the document hook could reset +#' them) are not mistaken for ids of the current document. The outermost +#' frame is used, so a child document shares its parent's ids. +#' +#' @returns The frame environment, or `NULL` when no `knitr::knit()` call is +#' on the stack +#' @noRd +current_knit_frame <- function() { + for (idx in seq_len(sys.nframe())) { + if (identical(sys.function(idx), knitr::knit)) { + return(sys.frame(idx)) + } + } + NULL +} + +#' Record the figure ids of a chunk, refusing any already used in the document +#' +#' @param id The chunk's figure ids, `NA` for none +#' @param derived Whether each id was derived from the chunk label +#' @param chunk_label The knitr chunk label +#' @returns `NULL`, invisibly; an error of class +#' `ggtibble_error_label_duplicated` for a repeated id +#' @noRd +register_document_ids <- function(id, derived, chunk_label) { + frame <- current_knit_frame() + if (!identical(get0("frame", envir = .ggtibble_id_cache, inherits = FALSE), frame)) { + assign("frame", frame, envir = .ggtibble_id_cache) + assign("chunks", character(), envir = .ggtibble_id_cache) + } + chunks <- get0("chunks", envir = .ggtibble_id_cache, inherits = FALSE, ifnotfound = character()) + for (idx in which(!is.na(id))) { + if (id[idx] %in% names(chunks)) { + rlang::abort( + paste0( + "The figure id `", id[idx], "`", + if (derived[idx]) paste0(" (derived from the chunk label for a figure without a label)"), + " in chunk `", chunk_label, "` was already used in chunk `", chunks[[id[idx]]], + "`; figure ids must be unique within a document" + ), + class = "ggtibble_error_label_duplicated" + ) + } + chunks[[id[idx]]] <- chunk_label + } + assign("chunks", chunks, envir = .ggtibble_id_cache) + invisible(NULL) +} + +#' Warn when a Quarto document has labels that are not cross-referenceable +#' +#' Quarto treats `@