diff --git a/.Rbuildignore b/.Rbuildignore index 46ab0604..2aa477a0 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -9,8 +9,7 @@ README.qmd man-roxygen Makefile .quarto -vignettes/.*\.qmd$ -vignettes/.*\.bib$ +vignettes/ docs/ docs .github @@ -20,4 +19,4 @@ tinytable_assets ^man/figures/.*\\.png$ ^man/figures/gallery/.*\\.png$ sandbox/ - +vignettes/ diff --git a/.gitignore b/.gitignore index 9fca1cd8..4a6aaee6 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ # produced vignettes vignettes/*.html vignettes/*.pdf +sandbox/*.pdf # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 .httr-oauth @@ -51,8 +52,9 @@ tinytable_assets cran-comments.md CRAN-SUBMISSION -sandbox/typst.typ -sandbox/typst.pdf +sandbox/*.typ +sandbox/*.pdf +sandbox/*.tex !_quarto/_freeze/ diff --git a/DESCRIPTION b/DESCRIPTION index 16e946be..f90bb7d2 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Package: tinytable Type: Package Title: Simple and Configurable Tables in 'HTML', 'LaTeX', 'Markdown', 'Word', 'PNG', 'PDF', and 'Typst' Formats Description: Create highly customized tables with this simple and dependency-free package. Data frames can be converted to 'HTML', 'LaTeX', 'Markdown', 'Word', 'PNG', 'PDF', or 'Typst' tables. The user interface is minimalist and easy to learn. The syntax is concise. 'HTML' tables can be customized using the flexible 'Bootstrap' framework, and 'LaTeX' code with the 'tabularray' package. -Version: 0.5.0.4 +Version: 0.6.1.4 Imports: methods Depends: @@ -20,6 +20,7 @@ Suggests: pandoc, quarto, rmarkdown, + rstudioapi, scales, stringi, tibble, @@ -30,8 +31,8 @@ Suggests: URL: https://vincentarelbundock.github.io/tinytable/ BugReports: https://github.com/vincentarelbundock/tinytable/issues Authors@R: c( - person("Vincent", "Arel-Bundock", - email = "vincent.arel-bundock@umontreal.ca", + person("Vincent", "Arel-Bundock", + email = "vincent.arel-bundock@umontreal.ca", role = c("aut", "cre"), comment = c(ORCID = "0000-0003-2042-7063"))) License: GPL (>= 3) diff --git a/Makefile b/Makefile index e74c85be..4032e19f 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,10 @@ installdep: document ## install with Suggests test: install ## test Rscript -e "library(tinytable);tinytest::run_test_dir()" -website: install ## render vignettes and website +typst: ## compile typst example + quarto render sandbox/typst.qmd + +website: install typst ## render vignettes and website rm -rf _quarto rm -rf docs Rscript -e "altdoc::render_docs(verbose = TRUE, freeze = TRUE, autolink = TRUE)" diff --git a/NAMESPACE b/NAMESPACE index ff334091..b7394fa6 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +S3method(knitr::knit_print, tinytable) S3method(print,tinytable) export(format_tt) export(group_tt) diff --git a/NEWS.md b/NEWS.md index c0fa0b71..0d79e35a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,12 +2,34 @@ ## Development +Breaking change: + +* `format_tt()` is now stricter, applying no formatting at all by default. Users must specify an argument explicitly or set a global option to change the table. + +Bugs: + +* `save_tt("file.pdf")` works with colors. Thanks to @olivedv for the report and solution #395. + +New: + +* `style_tt("notes")` and `style_tt("caption")` can style footnotes and captions. Note: This will only style captions handled by the `caption` argument in `tt()`, and not captions created by Quarto. Misc: +* Documentation improvements + +## 0.6.1 + +* Bug fix: d-column LaTeX generated an error in some cases. + +## 0.6.0 + * Major refactor of the style internals. HTML, LaTeX, and Typst documents should be much more concise and efficient. +* `theme_tt("spacing")`: Change the row and column spacing to create more compact or airy tables. LaTeX and HTML only. Thanks to @statzhero for feature request #353. * `style_tt()`: the `i` and `j` indices are now consistent in all formats. They refer to rows *after* the insertion of row groups. * `save_tt()` respects `options(tinytable_save_overwrite=TRUE)` +* LaTeX: Guard header rows when using `style_tt(align="d")`. Issue #367 +* Inline display in Quarto and Rmarkdown notebooks. `options(tinytable_print_rstudio_notebook = "inline")` or `"viewer"` Bugs: @@ -79,7 +101,7 @@ MathJax = { * `format_tt(num_big_mark)` applies to integer columns. * Use `getOption("viewer")` instead of `rstudioapi::viewer()` for positron support * `glue::glue()` string is accepted by `format_tt()`. Thanks to @LukasWallrich for report #792 on the `modelsummary` repository. -* Support Github Flavored Markdown (`gfm`) output. Thanks to @kylebutts for contribution #315. +* Support Github Flavored Markdown (`gfm`) output. Thanks to @kylebutts for contribution #315. * `theme_tt("rotate")` to rotate tables in LaTeX or Typst. * `save_tt("/path/to/file")` returns the file path invisibly. Thanks to @yjunechoe for issue #328. @@ -184,7 +206,7 @@ New features: * `rbind()` and `rbind2()` can be used to stack `tinytable` objects. `rbind2()` is more flexible than `rbind()`. See `?tinytable::rbind2` * New output format in `print()`: "dataframe" -* Rename table headers: `colnames(tab) <- c("a", "b", "c")` +* Rename table headers: `colnames(tab) <- c("a", "b", "c")` * `theme_tt("resize")` gets a `direction` argument with "up", "down", "both" options. Thanks to @MarcoPortmann for feature request #207 Minor: @@ -203,7 +225,7 @@ New function `theme_tt()`: * Function to apply collections of transformations to a `tinytable`. * Visual themes: - - grid, void, striped, bootstrap, default + - grid, void, striped, bootstrap, default * `resize`: Insert a LaTeX table in a `resizebox` environment to ensure a table fits the page, or to scale it to a fraction of `\linewidth` * `placement`: Determine where a LaTeX table float is positioned. Ex: `[H]`, `[htbp]` * `multipage`: Split long LaTeX tables across multiple pages with (optional) repeated headers/footers. Uses the `longtblr` environment from `tabularray`. @@ -271,7 +293,7 @@ Bugfix: New: -- `Typst` tables are now supported using the `tablex` extension: +- `Typst` tables are now supported using the `tablex` extension: - https://typst.app/ - https://github.com/PgBiel/typst-tablex - `escape` argument in `format_tt()` escapes or substitutes special characters in LaTeX or HTML output to prevent compilation and rendering errors. @@ -302,7 +324,7 @@ Bug fixes: Documentation: -- Improved vignette on the package website. +- Improved vignette on the package website. - Various documentation updates. - Math in $$ is the new recommendation. diff --git a/R/build_tt.R b/R/build_tt.R index d014457d..26d42cdd 100644 --- a/R/build_tt.R +++ b/R/build_tt.R @@ -6,6 +6,7 @@ build_tt <- function(x, output = NULL) { output <- sanitize_output(output) + x <- switch(output, html = swap_class(x, "tinytable_bootstrap"), latex = swap_class(x, "tinytable_tabularray"), @@ -17,6 +18,10 @@ build_tt <- function(x, output = NULL) { x@output <- output + # apply the style_notes + x <- style_notes(x) + x <- style_caption(x) + for (th in x@lazy_theme) { fn <- th[[1]] args <- th[[2]] @@ -24,15 +29,6 @@ build_tt <- function(x, output = NULL) { x <- do.call(fn, args) } - # groups must increment indices here - for (idx in seq_along(x@lazy_group)) { - l <- x@lazy_group[[idx]] - x@nrow <- x@nrow + length(l$i) - if (length(l$j) > 0) { - x@nhead <- x@nhead + 1 - } - } - tab <- x@table_dataframe # strip ANSI from `tibble`/`pillar`; keep for markdown diff --git a/R/class.R b/R/class.R index 48b283f9..88736723 100644 --- a/R/class.R +++ b/R/class.R @@ -15,48 +15,50 @@ swap_class <- function(x, new_class) { setClassUnion("NULLorCharacter", c("NULL", "character")) #' tinytable S4 class -#' +#' #' @keywords internal #' @export setClass( - Class = "tinytable", - slots = representation( - table_dataframe = "data.frame", - table_string = "character", - data = "data.frame", - caption = "character", - width = "numeric", - width_cols = "numeric", - notes = "list", - theme = "list", - placement = "character", - body = "character", - nrow = "numeric", - ncol = "numeric", - nhead = "numeric", - ngroupi = "numeric", - group_i_idx = "numeric", - names = "NULLorCharacter", - output = "character", - output_dir = "character", - id = "character", - bootstrap_class = "character", - bootstrap_css_rule = "character", - css = "data.frame", - style = "data.frame", - lazy_format = "list", - lazy_group = "list", - lazy_style = "list", - lazy_plot = "list", - lazy_finalize = "list", - lazy_theme = "list", - group_tt_i = "logical", - portable = "logical" - ) + Class = "tinytable", + slots = representation( + table_dataframe = "data.frame", + table_string = "character", + data = "data.frame", + caption = "character", + width = "numeric", + width_cols = "numeric", + notes = "list", + theme = "list", + placement = "character", + body = "character", + nrow = "numeric", + ncol = "numeric", + nhead = "numeric", + ngroupi = "numeric", + ngroupj = "numeric", + group_i_idx = "numeric", + names = "NULLorCharacter", + output = "character", + output_dir = "character", + id = "character", + bootstrap_class = "character", + bootstrap_css_rule = "character", + css = "data.frame", + style = "data.frame", + style_caption = "list", + style_notes = "list", + lazy_format = "list", + lazy_group = "list", + lazy_style = "list", + lazy_plot = "list", + lazy_finalize = "list", + lazy_theme = "list", + portable = "logical" + ) ) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal setMethod("initialize", "tinytable", function( @@ -77,6 +79,7 @@ setMethod("initialize", "tinytable", function( .Object@ncol <- ncol(.Object@data) .Object@nhead <- if (is.null(colnames(data))) 0 else 1 .Object@ngroupi <- 0 + .Object@ngroupj <- 0 .Object@names <- if (is.null(colnames(data))) character() else colnames(data) .Object@id <- get_id("tinytable_") .Object@output <- "tinytable" @@ -84,7 +87,6 @@ setMethod("initialize", "tinytable", function( .Object@css <- data.frame(i = NA, j = NA, bootstrap = NA, id = NA) .Object@portable <- FALSE .Object@style <- data.frame() - .Object@group_tt_i <- FALSE .Object@lazy_theme <- list() # conditional: allows NULL user input if (!is.null(placement)) .Object@placement <- placement @@ -95,85 +97,97 @@ setMethod("initialize", "tinytable", function( }) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal -setMethod("nrow", "tinytable", function(x) return(x@nrow)) +setMethod("nrow", "tinytable", function(x) { + return(x@nrow) +}) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal -setMethod("ncol", "tinytable", function(x) return(x@ncol)) +setMethod("ncol", "tinytable", function(x) { + return(x@ncol) +}) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal #' @export -setMethod("colnames", "tinytable", function(x) return(x@names)) +setMethod("colnames", "tinytable", function(x) { + return(x@names) +}) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal #' @export -setMethod("names", "tinytable", function(x) return(x@names)) +setMethod("names", "tinytable", function(x) { + return(x@names) +}) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal #' @export setReplaceMethod("colnames", - signature = "tinytable", - definition = function(x, value) { - # Issue #306 - if (length(value) == 0) value <- NULL - if (!is.null(value)) { - assert_character(value, len = length(x@names)) - } else { - if (x@nhead == 1) x@nhead <- 0 - } - x@names <- value - return(x) - } + signature = "tinytable", + definition = function(x, value) { + # Issue #306 + if (length(value) == 0) value <- NULL + if (!is.null(value)) { + assert_character(value, len = length(x@names)) + } else { + if (x@nhead == 1) x@nhead <- 0 + } + x@names <- value + return(x) + } ) #' Method for a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal #' @export setReplaceMethod("names", - signature = "tinytable", - definition = function(x, value) { - # Issue #306 - if (length(value) == 0) value <- NULL - if (!is.null(value)) { - assert_character(value, len = length(x@names)) - } else { - if (x@nhead == 1) x@nhead <- 0 - } - x@names <- value - return(x) - } + signature = "tinytable", + definition = function(x, value) { + # Issue #306 + if (length(value) == 0) value <- NULL + if (!is.null(value)) { + assert_character(value, len = length(x@names)) + } else { + if (x@nhead == 1) x@nhead <- 0 + } + x@names <- value + return(x) + } ) #' Dimensions a tinytable S4 object -#' +#' #' @inheritParams tt #' @keywords internal -setMethod("dim", "tinytable", function(x) return(c(x@nrow, x@ncol))) +setMethod("dim", "tinytable", function(x) { + return(c(x@nrow, x@ncol)) +}) #' Column names of a tinytable -#' +#' #' @inheritParams tt #' @keywords internal -setMethod("names", "tinytable", function(x) return(x@names)) +setMethod("names", "tinytable", function(x) { + return(x@names) +}) #' Convert a tinytable S4 object to a string -#' +#' #' @inheritParams tt #' @keywords internal setMethod("as.character", "tinytable", function(x) { @@ -188,7 +202,7 @@ setClass("tinytable_grid", contains = "tinytable") setClass("tinytable_dataframe", contains = "tinytable") #' Apply style settings to a tinytable -#' +#' #' @inheritParams tt #' @keywords internal setGeneric( @@ -197,7 +211,7 @@ setGeneric( ) #' Apply group settings to a tinytable -#' +#' #' @inheritParams tt #' @keywords internal setGeneric( @@ -206,7 +220,7 @@ setGeneric( ) #' Apply group settings to a tinytable -#' +#' #' @inheritParams tt #' @keywords internal setGeneric( @@ -215,12 +229,10 @@ setGeneric( ) #' Apply final settings to a tinytable -#' +#' #' @inheritParams tt #' @keywords internal setGeneric( name = "finalize", def = function(x, ...) standardGeneric("finalize") ) - - diff --git a/R/escape.R b/R/escape.R index cad87f3f..79aa47c3 100644 --- a/R/escape.R +++ b/R/escape.R @@ -1,56 +1,57 @@ escape_text <- function(x, output = "latex") { - if (length(x) < 1 || all(is.na(x))) return(x) - if(isFALSE(output)) return(x) - - out <- x - - if (isTRUE(output == "latex")) { - # LaTeX escaping code adapted from the `gt` package, published under MIT - # https://github.com/rstudio/gt/ - # YEAR: 2018-2024 - # COPYRIGHT HOLDER: gt authors - # If all text elements are `NA_character_` then return `text` unchanged - latex_special_chars <- c( - "\\" = "\\textbackslash{}", - "~" = "\\textasciitilde{}", - "^" = "\\textasciicircum{}", - "&" = "\\&", - "%" = "\\%", - "$" = "\\$", - "#" = "\\#", - "_" = "\\_", - "{" = "\\{", - "}" = "\\}" - ) - na_out <- is.na(out) - m <- gregexpr("[\\\\&%$#_{}~^]", out[!na_out], perl = TRUE) - special_chars <- regmatches(out[!na_out], m) - escaped_chars <- lapply(special_chars, function(x) { - latex_special_chars[x] - }) - regmatches(out[!na_out], m) <- escaped_chars - - } else if (isTRUE(output == "html")) { - out <- htmlEscape(out) - - } else if (isTRUE(output == "typst")) { - out <- gsub("<", "\\<", out, fixed = TRUE) - out <- gsub(">", "\\>", out, fixed = TRUE) - out <- gsub("*", "\\*", out, fixed = TRUE) - out <- gsub(">", "\\>", out, fixed = TRUE) - out <- gsub("@", "\\@", out, fixed = TRUE) - out <- gsub("=", "\\=", out, fixed = TRUE) - out <- gsub("-", "\\-", out, fixed = TRUE) - out <- gsub("+", "\\+", out, fixed = TRUE) - out <- gsub("/", "\\/", out, fixed = TRUE) - out <- gsub("$", "\\$", out, fixed = TRUE) - out <- gsub("#", "\\#", out, fixed = TRUE) - out <- gsub("[", "\\[", out, fixed = TRUE) - out <- gsub("]", "\\]", out, fixed = TRUE) + if (length(x) < 1 || all(is.na(x))) { + return(x) + } + if (isFALSE(output)) { + return(x) + } - } + out <- x + + if (isTRUE(output == "latex")) { + # LaTeX escaping code adapted from the `gt` package, published under MIT + # https://github.com/rstudio/gt/ + # YEAR: 2018-2024 + # COPYRIGHT HOLDER: gt authors + # If all text elements are `NA_character_` then return `text` unchanged + latex_special_chars <- c( + "\\" = "\\textbackslash{}", + "~" = "\\textasciitilde{}", + "^" = "\\textasciicircum{}", + "&" = "\\&", + "%" = "\\%", + "$" = "\\$", + "#" = "\\#", + "_" = "\\_", + "{" = "\\{", + "}" = "\\}" + ) + na_out <- is.na(out) + m <- gregexpr("[\\\\&%$#_{}~^]", out[!na_out], perl = TRUE) + special_chars <- regmatches(out[!na_out], m) + escaped_chars <- lapply(special_chars, function(x) { + latex_special_chars[x] + }) + regmatches(out[!na_out], m) <- escaped_chars + } else if (isTRUE(output == "html")) { + out <- htmlEscape(out) + } else if (isTRUE(output == "typst")) { + out <- gsub("<", "\\<", out, fixed = TRUE) + out <- gsub(">", "\\>", out, fixed = TRUE) + out <- gsub("*", "\\*", out, fixed = TRUE) + out <- gsub(">", "\\>", out, fixed = TRUE) + out <- gsub("@", "\\@", out, fixed = TRUE) + out <- gsub("=", "\\=", out, fixed = TRUE) + out <- gsub("-", "\\-", out, fixed = TRUE) + out <- gsub("+", "\\+", out, fixed = TRUE) + out <- gsub("/", "\\/", out, fixed = TRUE) + out <- gsub("$", "\\$", out, fixed = TRUE) + out <- gsub("#", "\\#", out, fixed = TRUE) + out <- gsub("[", "\\[", out, fixed = TRUE) + out <- gsub("]", "\\]", out, fixed = TRUE) + } - return(out) + return(out) } @@ -59,37 +60,39 @@ escape_text <- function(x, output = "latex") { # function copied from `htmltools` under GPL3 license on 2024-02-07 # https://cran.r-project.org/web/packages/htmltools/index.html htmlEscape <- local({ - .htmlSpecials <- list( - `&` = '&', - `<` = '<', - `>` = '>' + `&` = "&", + `<` = "<", + `>` = ">" ) - .htmlSpecialsPattern <- paste(names(.htmlSpecials), collapse='|') + .htmlSpecialsPattern <- paste(names(.htmlSpecials), collapse = "|") .htmlSpecialsAttrib <- c( .htmlSpecials, - `'` = ''', - `"` = '"', - `\r` = ' ', - `\n` = ' ' + `'` = "'", + `"` = """, + `\r` = " ", + `\n` = " " ) - .htmlSpecialsPatternAttrib <- paste(names(.htmlSpecialsAttrib), collapse='|') + .htmlSpecialsPatternAttrib <- paste(names(.htmlSpecialsAttrib), collapse = "|") - function(text, attribute=FALSE) { - pattern <- if(attribute) + function(text, attribute = FALSE) { + pattern <- if (attribute) { .htmlSpecialsPatternAttrib - else + } else { .htmlSpecialsPattern + } text <- enc2utf8(as.character(text)) # Short circuit in the common case that there's nothing to escape - if (!any(grepl(pattern, text, useBytes = TRUE))) + if (!any(grepl(pattern, text, useBytes = TRUE))) { return(text) + } - specials <- if(attribute) + specials <- if (attribute) { .htmlSpecialsAttrib - else + } else { .htmlSpecials + } for (chr in names(specials)) { text <- gsub(chr, specials[[chr]], text, fixed = TRUE, useBytes = TRUE) diff --git a/R/finalize_bootstrap.R b/R/finalize_bootstrap.R index afee8f6a..0e7a05f7 100644 --- a/R/finalize_bootstrap.R +++ b/R/finalize_bootstrap.R @@ -2,82 +2,86 @@ setMethod( f = "finalize", signature = "tinytable_bootstrap", definition = function(x, ...) { - - # class - cl <- x@bootstrap_class - if (is.null(cl) || length(cl) == 0) { - cl <- "table table-borderless" - } - out <- sub( - "$tinytable_BOOTSTRAP_CLASS", - cl, - x@table_string, - fixed = TRUE) + # class + cl <- x@bootstrap_class + if (is.null(cl) || length(cl) == 0) { + cl <- "table table-borderless" + } + out <- sub( + "$tinytable_BOOTSTRAP_CLASS", + cl, + x@table_string, + fixed = TRUE + ) if (isTRUE(getOption("knitr.in.progress"))) { - # Rmarkdown and Quarto load their own bootstrap, which we probably don't want to override - out <- lines_drop(out, "jsdelivr.*bootstrap", fixed = FALSE, unique = FALSE) - # avoid nesting full HTML page inside an HTML page - out <- lines_drop_between(out, - regex_start = "", - regex_end = "", - fixed = TRUE) - out <- lines_drop_between(out, - regex_start = "", - regex_end = "", - fixed = TRUE) + # Rmarkdown and Quarto load their own bootstrap, which we probably don't want to override + out <- lines_drop(out, "jsdelivr.*bootstrap", fixed = FALSE, unique = FALSE) + # avoid nesting full HTML page inside an HTML page + out <- lines_drop_between(out, + regex_start = "", + regex_end = "", + fixed = TRUE + ) + out <- lines_drop_between(out, + regex_start = "", + regex_end = "", + fixed = TRUE + ) } - # Changing function names to table ID to avoid conflict with other tables functions - out <- gsub("styleCell_\\w+\\(", paste0("styleCell_", x@id, "("), out) - out <- gsub("spanCell_\\w+\\(", paste0("spanCell_", x@id, "("), out) - + # Changing function names to table ID to avoid conflict with other tables functions + out <- gsub("styleCell_\\w+\\(", paste0("styleCell_", x@id, "("), out) + out <- gsub("spanCell_\\w+\\(", paste0("spanCell_", x@id, "("), out) - css_template <- " .table td.%s, .table th.%s { %s }" - css <- unique(stats::na.omit(x@css)) - css <- css[which(css$bootstrap != ""), ] + css_template <- " .table td.%s, .table th.%s { %s }" - if (nrow(css) > 0) { + css <- unique(stats::na.omit(x@css)) + css <- css[which(css$bootstrap != ""), ] - css_rules <- css - css_rules$id <- NULL - css_rules <- split(css_rules, list(css_rules$i, css_rules$j)) - css_rules <- Filter(function(z) nrow(z) > 0, css_rules) - css_rules <- lapply(css_rules, function(z) z[rev(seq_len(nrow(z))),]) - css_rules <- lapply(css_rules, unique) - css_rules <- lapply(css_rules, function(z) transform(z, bootstrap = paste(bootstrap, collapse = " "))[1,]) - css_rules <- do.call(rbind, css_rules) - id <- unique(css_rules[, "bootstrap", drop = FALSE]) - id$id <- sapply(seq_len(nrow(id)), function(z) sprintf("tinytable_css_%s", get_id())) - css_rules <- merge(css_rules, id) - css_rules <- css_rules[order(css_rules$i, css_rules$j),] + if (nrow(css) > 0) { + css_rules <- css + css_rules$id <- NULL + css_rules <- split(css_rules, list(css_rules$i, css_rules$j)) + css_rules <- Filter(function(z) nrow(z) > 0, css_rules) + css_rules <- lapply(css_rules, function(z) z[rev(seq_len(nrow(z))), ]) + css_rules <- lapply(css_rules, unique) + css_rules <- lapply(css_rules, function(z) transform(z, bootstrap = paste(bootstrap, collapse = " "))[1, ]) + css_rules <- do.call(rbind, css_rules) + id <- unique(css_rules[, "bootstrap", drop = FALSE]) + id$id <- sapply(seq_len(nrow(id)), function(z) sprintf("tinytable_css_%s", get_id())) + css_rules <- merge(css_rules, id) + css_rules <- css_rules[order(css_rules$i, css_rules$j), ] - for (ii in seq_len(nrow(css_rules))) { + for (ii in seq_len(nrow(css_rules))) { listener <- sprintf( - "window.addEventListener('load', function () { styleCell_%s(%s, %s, '%s') })", - x@id, - css_rules$i[[ii]], - css_rules$j[[ii]], - css_rules$id[[ii]]) + "window.addEventListener('load', function () { styleCell_%s(%s, %s, '%s') })", + x@id, + css_rules$i[[ii]], + css_rules$j[[ii]], + css_rules$id[[ii]] + ) out <- bootstrap_setting(out, listener, component = "cell") - } - css_rules_unique <- unique(css_rules[, c("bootstrap", "id")]) - for (ii in seq_len(nrow(css_rules_unique))) { - css_rule <- sprintf(css_template, - css_rules_unique$id[[ii]], - css_rules_unique$id[[ii]], - css_rules_unique$bootstrap[[ii]]) + } + css_rules_unique <- unique(css_rules[, c("bootstrap", "id")]) + for (ii in seq_len(nrow(css_rules_unique))) { + css_rule <- sprintf( + css_template, + css_rules_unique$id[[ii]], + css_rules_unique$id[[ii]], + css_rules_unique$bootstrap[[ii]] + ) out <- bootstrap_setting(out, css_rule, component = "css") + } } - } + x@table_string <- out - x@table_string <- out + for (fn in x@lazy_finalize) { + x <- fn(x) + } - for (fn in x@lazy_finalize) { - x <- fn(x) + return(x) } - - return(x) -}) +) diff --git a/R/finalize_tabularray.R b/R/finalize_tabularray.R index 452ea5da..367aea92 100644 --- a/R/finalize_tabularray.R +++ b/R/finalize_tabularray.R @@ -7,4 +7,4 @@ setMethod( } return(x) } -) \ No newline at end of file +) diff --git a/R/finalize_typst.R b/R/finalize_typst.R index 5309905a..afffef03 100644 --- a/R/finalize_typst.R +++ b/R/finalize_typst.R @@ -2,45 +2,46 @@ setMethod( f = "finalize", signature = "tinytable_typst", definition = function(x, ...) { + out <- x@table_string + out <- sub("$TINYTABLE_TYPST_NROW", nrow(x), out, fixed = TRUE) + out <- sub("$TINYTABLE_TYPST_NCOL", ncol(x), out, fixed = TRUE) + out <- sub("$TINYTABLE_TYPST_NHEAD", x@nhead, out, fixed = TRUE) - out <- x@table_string - out <- sub("$TINYTABLE_TYPST_NROW", nrow(x), out, fixed = TRUE) - out <- sub("$TINYTABLE_TYPST_NCOL", ncol(x), out, fixed = TRUE) - out <- sub("$TINYTABLE_TYPST_NHEAD", x@nhead, out, fixed = TRUE) - - cap <- x@caption - if (length(cap) == 1) { - out <- sub("$TINYTABLE_TYPST_CAPTION", sprintf("caption: [%s],", cap), out, fixed = TRUE) - } else { - out <- sub("$TINYTABLE_TYPST_CAPTION", "", out, fixed = TRUE) - } + cap <- x@caption + if (length(cap) == 1) { + out <- sub("$TINYTABLE_TYPST_CAPTION", sprintf("caption: %s,", cap), out, fixed = TRUE) + } else { + out <- sub("$TINYTABLE_TYPST_CAPTION", "", out, fixed = TRUE) + } - # Quarto cross-references - if (isTRUE(check_dependency("knitr"))) { - quarto_caption <- isTRUE(knitr::pandoc_to("typst")) && - isFALSE(getOption("tinytable_quarto_figure", default = FALSE)) - (!is.null(knitr::opts_current$get()[["label"]]) || - !is.null(knitr::opts_current$get()[["tbl-cap"]])) - if (quarto_caption) { - out <- lines_drop_between(out, - regex_start = "// start figure preamble", - regex_end = "// end figure preamble", - fixed = TRUE) - out <- lines_drop(out, regex = "// start figure preamble", fixed = TRUE) - out <- lines_drop(out, regex = "// end figure", fixed = TRUE) - out <- lines_drop(out, regex = "// start block", fixed = TRUE) - out <- lines_drop(out, regex = "// end block", fixed = TRUE) - out <- sub(" table(", " #table(", out, fixed = TRUE) + # Quarto cross-references + if (isTRUE(check_dependency("knitr"))) { + quarto_caption <- isTRUE(knitr::pandoc_to("typst")) && + isFALSE(getOption("tinytable_quarto_figure", default = FALSE)) + (!is.null(knitr::opts_current$get()[["label"]]) || + !is.null(knitr::opts_current$get()[["tbl-cap"]])) + if (quarto_caption) { + out <- lines_drop_between(out, + regex_start = "// start figure preamble", + regex_end = "// end figure preamble", + fixed = TRUE + ) + out <- lines_drop(out, regex = "// start figure preamble", fixed = TRUE) + out <- lines_drop(out, regex = "// end figure", fixed = TRUE) + out <- lines_drop(out, regex = "// start block", fixed = TRUE) + out <- lines_drop(out, regex = "// end block", fixed = TRUE) + out <- sub(" table(", " #table(", out, fixed = TRUE) + } } - } - x@table_string <- out + x@table_string <- out - for (fn in x@lazy_finalize) { - x <- fn(x) - } + for (fn in x@lazy_finalize) { + x <- fn(x) + } - return(x) -}) + return(x) + } +) diff --git a/R/footnotes.R b/R/footnotes.R index b60aa0c4..3e9ee34b 100644 --- a/R/footnotes.R +++ b/R/footnotes.R @@ -1,29 +1,29 @@ footnote_markers <- function(x) { - notes <- x@notes - tab <- x@table_dataframe - for (idx in seq_along(notes)) { - n <- notes[[idx]] - sup <- names(notes)[idx] - if (is.list(n)) { - if (x@output == "latex") { - tab[n$i, n$j] <- paste0(tab[n$i, n$j], "\\textsuperscript{", sup, "}") - if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "\\textsuperscript{", sup, "}") - if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "\\textsuperscript{", sup, "}") - } else if (x@output == "html") { - tab[n$i, n$j] <- paste0(tab[n$i, n$j], "", sup, "") - if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "", sup, "") - if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "", sup, "") - } else if (x@output == "typst") { - tab[n$i, n$j] <- paste0(tab[n$i, n$j], "#super[", sup, "]") - if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "#super[", sup, "]") - if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "#super[", sup, "]") - } else { - tab[n$i, n$j] <- paste0(tab[n$i, n$j], "^", sup, "^") - if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "^", sup, "^") - if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "^", sup, "^") - } - } + notes <- x@notes + tab <- x@table_dataframe + for (idx in seq_along(notes)) { + n <- notes[[idx]] + sup <- names(notes)[idx] + if (is.list(n)) { + if (x@output == "latex") { + tab[n$i, n$j] <- paste0(tab[n$i, n$j], "\\textsuperscript{", sup, "}") + if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "\\textsuperscript{", sup, "}") + if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "\\textsuperscript{", sup, "}") + } else if (x@output == "html") { + tab[n$i, n$j] <- paste0(tab[n$i, n$j], "", sup, "") + if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "", sup, "") + if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "", sup, "") + } else if (x@output == "typst") { + tab[n$i, n$j] <- paste0(tab[n$i, n$j], "#super[", sup, "]") + if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "#super[", sup, "]") + if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "#super[", sup, "]") + } else { + tab[n$i, n$j] <- paste0(tab[n$i, n$j], "^", sup, "^") + if (0 %in% n$i) colnames(tab)[n$j] <- paste0(colnames(tab)[n$j], "^", sup, "^") + if (0 %in% n$i) x@names[n$j] <- paste0(x@names[n$j], "^", sup, "^") + } } - x@table_dataframe <- tab - return(x) -} \ No newline at end of file + } + x@table_dataframe <- tab + return(x) +} diff --git a/R/format_numeric.R b/R/format_numeric.R index aaff0cad..429d5643 100644 --- a/R/format_numeric.R +++ b/R/format_numeric.R @@ -9,8 +9,9 @@ format_numeric <- function(value, num_suffix, digits, num_mark_big, num_mark_dec num_mark_big = num_mark_big, num_mark_dec = num_mark_dec, num_zero = num_zero, - num_fmt = num_fmt) - # non-integer numeric + num_fmt = num_fmt + ) + # non-integer numeric } else if (is.numeric(value) && !isTRUE(check_integerish(value)) && !is.null(digits)) { out <- format_non_integer_numeric( value, @@ -18,15 +19,17 @@ format_numeric <- function(value, num_suffix, digits, num_mark_big, num_mark_dec num_mark_big = num_mark_big, num_mark_dec = num_mark_dec, num_zero = num_zero, - num_fmt = num_fmt) - # integer - } else if (isTRUE(check_integerish(value)) && !is.null(digits)) { - out <- format_integer(value, - digits = digits, - num_mark_big = num_mark_big, - num_mark_dec = num_mark_dec, - num_zero = num_zero, - num_fmt = num_fmt) + num_fmt = num_fmt + ) + # integer + } else if (isTRUE(check_integerish(value))) { + out <- format_integer(value, + digits = digits, + num_mark_big = num_mark_big, + num_mark_dec = num_mark_dec, + num_zero = num_zero, + num_fmt = num_fmt + ) } else { out <- NULL } @@ -46,7 +49,8 @@ format_num_suffix <- function(x, digits, num_mark_big, num_mark_dec, num_zero, n format(k, digits = digits, drop0trailing = !num_zero, type = "f", big.mark = num_mark_big, decimal.mark = num_mark_dec, - scientific = FALSE) + scientific = FALSE + ) }) } number <- fun(x) diff --git a/R/format_tt.R b/R/format_tt.R index ffc6c419..d2d5277d 100644 --- a/R/format_tt.R +++ b/R/format_tt.R @@ -1,6 +1,6 @@ #' Format columns of a data frame #' -#' This function formats the columns of a data frame based on the column type (logical, date, numeric). +#' This function formats the columns of a data frame based on the column type (logical, date, numeric). #' It allows various formatting options like significant digits, decimal points, and scientific notation. #' It also includes custom formatting for date and boolean values. #' If this function is applied several times to the same cell, the last transformation is retained and the previous calls are ignored, except for the `escape` argument which can be applied to previously transformed data. @@ -21,7 +21,7 @@ #' - TRUE: Replace `NA` by an empty string. #' - FALSE: Print `NA` as the string "NA". #' - String: Replace `NA` entries by the user-supplied string. -#' - Named list: Replace matching elements of the vectors in the list by theirs names. Example: +#' - Named list: Replace matching elements of the vectors in the list by theirs names. Example: #' - `list("-" = c(NA, NaN), "Tiny" = -Inf, "Massive" = Inf)` #' @param escape Logical or "latex" or "html". If TRUE, escape special characters to display them as text in the format of the output of a `tt()` table. #' - If `i` and `j` are both `NULL`, escape all cells, column names, caption, notes, and spanning labels created by `group_tt()`. @@ -29,7 +29,6 @@ #' @param fn Function for custom formatting. Accepts a vector and returns a character vector of the same length. #' @param quarto Logical. Enable Quarto data processing and wrap cell content in a `data-qmd` span (HTML) or `\QuartoMarkdownBase64{}` macro (LaTeX). See warnings in the Global Options section below. #' @param sprintf String passed to the `?sprintf` function to format numbers or interpolate strings with a user-defined pattern (similar to the `glue` package, but using Base R). -#' @param ... Additional arguments are ignored. #' @inheritParams tt #' @inheritParams style_tt #' @template global_options @@ -39,39 +38,42 @@ #' @examples #' dat <- data.frame( #' a = rnorm(3, mean = 10000), -#' b = rnorm(3, 10000)) +#' b = rnorm(3, 10000) +#' ) #' tab <- tt(dat) #' format_tt(tab, -#' digits = 2, -#' num_mark_dec = ",", -#' num_mark_big = " ") -#' +#' digits = 2, +#' num_mark_dec = ",", +#' num_mark_big = " " +#' ) +#' #' k <- tt(data.frame(x = c(0.000123456789, 12.4356789))) #' format_tt(k, digits = 2, num_fmt = "significant_cell") -#' +#' #' dat <- data.frame( -#' a = c("Burger", "Halloumi", "Tofu", "Beans"), -#' b = c(1.43202, 201.399, 0.146188, 0.0031), -#' c = c(98938272783457, 7288839482, 29111727, 93945)) +#' a = c("Burger", "Halloumi", "Tofu", "Beans"), +#' b = c(1.43202, 201.399, 0.146188, 0.0031), +#' c = c(98938272783457, 7288839482, 29111727, 93945) +#' ) #' tt(dat) |> -#' format_tt(j = "a", sprintf = "Food: %s") |> -#' format_tt(j = 2, digits = 1, num_fmt = "decimal", num_zero = TRUE) |> -#' format_tt(j = "c", digits = 2, num_suffix = TRUE) -#' +#' format_tt(j = "a", sprintf = "Food: %s") |> +#' format_tt(j = 2, digits = 1, num_fmt = "decimal", num_zero = TRUE) |> +#' format_tt(j = "c", digits = 2, num_suffix = TRUE) +#' #' y <- tt(data.frame(x = c(123456789.678, 12435.6789))) -#' format_tt(y, digits=3, num_mark_big=" ") +#' format_tt(y, digits = 3, num_mark_big = " ") #' #' x <- tt(data.frame(Text = c("_italicized text_", "__bold text__"))) -#' format_tt(x, markdown=TRUE) +#' format_tt(x, markdown = TRUE) #' #' tab <- data.frame(a = c(NA, 1, 2), b = c(3, NA, 5)) #' tt(tab) |> format_tt(replace = "-") #' #' dat <- data.frame( -#' "LaTeX" = c("Dollars $", "Percent %", "Underscore _"), -#' "HTML" = c("
", "4", "blah") +#' "LaTeX" = c("Dollars $", "Percent %", "Underscore _"), +#' "HTML" = c("
", "4", "blah") #' ) -#' tt(dat) |> format_tt(escape = TRUE) +#' tt(dat) |> format_tt(escape = TRUE) #' format_tt <- function(x, i = NULL, @@ -82,386 +84,376 @@ format_tt <- function(x, num_suffix = get_option("tinytable_format_num_suffix", default = FALSE), num_mark_big = get_option("tinytable_format_num_mark_big", default = ""), num_mark_dec = get_option("tinytable_format_num_mark_dec", default = getOption("OutDec", default = ".")), - date = get_option("tinytable_format_date", default = "%Y-%m-%d"), - bool = get_option("tinytable_format_bool", default = function(column) tools::toTitleCase(tolower(column))), + date = get_option("tinytable_format_date", default = NULL), + bool = get_option("tinytable_format_bool", default = NULL), math = get_option("tinytable_format_math", default = FALSE), - other = get_option("tinytable_format_other", default = as.character), - replace = get_option("tinytable_format_replace", default = TRUE), + other = get_option("tinytable_format_other", default = NULL), + replace = get_option("tinytable_format_replace", default = FALSE), escape = get_option("tinytable_format_escape", default = FALSE), markdown = get_option("tinytable_format_markdown", default = FALSE), quarto = get_option("tinytable_format_quarto", default = FALSE), fn = get_option("tinytable_format_fn", default = NULL), - sprintf = get_option("tinytable_format_sprintf", default = NULL), - ... - ) { - out <- x - - dots <- list(...) - if ("replace_na" %in% names(dots)) { - replace <- dots[["replace_na"]] - warning("The `replace_na` argument was renamed `replace`.", call. = FALSE) - } - - if (inherits(out, "tinytable")) { - cal <- call("format_tt_lazy", - i = i, - j = j, - digits = digits, - num_fmt = num_fmt, - num_zero = num_zero, - num_suffix = num_suffix, - num_mark_big = num_mark_big, - num_mark_dec = num_mark_dec, - replace = replace, - fn = fn, - sprintf = sprintf, - url = url, - date = date, - bool = bool, - math = math, - escape = escape, - markdown = markdown, - quarto = quarto, - other = other, - inull = is.null(i), - jnull = is.null(j)) - out@lazy_format <- c(out@lazy_format, list(cal)) - } else { - - out <- format_tt_lazy(out, - i = i, - j = j, - digits = digits, - num_fmt = num_fmt, - num_zero = num_zero, - num_suffix = num_suffix, - num_mark_big = num_mark_big, - num_mark_dec = num_mark_dec, - replace = replace, - fn = fn, - sprintf = sprintf, - url = url, - date = date, - bool = bool, - math = math, - other = other, - escape = escape, - quarto = quarto, - markdown = markdown, - inull = is.null(i), - jnull = is.null(j)) - } - - return(out) + sprintf = get_option("tinytable_format_sprintf", default = NULL)) { + + assert_integerish(digits, len = 1, null.ok = TRUE) + assert_choice(num_fmt, c("significant", "significant_cell", "decimal", "scientific")) + assert_flag(num_zero) + assert_string(num_mark_big) + assert_string(num_mark_dec) + assert_string(date, null.ok = TRUE) + assert_function(bool, null.ok = TRUE) + assert_function(identity, null.ok = TRUE) + assert_function(other, null.ok = TRUE) + assert_flag(markdown) + assert_flag(quarto) + assert_function(fn, null.ok = TRUE) + assert_string(sprintf, null.ok = TRUE) + replace <- sanitize_replace(replace) + sanity_num_mark(digits, num_mark_big, num_mark_dec) + + out <- x + + if (inherits(out, "tinytable")) { + cal <- call("format_tt_lazy", + i = i, + j = j, + digits = digits, + num_fmt = num_fmt, + num_zero = num_zero, + num_suffix = num_suffix, + num_mark_big = num_mark_big, + num_mark_dec = num_mark_dec, + replace = replace, + fn = fn, + sprintf = sprintf, + url = url, + date = date, + bool = bool, + math = math, + escape = escape, + markdown = markdown, + quarto = quarto, + other = other, + inull = is.null(i), + jnull = is.null(j) + ) + out@lazy_format <- c(out@lazy_format, list(cal)) + } else { + out <- format_tt_lazy(out, + i = i, + j = j, + digits = digits, + num_fmt = num_fmt, + num_zero = num_zero, + num_suffix = num_suffix, + num_mark_big = num_mark_big, + num_mark_dec = num_mark_dec, + replace = replace, + fn = fn, + sprintf = sprintf, + url = url, + date = date, + bool = bool, + math = math, + other = other, + escape = escape, + quarto = quarto, + markdown = markdown, + inull = is.null(i), + jnull = is.null(j) + ) + } + + return(out) } format_tt_lazy <- function(x, - i = NULL, - j = NULL, + i, + j, digits, - num_fmt = "significant", - num_zero = FALSE, - num_suffix = FALSE, - num_mark_big = "", - num_mark_dec = NULL, - replace = TRUE, - fn = NULL, - sprintf = NULL, - url = FALSE, - date = "%Y-%m-%d", - bool = identity, - math = FALSE, - escape = FALSE, - markdown = FALSE, - quarto = quarto, - other = as.character, - inull = FALSE, - jnull = FALSE - ) { - - # format_tt() supports vectors - if (isTRUE(check_atomic_vector(x))) { - atomic_vector <- TRUE - if (is.factor(x)) x <- as.character(x) - ori <- out <- x <- data.frame(tinytable = x, stringsAsFactors = FALSE) - j <- 1 - } else if (is.data.frame(x)) { - atomic_vector <- FALSE - ori <- out <- x - } else if (inherits(x, "tinytable")){ - atomic_vector <- FALSE - # if no other format_tt() call has been applied, we ctan have numeric values - out <- x@table_dataframe - ori <- x@data + num_fmt, + num_zero, + num_suffix, + num_mark_big, + num_mark_dec, + replace, + fn, + sprintf, + url, + date, + bool, + math, + escape, + markdown, + quarto, + other, + inull, + jnull) { + # format_tt() supports vectors + if (isTRUE(check_atomic_vector(x))) { + atomic_vector <- TRUE + if (is.factor(x)) x <- as.character(x) + ori <- out <- x <- data.frame(tinytable = x, stringsAsFactors = FALSE) + j <- 1 + } else if (is.data.frame(x)) { + atomic_vector <- FALSE + ori <- out <- x + } else if (inherits(x, "tinytable")) { + atomic_vector <- FALSE + # if no other format_tt() call has been applied, we ctan have numeric values + out <- x@table_dataframe + ori <- x@data + } else { + stop("`x` must be a `tinytable` object, a data frame, or an atomic vector.", call. = FALSE) + } + + + i <- sanitize_i(i, x, lazy = FALSE) + j <- sanitize_j(j, x) + + # In sanity_tt(), we fill in missing NULL `j` in the format-specific versions, + # because tabularray can do whole column styling. Here, we need to fill in + # NULL for all formats since this is applied before creating the table. + # nrow(out) because nrow(x) sometimes includes rows that will be added **in the lazy future** by group_tt() + + # format each column + # Issue #230: drop=TRUE fixes bug which returned a character dput-like vector + for (col in j) { + # sprintf() is self-contained + if (!is.null(sprintf)) { + out[i, col] <- base::sprintf(sprintf, ori[i, col, drop = TRUE]) } else { - stop("`x` must be a `tinytable` object, a data frame, or an atomic vector.", call. = FALSE) + # logical + if (!is.null(bool) && is.logical(ori[i, col])) { + out[i, col] <- bool(ori[i, col, drop = TRUE]) + + # date + } else if (!is.null(date) && inherits(ori[i, col], "Date")) { + out[i, col] <- format(ori[i, col, drop = TRUE], date) + + # numeric + } else if (!is.null(digits) && is.numeric(ori[i, col, drop = TRUE])) { + tmp <- format_numeric(ori[i, col], + num_suffix = num_suffix, + digits = digits, + num_mark_big = num_mark_big, + num_mark_dec = num_mark_dec, + num_zero = num_zero, + num_fmt = num_fmt + ) + if (!is.null(tmp)) out[i, col] <- tmp + + # other + } else if (is.function(other)) { + out[i, col] <- other(ori[i, col, drop = TRUE]) + } } - assert_integerish(digits, len = 1, null.ok = TRUE) - assert_integerish(i, null.ok = TRUE) - assert_choice(num_fmt, c("significant", "significant_cell", "decimal", "scientific")) - assert_flag(num_zero) - assert_string(num_mark_big) - assert_string(num_mark_dec) - assert_string(date) - assert_function(bool) - assert_function(identity) - assert_function(fn, null.ok = TRUE) - assert_string(sprintf, null.ok = TRUE) - assert_flag(markdown) - assert_flag(quarto) - replace <- sanitize_replace(replace) - sanity_num_mark(digits, num_mark_big, num_mark_dec) - - i <- sanitize_i(i, x, lazy = FALSE) - j <- sanitize_j(j, x) - - # In sanity_tt(), we fill in missing NULL `j` in the format-specific versions, - # because tabularray can do whole column styling. Here, we need to fill in - # NULL for all formats since this is applied before creating the table. - # nrow(out) because nrow(x) sometimes includes rows that will be added **in the lazy future** by group_tt() - - # format each column - # Issue #230: drop=TRUE fixes bug which returned a character dput-like vector - for (col in j) { - # sprintf() is self-contained - if (!is.null(sprintf)) { - out[i, col] <- base::sprintf(sprintf, ori[i, col, drop = TRUE]) - - } else { - # logical - if (is.logical(ori[i, col])) { - out[i, col] <- bool(ori[i, col, drop = TRUE]) - - # date - } else if (inherits(ori[i, col], "Date")) { - out[i, col] <- format(ori[i, col, drop = TRUE], date) - - # numeric - } else if (is.numeric(ori[i, col, drop = TRUE])) { - tmp <- format_numeric(ori[i, col], - num_suffix = num_suffix, - digits = digits, - num_mark_big = num_mark_big, - num_mark_dec = num_mark_dec, - num_zero = num_zero, - num_fmt = num_fmt) - if (!is.null(tmp)) out[i, col] <- tmp - - # other - } else { - out[i, col] <- other(ori[i, col, drop = TRUE]) - } - } - - for (k in seq_along(replace)) { - idx <- ori[i, col, drop = TRUE] %in% replace[[k]] - out[i, col][idx] <- names(replace)[[k]] - } - - } # loop over columns + for (k in seq_along(replace)) { + idx <- ori[i, col, drop = TRUE] %in% replace[[k]] + out[i, col][idx] <- names(replace)[[k]] + } + } # loop over columns - # Custom functions overwrite all the other formatting, but is before markdown - # before escaping - if (is.function(fn)) { - for (col in j) { - out[i, col] <- fn(ori[i, col, drop = TRUE]) - } + # Custom functions overwrite all the other formatting, but is before markdown + # before escaping + if (is.function(fn)) { + for (col in j) { + out[i, col] <- fn(ori[i, col, drop = TRUE]) } + } - if (isTRUE(math)) { - for (row in i) { - for (col in j) { - out[row, col] <- format_math(out[row, col], math) - } + if (isTRUE(math)) { + for (row in i) { + for (col in j) { + out[row, col] <- format_math(out[row, col], math) + } + } + if (inull && jnull) { + x@caption <- format_math(x@caption, math) + colnames(x) <- format_math(colnames(x), math) + for (idx in seq_along(x@notes)) { + n <- x@notes[[idx]] + if (is.character(n) && length(n) == 1) { + x@notes[[idx]] <- format_math(n, math = math) + } else if (is.list(n) && "text" %in% names(n)) { + n$text <- format_math(n$text, math = math) + x@notes[[idx]] <- n + } + } + for (idx in seq_along(x@lazy_group)) { + g <- x@lazy_group[[idx]] + if (!is.null(g$j)) { + names(g$j) <- format_math(names(g$j), math = math) } - if (inull && jnull) { - x@caption <- format_math(x@caption, math) - colnames(x) <- format_math(colnames(x), math) - for (idx in seq_along(x@notes)) { - n <- x@notes[[idx]] - if (is.character(n) && length(n) == 1) { - x@notes[[idx]] <- format_math(n, math = math) - } else if (is.list(n) && "text" %in% names(n)) { - n$text <- format_math(n$text, math = math) - x@notes[[idx]] <- n - } - } - for (idx in seq_along(x@lazy_group)) { - g <- x@lazy_group[[idx]] - if (!is.null(g$j)) { - names(g$j) <- format_math(names(g$j), math = math) - } - if (!is.null(g$i)) { - names(g$i) <- format_math(names(g$i), math = math) - } - x@lazy_group[[idx]] <- g - } + if (!is.null(g$i)) { + names(g$i) <- format_math(names(g$i), math = math) } + x@lazy_group[[idx]] <- g + } + } + } + + + # escape latex characters + if (!isFALSE(escape)) { + if (isTRUE(escape == "latex")) { + o <- "latex" + } else if (isTRUE(escape == "html")) { + o <- "html" + } else if (isTRUE(escape == "typst")) { + o <- "typst" + } else if (inherits(x, "tinytable")) { + o <- x@output + } else { + o <- FALSE } - - # escape latex characters - if (!isFALSE(escape)) { - if (isTRUE(escape == "latex")) { - o <- "latex" - } else if (isTRUE(escape == "html")) { - o <- "html" - } else if (isTRUE(escape == "typst")) { - o <- "typst" - } else if (inherits(x, "tinytable")) { - o <- x@output - } else { - o <- FALSE + # caption & groups: if i and j are both null + if (inull && jnull) { + if (inherits(x, "tinytable")) { + x@caption <- escape_text(x@caption, output = o) + + for (idx in seq_along(x@notes)) { + n <- x@notes[[idx]] + if (is.character(n) && length(n) == 1) { + x@notes[[idx]] <- escape_text(n, output = o) + } else if (is.list(n) && "text" %in% names(n)) { + n$text <- escape_text(n$text, output = o) + x@notes[[idx]] <- n + } } - # caption & groups: if i and j are both null - if (inull && jnull) { - if (inherits(x, "tinytable")) { - x@caption <- escape_text(x@caption, output = o) - - for (idx in seq_along(x@notes)) { - n <- x@notes[[idx]] - if (is.character(n) && length(n) == 1) { - x@notes[[idx]] <- escape_text(n, output = o) - } else if (is.list(n) && "text" %in% names(n)) { - n$text <- escape_text(n$text, output = o) - x@notes[[idx]] <- n - } - } - - for (idx in seq_along(x@lazy_group)) { - g <- x@lazy_group[[idx]] - if (!is.null(g$j)) { - names(g$j) <- escape_text(names(g$j), output = o) - } - if (!is.null(g$i)) { - names(g$i) <- escape_text(names(g$i), output = o) - } - x@lazy_group[[idx]] <- g - } - } - colnames(x) <- escape_text(colnames(x), output = o) - for (col in seq_len(ncol(out))) { - out[, col] <- escape_text(out[, col], output = o) - } - - } else { - # body - for (row in i) { - for (col in j) { - out[row, col] <- escape_text(out[row, col], output = o) - } - } - - # column names - if (0 %in% i) { - colnames(x) <- escape_text(colnames(x), output = o) - } + for (idx in seq_along(x@lazy_group)) { + g <- x@lazy_group[[idx]] + if (!is.null(g$j)) { + names(g$j) <- escape_text(names(g$j), output = o) + } + if (!is.null(g$i)) { + names(g$i) <- escape_text(names(g$i), output = o) + } + x@lazy_group[[idx]] <- g } + } + colnames(x) <- escape_text(colnames(x), output = o) + for (col in seq_len(ncol(out))) { + out[, col] <- escape_text(out[, col], output = o) + } + } else { + # body + for (row in i) { + for (col in j) { + out[row, col] <- escape_text(out[row, col], output = o) + } + } + # column names + if (0 %in% i) { + colnames(x) <- escape_text(colnames(x), output = o) + } } + } - # markdown and quarto at the very end - for (col in j) { - if (isTRUE(markdown)) { - assert_dependency("markdown") - out <- format_markdown(out = out, i = i, col = col, x = x) - } - - if (isTRUE(quarto)) { - tmp <- format_quarto(out = out, i = i, col = col, x = x) - out <- tmp$out - x <- tmp$x - } + # markdown and quarto at the very end + for (col in j) { + if (isTRUE(markdown)) { + assert_dependency("markdown") + out <- format_markdown(out = out, i = i, col = col, x = x) } - if (inull && jnull && isTRUE(markdown)) { - colnames(x) <- format_markdown(colnames(x), x = x) - if (inherits(x, "tinytable")) { - for (k in seq_along(x@lazy_group)) { - g <- x@lazy_group[[k]] - if (!is.null(g$j)) { - names(g$j) <- format_markdown(names(g$j), x = x) - } - if (!is.null(g$i)) { - names(g$i) <- format_markdown(names(g$i), x = x) - } - x@lazy_group[[k]] <- g - } + if (isTRUE(quarto)) { + tmp <- format_quarto(out = out, i = i, col = col, x = x) + out <- tmp$out + x <- tmp$x + } + } + + if (inull && jnull && isTRUE(markdown)) { + colnames(x) <- format_markdown(colnames(x), x = x) + if (inherits(x, "tinytable")) { + for (k in seq_along(x@lazy_group)) { + g <- x@lazy_group[[k]] + if (!is.null(g$j)) { + names(g$j) <- format_markdown(names(g$j), x = x) } + if (!is.null(g$i)) { + names(g$i) <- format_markdown(names(g$i), x = x) + } + x@lazy_group[[k]] <- g + } } + } - # output - if (isTRUE(atomic_vector)) { - return(out[[1]]) - } else if (!inherits(x, "tinytable")) { - return(out) - } else { - x@table_dataframe <- out - return(x) - } + # output + if (isTRUE(atomic_vector)) { + return(out[[1]]) + } else if (!inherits(x, "tinytable")) { + return(out) + } else { + x@table_dataframe <- out + return(x) + } } format_math <- function(out, math) { - if (isTRUE(math)) { - out <- sprintf("$%s$", out) - } - return(out) + if (isTRUE(math)) { + out <- sprintf("$%s$", out) + } + return(out) } format_markdown <- function(out, i = NULL, col = NULL, x) { - tmpfun_html <- function(k) { - k <- trimws(markdown::mark_html(text = k, template = FALSE)) - k <- sub("

", "", k, fixed = TRUE) - k <- sub("

", "", k, fixed = TRUE) - return(k) + tmpfun_html <- function(k) { + k <- trimws(markdown::mark_html(text = k, template = FALSE)) + k <- sub("

", "", k, fixed = TRUE) + k <- sub("

", "", k, fixed = TRUE) + return(k) + } + + tmpfun_latex <- function(k) { + k <- trimws(markdown::mark_latex(text = k, template = FALSE)) + return(k) + } + + if (inherits(out, "data.frame")) { + ipos <- i[i > 0] + if (length(ipos) > 0) { + if (inherits(x, "tinytable_bootstrap")) { + out[ipos, col] <- sapply(out[ipos, col], function(k) tmpfun_html(k)) + } else if (inherits(x, "tinytable_tabularray")) { + out[ipos, col] <- sapply(out[ipos, col], function(k) tmpfun_latex(k)) + } } - - tmpfun_latex <- function(k) { - k <- trimws(markdown::mark_latex(text = k, template = FALSE)) - return(k) - } - - if (inherits(out, "data.frame")) { - ipos <- i[i > 0] - if (length(ipos) > 0) { - if (inherits(x, "tinytable_bootstrap")) { - out[ipos, col] <- sapply(out[ipos, col], function(k) tmpfun_html(k)) - } else if (inherits(x, "tinytable_tabularray")) { - out[ipos, col] <- sapply(out[ipos, col], function(k) tmpfun_latex(k)) - } - } - } else { - if (inherits(x, "tinytable_bootstrap")) { - out <- sapply(out, function(k) tmpfun_html(k)) - } else if (inherits(x, "tinytable_tabularray")) { - out <- sapply(out, function(k) tmpfun_latex(k)) - } + } else { + if (inherits(x, "tinytable_bootstrap")) { + out <- sapply(out, function(k) tmpfun_html(k)) + } else if (inherits(x, "tinytable_tabularray")) { + out <- sapply(out, function(k) tmpfun_latex(k)) } + } - return(out) + return(out) } format_quarto <- function(out, i, col, x) { - if (isTRUE(x@output == "html")) { - fun <- function(z) { - z@table_string <- sub("data-quarto-disable-processing='true'", - "data-quarto-disable-processing='false'", - z@table_string, - fixed = TRUE) - return(z) - } - x <- style_tt(x, finalize = fun) - out[i, col] <- sprintf('', out[i, col, drop = TRUE]) - } else if (isTRUE(x@output == "latex")) { - assert_dependency("base64enc") - tmp <- sapply(out[i, col, drop = TRUE], function(z) base64enc::base64encode(charToRaw(z))) - out[i, col] <- sprintf("\\QuartoMarkdownBase64{%s}", tmp) + if (isTRUE(x@output == "html")) { + fun <- function(z) { + z@table_string <- sub("data-quarto-disable-processing='true'", + "data-quarto-disable-processing='false'", + z@table_string, + fixed = TRUE + ) + return(z) } - - return(list("out" = out, "x" = x)) + x <- style_tt(x, finalize = fun) + out[i, col] <- sprintf('', out[i, col, drop = TRUE]) + } else if (isTRUE(x@output == "latex")) { + assert_dependency("base64enc") + tmp <- sapply(out[i, col, drop = TRUE], function(z) base64enc::base64encode(charToRaw(z))) + out[i, col] <- sprintf("\\QuartoMarkdownBase64{%s}", tmp) + } + + return(list("out" = out, "x" = x)) } - diff --git a/R/group_bootstrap.R b/R/group_bootstrap.R index 015d4f53..ca67fae4 100644 --- a/R/group_bootstrap.R +++ b/R/group_bootstrap.R @@ -14,7 +14,8 @@ setMethod( out <- group_bootstrap_row(out, i = i, j = j, indent = indent, ...) } return(out) - }) + } +) group_bootstrap_col <- function(x, j, ihead, ...) { @@ -33,7 +34,8 @@ group_bootstrap_col <- function(x, j, ihead, ...) { jstring <- lapply(names(j), function(n) { sprintf( '%s', - max(j[[n]]) - min(j[[n]]) + 1, n) + max(j[[n]]) - min(j[[n]]) + 1, n + ) }) jstring <- paste(unlist(jstring), collapse = "\n") jstring <- sprintf("\n%s\n", jstring) @@ -67,7 +69,8 @@ group_bootstrap_row <- function(x, i, j, indent = 1, ...) { # 0-indexing i[g] + x@nhead - 1, ncol(x), - names(i)[g]) + names(i)[g] + ) out <- lines_insert(out, js, "tinytable span after", "after") # out <- bootstrap_setting(out, new = js, component = "cell") } @@ -78,7 +81,8 @@ group_bootstrap_row <- function(x, i, j, indent = 1, ...) { "insertSpanRow(", paste0("insertSpanRow_", get_id(""), "("), out, - fixed = TRUE) + fixed = TRUE + ) idx <- insert_values(seq_len(nrow(x)), rep(NA, length(i)), i) diff --git a/R/group_grid.R b/R/group_grid.R index 08f32173..9e0e5729 100644 --- a/R/group_grid.R +++ b/R/group_grid.R @@ -9,7 +9,8 @@ setMethod( x <- group_grid_row(x, i) x <- group_grid_col(x, j) return(x) - }) + } +) group_grid_col <- function(x, j, ...) { diff --git a/R/group_tabularray.R b/R/group_tabularray.R index a2a971de..1565b88e 100644 --- a/R/group_tabularray.R +++ b/R/group_tabularray.R @@ -9,7 +9,8 @@ setMethod( x <- group_tabularray_col(x, j, ...) x <- group_tabularray_row(x, i, indent) return(x) - }) + } +) group_tabularray_col <- function(x, j, ihead, ...) { @@ -38,7 +39,8 @@ group_tabularray_col <- function(x, j, ihead, ...) { out[1:idx], # empty lines can break latex trimws(header), - out[(idx + 1):length(out)]) + out[(idx + 1):length(out)] + ) out <- paste(out, collapse = "\n") # rebuild including meta before style_tt @@ -54,7 +56,8 @@ group_tabularray_col <- function(x, j, ihead, ...) { i = ihead, j = z, align = "c", - colspan = cs) + colspan = cs + ) x <- do.call(style_tt, args) } diff --git a/R/group_tt.R b/R/group_tt.R index c3492f2a..ce198c6b 100644 --- a/R/group_tt.R +++ b/R/group_tt.R @@ -11,15 +11,16 @@ #' @param ... Other arguments are ignored. #' @return An object of class `tt` representing the table. #' @param indent integer number of `pt` to use when indenting the non-labelled rows. +#' @template limitations_word_markdown #' @details #' Warning: The `style_tt()` can normally be used to style the group headers, as expected, but that feature is not available for Markdown and Word tables. #' @examples #' #' # vector of row labels #' dat <- data.frame( -#' label = c("a", "a", "a", "b", "b", "c", "a", "a"), -#' x1 = rnorm(8), -#' x2 = rnorm(8)) +#' label = c("a", "a", "a", "b", "b", "c", "a", "a"), +#' x1 = rnorm(8), +#' x2 = rnorm(8)) #' tt(dat[, 2:3]) |> group_tt(i = dat$label) #' #' # named lists of labels @@ -51,7 +52,6 @@ #' group_tt(j = list("Hello" = 1:2, "World" = 3:4, "Hello" = 5:6)) |> #' group_tt(j = list("Foo" = 1:3, "Bar" = 4:6)) #' - group_tt <- function(x, i = NULL, j = NULL, indent = 1, ...) { # ... is important for ihead passing @@ -67,29 +67,30 @@ group_tt <- function(x, i = NULL, j = NULL, indent = 1, ...) { i <- sanitize_group_index(i, hi = nrow(x) + 1, orientation = "row") j <- sanitize_group_index(j, hi = ncol(x), orientation = "column") - # we don't need this as a list, and we use some sorting later + # increment indices eagerly i <- unlist(i) if (!is.null(i)) { - if (isTRUE(x@group_tt_i)) { + if (x@ngroupi > 0) { stop("Only one row-wise `group_tt(i = ...)` call is allowed.", call. = FALSE) } - x@group_tt_i <- TRUE + + x@ngroupi <- length(i) + x@nrow <- x@nrow + x@ngroupi + x@group_i_idx <- as.numeric(i) + if (isTRUE(indent > 0)) { - idx_indent <- setdiff( - seq_len(nrow(x) + length(i)), - i + seq_along(i) - 1) + idx_indent <- setdiff(seq_len(nrow(x)), i + seq_along(i) - 1) x <- style_tt(x, i = idx_indent, j = 1, indent = indent) } } - if (!is.null(i)) { - x@ngroupi <- x@ngroupi + length(i) - x@group_i_idx <- as.numeric(unlist(i)) + if (!is.null(j)) { + x@nhead <- x@nhead + 1 } + # apply group labels lazily cal <- call("group_eval", i = i, j = j, indent = indent) - x@lazy_group <- c(x@lazy_group, list(cal)) return(x) diff --git a/R/group_typst.R b/R/group_typst.R index d651f5df..5948fdbe 100644 --- a/R/group_typst.R +++ b/R/group_typst.R @@ -16,7 +16,8 @@ setMethod( } return(out) - }) + } +) group_typst_row <- function(x, i, indent, ...) { @@ -24,7 +25,6 @@ group_typst_row <- function(x, i, indent, ...) { tab <- strsplit(tab, split = "\\n")[[1]] body_min <- utils::head(grep("tinytable cell content after", tab), 1) + 1 body_max <- utils::head(grep("end table", tab), 1) - 1 - body <- body_min:body_max top <- tab[1:(body_min - 1)] mid <- tab[body_min:body_max] mid <- mid[mid != ""] @@ -32,15 +32,15 @@ group_typst_row <- function(x, i, indent, ...) { for (idx in rev(seq_along(i))) { mid <- append(mid, sprintf("table.cell(colspan: %s)[%s],", ncol(x), names(i)[idx]), - after = i[idx] - 1) + after = i[idx] - 1 + ) } tab <- c(top, mid, bot) tab <- paste(tab, collapse = "\n") x@table_string <- tab idx_new <- i + seq_along(i) - 1 - idx_all <- seq_len(nrow(x) + length(i)) + idx_all <- seq_len(nrow(x)) idx <- setdiff(idx_all, idx_new) - # x <- style_tt(x, idx, indent = indent) return(x) } @@ -58,7 +58,8 @@ group_typst_col <- function(x, j, ihead, ...) { col <- ifelse( trimws(lab) == "", sprintf("[%s],", lab), - sprintf("table.cell(stroke: (bottom: .05em + black), colspan: %s, align: center)[%s],", len, lab)) + sprintf("table.cell(stroke: (bottom: .05em + black), colspan: %s, align: center)[%s],", len, lab) + ) col <- paste(col, collapse = "") out <- lines_insert(out, col, "repeat: true", "after") if (!any(grepl("column-gutter", out))) { diff --git a/R/last_style.R b/R/last_style.R index d132560e..69a52d96 100644 --- a/R/last_style.R +++ b/R/last_style.R @@ -1,25 +1,27 @@ last_valid <- function(x) { - x <- x[!is.na(x)] - if (length(x) == 0) return(NA) - return(utils::tail(x, 1)) + x <- x[!is.na(x)] + if (length(x) == 0) { + return(NA) + } + return(utils::tail(x, 1)) } last_style_vec <- function(x) { - if (is.factor(x)) { - x <- as.character(x) - } - if (is.logical(x) && !all(is.na(x))) { - x <- any(sapply(x, isTRUE)) - } else { - x <- last_valid(x) - } - return(x) + if (is.factor(x)) { + x <- as.character(x) + } + if (is.logical(x) && !all(is.na(x))) { + x <- any(sapply(x, isTRUE)) + } else { + x <- last_valid(x) + } + return(x) } last_style <- function(sty) { - sty <- split(sty, list(sty$i, sty$j)) - sty <- lapply(sty, function(k) lapply(k, last_style_vec)) - sty <- do.call(rbind, lapply(sty, data.frame)) - return(sty) + sty <- split(sty, list(sty$i, sty$j)) + sty <- lapply(sty, function(k) lapply(k, last_style_vec)) + sty <- do.call(rbind, lapply(sty, data.frame)) + return(sty) } diff --git a/R/package.R b/R/package.R index a133c157..e321b112 100644 --- a/R/package.R +++ b/R/package.R @@ -2,5 +2,5 @@ # 2012 hadley says "globalVariables is a hideous hack and I will never use it" # 2014 hadley updates his own answer with globalVariables as one of "two solutions" utils::globalVariables(c( -"bootstrap" + "bootstrap" )) diff --git a/R/plot_tt.R b/R/plot_tt.R index 95066323..3c0b0209 100644 --- a/R/plot_tt.R +++ b/R/plot_tt.R @@ -102,7 +102,8 @@ plot_tt <- function(x, xlim = xlim, height = height, images = images, - assets = assets) + assets = assets + ) cal <- c(cal, list(...)) cal <- do.call(call, cal) @@ -130,9 +131,9 @@ plot_tt_lazy <- function(x, assert_dependency("ggplot2") images <- NULL - if(isTRUE(x@output == "html") && isTRUE(x@portable)) { - path_full <- tempdir() - assets <- tempdir() + if (isTRUE(x@output == "html") && isTRUE(x@portable)) { + path_full <- tempdir() + assets <- tempdir() } else { path_full <- file.path(x@output_dir, assets) } @@ -182,7 +183,7 @@ plot_tt_lazy <- function(x, if (isTRUE(x@output == "latex")) { cell <- "\\includegraphics[height=%sem]{%s}" cell <- sprintf(cell, height, images) - } else if(isTRUE(x@output == "html") && isTRUE(x@portable)) { + } else if (isTRUE(x@output == "html") && isTRUE(x@portable)) { assert_dependency("base64enc") http <- grepl("^http", trimws(images)) @@ -192,7 +193,8 @@ plot_tt_lazy <- function(x, cell <- ifelse( grepl("^http", trimws(images)), '', - '') + '' + ) cell <- sprintf(cell, images, height) } else if (isTRUE(x@output == "markdown")) { cell <- "![](%s){ height=%s }" @@ -250,7 +252,7 @@ encode <- function(images) { assert_dependency("base64enc") ext <- tools::file_ext(images) - if(any(ext == "")) stop("Empty image extensions are not allowed", call. = FALSE) + if (any(ext == "")) stop("Empty image extensions are not allowed", call. = FALSE) encoded <- sapply(images, base64enc::base64encode) sprintf("data:image/%s;base64, %s", ext, encoded) diff --git a/R/posit.R b/R/posit.R new file mode 100644 index 00000000..d63ef152 --- /dev/null +++ b/R/posit.R @@ -0,0 +1,20 @@ +is_rstudio <- function() { + identical(Sys.getenv("RSTUDIO"), "1") +} + +is_positron <- function() { + identical(Sys.getenv("POSITRON"), "1") +} + +is_rstudio_notebook <- function() { + flag <- FALSE + # inline doesn't work in Positron + if (is_rstudio()) { + assert_dependency("rstudioapi") + con <- rstudioapi::getActiveDocumentContext()[["path"]] + if (isTRUE(grepl("\\.qmd$|\\.Rmd$", con))) { + flag <- TRUE + } + } + return(flag) +} diff --git a/R/print.R b/R/print.R index ae104caa..4a5f0f8c 100644 --- a/R/print.R +++ b/R/print.R @@ -1,6 +1,7 @@ #' Print a tinytable object in knitr #' #' @keywords internal +#' @rawNamespace S3method(knitr::knit_print, tinytable) #' @return A string with class `knit_asis` to be printed in Rmarkdown or Quarto documents. #' @export knit_print.tinytable <- function(x, @@ -36,7 +37,6 @@ knit_print.tinytable <- function(x, return(out) } - #' Print, display, or convert a tinytable object #' #' This function is called automatically by `R` whenever a `tinytable` object is anprinted to the console or in an HTML viewer pane. @@ -74,6 +74,16 @@ print.tinytable <- function(x, if (output %in% c("latex", "typst", "markdown", "gfm")) { cat(tab, "\n") } else if (output == "html") { + if (is_rstudio_notebook()) { + tinytable_print_rstudio <- getOption("tinytable_print_rstudio_notebook", default = "inline") + assert_choice(tinytable_print_rstudio, c("inline", "viewer")) + if (tinytable_print_rstudio == "inline") { + tab <- sprintf("\n```{=html}\n%s\n```\n`", tab) + print(knitr::asis_output(tab)) + return(invisible(x)) + } + } + # need to change the output directory to a temporary directory # for plot_tt() inline plots to show up in RStudio htmlFile <- file.path(dir, "index.html") diff --git a/R/rbind2.R b/R/rbind2.R index d704446c..510923e9 100644 --- a/R/rbind2.R +++ b/R/rbind2.R @@ -1,5 +1,5 @@ #' Combine `tinytable` objects by rows (vertically) -#' +#' #' @details #' `format_tt()` calls applied to `x` or `y` are evaluated before binding, to allow distinct formatting for each panel. #' @@ -25,55 +25,56 @@ #' @aliases rbind2 #' @examples #' library(tinytable) -#' x = tt(mtcars[1:3, 1:2], caption = "Combine two tiny tables.") -#' y = tt(mtcars[4:5, 8:10]) -#' +#' x <- tt(mtcars[1:3, 1:2], caption = "Combine two tiny tables.") +#' y <- tt(mtcars[4:5, 8:10]) +#' #' # rbind() does not support additional aarguments #' # rbind2() supports additional arguments -#' +#' #' # basic combination #' rbind(x, y) -#' +#' #' rbind(x, y) |> format_tt(replace = "") -#' +#' #' # omit y header #' rbind2(x, y, headers = FALSE) -#' +#' #' # bind by position rather than column names #' rbind2(x, y, use_names = FALSE) -#' +#' #' @importFrom methods rbind2 #' @export -setMethod("rbind2", - signature = signature(x = "tinytable", y = "tinytable"), - definition = function(x, y, - use_names = TRUE, - headers = TRUE, - ...) { +setMethod("rbind2", + signature = signature(x = "tinytable", y = "tinytable"), + definition = function(x, y, + use_names = TRUE, + headers = TRUE, + ...) { + assert_class(x, "tinytable") + assert_class(y, "tinytable") + assert_dependency("data.table") + assert_flag(use_names) + assert_flag(headers) - assert_class(x, "tinytable") - assert_class(y, "tinytable") - assert_dependency("data.table") - assert_flag(use_names) - assert_flag(headers) + x_df <- print(x, output = "dataframe") + y_df <- print(y, output = "dataframe") - x_df <- print(x, output = "dataframe") - y_df <- print(y, output = "dataframe") + if (isTRUE(headers) && !is.null(colnames(y))) { + y_df <- base::rbind(colnames(y_df), y_df) + } - if (isTRUE(headers) && !is.null(colnames(y))) { - y_df <- base::rbind(colnames(y_df), y_df) - } + out <- data.table::rbindlist(list(x_df, y_df), + fill = TRUE, + use.names = use_names + ) - out <- data.table::rbindlist(list(x_df, y_df), - fill = TRUE, - use.names = use_names) + out <- tt(out) - out <- tt(out) + out@output <- x@output + out@notes <- c(x@notes, y@notes) + out@width <- x@width + out@caption <- x@caption - out@output <- x@output - out@notes <- c(x@notes, y@notes) - out@width <- x@width - out@caption <- x@caption - - return(out) -}) + return(out) + } +) diff --git a/R/sanity.R b/R/sanity.R index cf267bb4..ff119a2f 100644 --- a/R/sanity.R +++ b/R/sanity.R @@ -1,14 +1,14 @@ usepackage_latex <- function(name, options = NULL, extra_lines = NULL) { - assert_dependency("rmarkdown") - invisible(knitr::knit_meta_add(list(rmarkdown::latex_dependency(name, options, extra_lines)))) + assert_dependency("rmarkdown") + invisible(knitr::knit_meta_add(list(rmarkdown::latex_dependency(name, options, extra_lines)))) } sanity_align <- function(align, i) { - if (any(grepl("d", align)) && !is.null(i)) { - msg <- "d column alignment can only be applied to entire columns. `i` must be `NULL`." - stop(msg, call. = FALSE) - } + if (any(grepl("d", align)) && !is.null(i)) { + msg <- "d column alignment can only be applied to entire columns. `i` must be `NULL`." + stop(msg, call. = FALSE) + } } @@ -31,78 +31,104 @@ sanitize_i <- function(i, x, pre_group_i = FALSE, lazy = TRUE) { } return(out) } +sanitize_i <- function(i, x, pre_group_i = FALSE, lazy = TRUE) { + if (is.character(i)) { + assert_choice(i, c("notes", "caption")) + return(i) + } else if (is.matrix(i) && is.logical(i)) { + return(i) + } + out <- seq_len(nrow(x)) + assert_numeric(i, null.ok = TRUE, name = "i") + if (is.null(i) && isTRUE(lazy)) { + out <- NA + attr(out, "null") <- TRUE + attr(out, "body") <- seq_len(nrow(x)) + attr(out, "head") <- integer() + } else { + if (!is.null(i)) { + out <- i + } else if (inherits(x, "tinytable")) { + out <- seq_len(nrow(x@table_dataframe)) + } + attr(out, "null") <- FALSE + attr(out, "body") <- out[out > 0] + attr(out, "head") <- out[out < 1] + } + return(out) +} sanitize_j <- function(j, x) { - # regex - if (is.character(j) && length(j) == 1 && !is.null(colnames(x))) { - out <- grep(j, colnames(x), perl = TRUE) - # full names - } else if (is.character(j) && length(j) > 1 && !is.null(colnames(x))) { - bad <- setdiff(j, colnames(x)) - if (length(bad) > 0) { - msg <- sprintf("Missing columns: %s", paste(bad, collapse = ", ")) - stop(msg, call. = FALSE) - } - out <- which(colnames(x) %in% j) + # regex + if (is.character(j) && length(j) == 1 && !is.null(colnames(x))) { + out <- grep(j, colnames(x), perl = TRUE) + # full names + } else if (is.character(j) && length(j) > 1 && !is.null(colnames(x))) { + bad <- setdiff(j, colnames(x)) + if (length(bad) > 0) { + msg <- sprintf("Missing columns: %s", paste(bad, collapse = ", ")) + stop(msg, call. = FALSE) + } + out <- which(colnames(x) %in% j) + } else { + assert_integerish(j, lower = 1, upper = ncol(x), null.ok = TRUE) + if (is.null(j)) { + out <- seq_len(ncol(x)) } else { - assert_integerish(j, lower = 1, upper = ncol(x), null.ok = TRUE) - if (is.null(j)) { - out <- seq_len(ncol(x)) - } else { - out <- j - } + out <- j } - attr(out, "null") <- is.null(j) - return(out) + } + attr(out, "null") <- is.null(j) + return(out) } sanitize_output <- function(output) { - assert_choice(output, choice = c("tinytable", "markdown", "latex", "html", "typst", "dataframe", "gfm"), null.ok = TRUE) - - # default output format - if (is.null(output) || isTRUE(output == "tinytable")) { - has_viewer <- interactive() && !is.null(getOption("viewer")) - out <- if (has_viewer) "html" else "markdown" - } else { - out <- output - } - - if (isTRUE(check_dependency("knitr"))) { - if (isTRUE(knitr::pandoc_to() %in% c("latex", "beamer"))) { - flag <- getOption("tinytable_latex_preamble", default = TRUE) - if (isTRUE(flag)) { - usepackage_latex("float") - usepackage_latex("tabularray", extra_lines = c( - "\\usepackage[normalem]{ulem}", - "\\usepackage{graphicx}", - "\\UseTblrLibrary{booktabs}", - "\\UseTblrLibrary{rotating}", - "\\UseTblrLibrary{siunitx}", - "\\NewTableCommand{\\tinytableDefineColor}[3]{\\definecolor{#1}{#2}{#3}}", - "\\newcommand{\\tinytableTabularrayUnderline}[1]{\\underline{#1}}", - "\\newcommand{\\tinytableTabularrayStrikeout}[1]{\\sout{#1}}" - )) - } - if (is.null(output)) out <- "latex" - } else if (isTRUE(knitr::pandoc_to() %in% c("html", "revealjs"))) { - if (is.null(output)) out <- "html" - } else if (isTRUE(knitr::pandoc_to() == "typst")) { - if (is.null(output)) out <- "typst" - if (isTRUE(check_dependency("quarto"))) { - if (isTRUE(quarto::quarto_version() < "1.5.29")) { - msg <- "Typst tables require version 1.5.29 or later of Quarto and version 0.11.0 or later of Typst. This software may (or may not) only be available in pre-release builds: https://quarto.org/docs/download" - stop(msg, call. = FALSE) - } - } - } else if (isTRUE(knitr::pandoc_to() == "docx")) { - if (is.null(output)) out <- "markdown" - } else { - if (is.null(output)) out <- "markdown" + assert_choice(output, choice = c("tinytable", "markdown", "latex", "html", "typst", "dataframe", "gfm"), null.ok = TRUE) + + # default output format + if (is.null(output) || isTRUE(output == "tinytable")) { + has_viewer <- interactive() && !is.null(getOption("viewer")) + out <- if (has_viewer) "html" else "markdown" + } else { + out <- output + } + + if (isTRUE(check_dependency("knitr"))) { + if (isTRUE(knitr::pandoc_to() %in% c("latex", "beamer"))) { + flag <- getOption("tinytable_latex_preamble", default = TRUE) + if (isTRUE(flag)) { + usepackage_latex("float") + usepackage_latex("tabularray", extra_lines = c( + "\\usepackage[normalem]{ulem}", + "\\usepackage{graphicx}", + "\\UseTblrLibrary{booktabs}", + "\\UseTblrLibrary{rotating}", + "\\UseTblrLibrary{siunitx}", + "\\NewTableCommand{\\tinytableDefineColor}[3]{\\definecolor{#1}{#2}{#3}}", + "\\newcommand{\\tinytableTabularrayUnderline}[1]{\\underline{#1}}", + "\\newcommand{\\tinytableTabularrayStrikeout}[1]{\\sout{#1}}" + )) + } + if (is.null(output)) out <- "latex" + } else if (isTRUE(knitr::pandoc_to() %in% c("html", "revealjs"))) { + if (is.null(output)) out <- "html" + } else if (isTRUE(knitr::pandoc_to() == "typst")) { + if (is.null(output)) out <- "typst" + if (isTRUE(check_dependency("quarto"))) { + if (isTRUE(quarto::quarto_version() < "1.5.29")) { + msg <- "Typst tables require version 1.5.29 or later of Quarto and version 0.11.0 or later of Typst. This software may (or may not) only be available in pre-release builds: https://quarto.org/docs/download" + stop(msg, call. = FALSE) } + } + } else if (isTRUE(knitr::pandoc_to() == "docx")) { + if (is.null(output)) out <- "markdown" + } else { + if (is.null(output)) out <- "markdown" } + } - return(out) + return(out) } @@ -110,315 +136,315 @@ sanitize_output <- function(output) { #' #' @noRd check_dependency <- function(library_name) { - flag <- requireNamespace(library_name, quietly = TRUE) - if (isFALSE(flag)) { - msg <- sprintf("Please install the `%s` package.", library_name) - return(msg) - } else { - return(TRUE) - } + flag <- requireNamespace(library_name, quietly = TRUE) + if (isFALSE(flag)) { + msg <- sprintf("Please install the `%s` package.", library_name) + return(msg) + } else { + return(TRUE) + } } assert_dependency <- function(library_name) { - flag <- check_dependency(library_name) - if (!isTRUE(flag)) stop(flag, call. = FALSE) - return(invisible()) + flag <- check_dependency(library_name) + if (!isTRUE(flag)) stop(flag, call. = FALSE) + return(invisible()) } assert_choice <- function(x, choice, null.ok = FALSE, name = as.character(substitute(x))) { - if (is.null(x) && isTRUE(null.ok)) { - return(TRUE) - } - if (is.character(x) && length(x) == 1 && x %in% choice) { - return(TRUE) - } - msg <- sprintf( - "`%s` must be one of: %s", - name, - paste(choice, collapse = ", ") - ) - stop(msg, call. = FALSE) + if (is.null(x) && isTRUE(null.ok)) { + return(TRUE) + } + if (is.character(x) && length(x) == 1 && x %in% choice) { + return(TRUE) + } + msg <- sprintf( + "`%s` must be one of: %s", + name, + paste(choice, collapse = ", ") + ) + stop(msg, call. = FALSE) } check_string <- function(x, null.ok = FALSE) { - if (is.null(x) && isTRUE(null.ok)) { - return(invisible(TRUE)) - } - if (is.character(x) && length(x) == 1) { - return(invisible(TRUE)) - } - return(FALSE) + if (is.null(x) && isTRUE(null.ok)) { + return(invisible(TRUE)) + } + if (is.character(x) && length(x) == 1) { + return(invisible(TRUE)) + } + return(FALSE) } assert_string <- function(x, null.ok = FALSE, name = as.character(substitute(x))) { - msg <- sprintf("`%s` must be a string.", name) - if (!isTRUE(check_string(x, null.ok = null.ok))) { - stop(msg, call. = FALSE) - } + msg <- sprintf("`%s` must be a string.", name) + if (!isTRUE(check_string(x, null.ok = null.ok))) { + stop(msg, call. = FALSE) + } } check_flag <- function(x, null.ok = FALSE) { - if (is.null(x) && isTRUE(null.ok)) { - return(TRUE) - } - if (is.logical(x) && length(x) == 1) { - return(TRUE) - } - return(FALSE) + if (is.null(x) && isTRUE(null.ok)) { + return(TRUE) + } + if (is.logical(x) && length(x) == 1) { + return(TRUE) + } + return(FALSE) } assert_flag <- function(x, null.ok = FALSE, name = as.character(substitute(x))) { - msg <- sprintf("`%s` must be a logical flag.", name) - if (!isTRUE(check_flag(x, null.ok = null.ok))) { - stop(msg, call. = FALSE) - } + msg <- sprintf("`%s` must be a logical flag.", name) + if (!isTRUE(check_flag(x, null.ok = null.ok))) { + stop(msg, call. = FALSE) + } } check_function <- function(x, null.ok = FALSE) { - if (is.null(x) && isTRUE(null.ok)) { - return(TRUE) - } - if (is.function(x)) { - return(TRUE) - } - return(FALSE) + if (is.null(x) && isTRUE(null.ok)) { + return(TRUE) + } + if (is.function(x)) { + return(TRUE) + } + return(FALSE) } assert_function <- function(x, null.ok = FALSE, name = as.character(substitute(x))) { - msg <- sprintf("`%s` must be a function.", name) - if (!isTRUE(check_function(x, null.ok = null.ok))) { - stop(msg, call. = FALSE) - } + msg <- sprintf("`%s` must be a function.", name) + if (!isTRUE(check_function(x, null.ok = null.ok))) { + stop(msg, call. = FALSE) + } } assert_length <- function(x, len = 1, null.ok = FALSE, name = as.character(substitute(x))) { - if (is.null(x) && isTRUE(null.ok)) { - return(invisible(TRUE)) - } - msg <- sprintf("`%s` must be one of these lengths: %s", name, paste(len, collapse = ", ")) - if (!length(x) %in% len) { - stop(msg, call. = FALSE) - } + if (is.null(x) && isTRUE(null.ok)) { + return(invisible(TRUE)) + } + msg <- sprintf("`%s` must be one of these lengths: %s", name, paste(len, collapse = ", ")) + if (!length(x) %in% len) { + stop(msg, call. = FALSE) + } } assert_logical <- function(x, null.ok = FALSE, name = as.character(substitute(x))) { - if (is.null(x) && isTRUE(null.ok)) { - return(invisible(TRUE)) - } - msg <- sprintf("`%s` must be a logical vector", name) - if (!is.logical(x)) stop(msg, call. = FALSE) + if (is.null(x) && isTRUE(null.ok)) { + return(invisible(TRUE)) + } + msg <- sprintf("`%s` must be a logical vector", name) + if (!is.logical(x)) stop(msg, call. = FALSE) } check_integerish <- function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) { - if (is.null(x) && isTRUE(null.ok)) { - return(TRUE) - } - if (!is.numeric(x)) { - return(FALSE) - } - x <- stats::na.omit(x) - if (!is.null(len) && length(x) != len) { - return(FALSE) - } - if (!is.null(lower) && any(x < lower)) { - return(FALSE) - } - if (!is.null(upper) && any(x > upper)) { - return(FALSE) - } - if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) { - return(FALSE) - } + if (is.null(x) && isTRUE(null.ok)) { return(TRUE) + } + if (!is.numeric(x)) { + return(FALSE) + } + x <- stats::na.omit(x) + if (!is.null(len) && length(x) != len) { + return(FALSE) + } + if (!is.null(lower) && any(x < lower)) { + return(FALSE) + } + if (!is.null(upper) && any(x > upper)) { + return(FALSE) + } + if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) { + return(FALSE) + } + return(TRUE) } assert_integerish <- function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) { - if (isTRUE(null.ok) && is.null(x)) { - return(invisible()) - } - msg <- sprintf("`%s` must be integer-ish", name) - if (is.null(x) && !isTRUE(null.ok)) stop(sprintf("%s should not be NULL.", name), call. = FALSE) - if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) { - if (!is.numeric(x)) msg <- paste0(msg, "; it is not numeric") - if (!is.null(len) && length(x) != len) msg <- paste0(msg, sprintf("; its length must be %s", len)) - if (!is.null(lower) && any(x < lower)) msg <- paste0(msg, sprintf("; all values must be greater than or equal to %s", lower)) - if (!is.null(upper) && any(x > upper)) msg <- paste0(msg, sprintf("; all values must be less than or equal to %s", upper)) - if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg <- paste0(msg, "; all values must be close to integers") - stop(msg, call. = FALSE) - } + if (isTRUE(null.ok) && is.null(x)) { + return(invisible()) + } + msg <- sprintf("`%s` must be integer-ish", name) + if (is.null(x) && !isTRUE(null.ok)) stop(sprintf("%s should not be NULL.", name), call. = FALSE) + if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) { + if (!is.numeric(x)) msg <- paste0(msg, "; it is not numeric") + if (!is.null(len) && length(x) != len) msg <- paste0(msg, sprintf("; its length must be %s", len)) + if (!is.null(lower) && any(x < lower)) msg <- paste0(msg, sprintf("; all values must be greater than or equal to %s", lower)) + if (!is.null(upper) && any(x > upper)) msg <- paste0(msg, sprintf("; all values must be less than or equal to %s", upper)) + if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg <- paste0(msg, "; all values must be close to integers") + stop(msg, call. = FALSE) + } } check_null <- function(x) { - is.null(x) + is.null(x) } assert_null <- function(x, name = as.character(substitute(x))) { - if (!isTRUE(check_null(x))) stop(sprintf("%s should be NULL.", name), call. = FALSE) + if (!isTRUE(check_null(x))) stop(sprintf("%s should be NULL.", name), call. = FALSE) } check_numeric <- function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) { - if (is.null(x) && isTRUE(null.ok)) { - return(TRUE) - } - if (!is.numeric(x)) { - return(FALSE) - } - if (!is.null(len) && length(x) != len) { - return(FALSE) - } - if (!is.null(lower) && any(x < lower)) { - return(FALSE) - } - if (!is.null(upper) && any(x > upper)) { - return(FALSE) - } + if (is.null(x) && isTRUE(null.ok)) { return(TRUE) + } + if (!is.numeric(x)) { + return(FALSE) + } + if (!is.null(len) && length(x) != len) { + return(FALSE) + } + if (!is.null(lower) && any(x < lower)) { + return(FALSE) + } + if (!is.null(upper) && any(x > upper)) { + return(FALSE) + } + return(TRUE) } assert_numeric <- function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) { - msg <- sprintf("`%s` must be numeric", name) - if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) { - if (!is.null(len) && length(x) != len) msg <- paste0(msg, sprintf("; its length must be %s", len)) - if (!is.null(lower) && any(x < lower)) msg <- paste0(msg, sprintf("; all values must be greater than or equal to %s", lower)) - if (!is.null(upper) && any(x > upper)) msg <- paste0(msg, sprintf("; all values must be less than or equal to %s", upper)) - stop(msg, call. = FALSE) - } + msg <- sprintf("`%s` must be numeric", name) + if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) { + if (!is.null(len) && length(x) != len) msg <- paste0(msg, sprintf("; its length must be %s", len)) + if (!is.null(lower) && any(x < lower)) msg <- paste0(msg, sprintf("; all values must be greater than or equal to %s", lower)) + if (!is.null(upper) && any(x > upper)) msg <- paste0(msg, sprintf("; all values must be less than or equal to %s", upper)) + stop(msg, call. = FALSE) + } } assert_data_frame <- function(x, min_rows = 0, min_cols = 0, name = as.character(substitute(x))) { - msg <- sprintf("`%s` must be a data.frame.", name) - if (!is.data.frame(x)) stop(msg, call. = FALSE) - msg <- sprintf("Number of rows in `%s` must be at least `%s`", name, min_rows) - if (nrow(x) < min_rows) stop(msg, call. = FALSE) - msg <- sprintf("Number of columns in `%s` must be at least `%s`", name, min_cols) - if (ncol(x) < min_cols) stop(msg, call. = FALSE) + msg <- sprintf("`%s` must be a data.frame.", name) + if (!is.data.frame(x)) stop(msg, call. = FALSE) + msg <- sprintf("Number of rows in `%s` must be at least `%s`", name, min_rows) + if (nrow(x) < min_rows) stop(msg, call. = FALSE) + msg <- sprintf("Number of columns in `%s` must be at least `%s`", name, min_cols) + if (ncol(x) < min_cols) stop(msg, call. = FALSE) } check_character <- function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) { - if (isTRUE(null.ok) && is.null(x)) { - return(TRUE) - } else if (!is.character(x)) { - msg <- sprintf("`%s` must be character.", name) - return(msg) - } else if (!is.null(len) && length(x) != len) { - msg <- sprintf("`%s` must have length %s.", name, len) - return(msg) - } + if (isTRUE(null.ok) && is.null(x)) { return(TRUE) + } else if (!is.character(x)) { + msg <- sprintf("`%s` must be character.", name) + return(msg) + } else if (!is.null(len) && length(x) != len) { + msg <- sprintf("`%s` must have length %s.", name, len) + return(msg) + } + return(TRUE) } assert_character <- function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) { - flag <- check_character(x, len = len, null.ok = null.ok, name = name) - if (!isTRUE(flag)) { - stop(flag, call. = FALSE) - } else { - return(invisible(TRUE)) - } + flag <- check_character(x, len = len, null.ok = null.ok, name = name) + if (!isTRUE(flag)) { + stop(flag, call. = FALSE) + } else { + return(invisible(TRUE)) + } } assert_list <- function(x, named = FALSE, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) { - if (isTRUE(null.ok) && is.null(x)) { - return(invisible(TRUE)) - } - if (!is.list(x)) stop("Input is not a list.", call. = FALSE) - if (isTRUE(named)) { - if (is.null(names(x))) { - stop(sprintf("`%s` should be named list.", name), call. = FALSE) - } + if (isTRUE(null.ok) && is.null(x)) { + return(invisible(TRUE)) + } + if (!is.list(x)) stop("Input is not a list.", call. = FALSE) + if (isTRUE(named)) { + if (is.null(names(x))) { + stop(sprintf("`%s` should be named list.", name), call. = FALSE) } - if (!is.null(len)) { - if (length(x) != len) { - stop(sprintf("`%s` must be of length %s.", name, len), call. = FALSE) - } + } + if (!is.null(len)) { + if (length(x) != len) { + stop(sprintf("`%s` must be of length %s.", name, len), call. = FALSE) } + } } assert_function <- function(x, null.ok = FALSE, name = as.character(substitute(x))) { - if (isTRUE(null.ok) && is.null(x)) { - return(invisible(TRUE)) - } - if (!is.function(x)) { - msg <- sprintf("`%s` must be a function.", name) - stop(msg, call. = FALSE) - } + if (isTRUE(null.ok) && is.null(x)) { + return(invisible(TRUE)) + } + if (!is.function(x)) { + msg <- sprintf("`%s` must be a function.", name) + stop(msg, call. = FALSE) + } } check_atomic_vector <- function(x, null.ok = FALSE, name = as.character(substitute(x))) { - if (isTRUE(null.ok) && is.null(x)) { - return(invisible(TRUE)) - } - # doesn't work on glue::glue() output - # flag <- is.atomic(x) && is.vector(x) && !is.list(x) - flag <- is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x) - if (flag) { - out <- TRUE - } else if (is.factor(x) && is.null(dim(x))) { - out <- TRUE - } else { - out <- sprintf("`%s` must be an atomic vector.", name) - } - return(out) + if (isTRUE(null.ok) && is.null(x)) { + return(invisible(TRUE)) + } + # doesn't work on glue::glue() output + # flag <- is.atomic(x) && is.vector(x) && !is.list(x) + flag <- is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x) + if (flag) { + out <- TRUE + } else if (is.factor(x) && is.null(dim(x))) { + out <- TRUE + } else { + out <- sprintf("`%s` must be an atomic vector.", name) + } + return(out) } assert_class <- function(x, classname) { - if (!inherits(x, classname)) { - msg <- sprintf("`x` must be of class `%s`.", classname) - stop(msg, call. = FALSE) - } + if (!inherits(x, classname)) { + msg <- sprintf("`x` must be of class `%s`.", classname) + stop(msg, call. = FALSE) + } } sanitize_notes <- function(notes) { - if (is.character(notes) && length(notes) > 0) { - notes <- as.list(notes) - } - assert_list(notes, null.ok = TRUE) - for (idx in seq_along(notes)) { - n <- notes[[idx]] - bad <- FALSE - if (is.list(n)) { - if (is.null(names(notes)[idx])) { - bad <- TRUE - } - if (!all(c("i", "j", "text") %in% names(n))) { - bad <- TRUE - } - } else if (!is.character(n) || length(n) != 1) { - bad <- TRUE - } - if (isTRUE(bad)) { - stop("`notes` includes invalid elements. Please refer to the documentation for details.", call. = FALSE) - } - } - return(notes) + if (is.character(notes) && length(notes) > 0) { + notes <- as.list(notes) + } + assert_list(notes, null.ok = TRUE) + for (idx in seq_along(notes)) { + n <- notes[[idx]] + bad <- FALSE + if (is.list(n)) { + if (is.null(names(notes)[idx])) { + bad <- TRUE + } + if (!all(c("i", "j", "text") %in% names(n))) { + bad <- TRUE + } + } else if (!is.character(n) || length(n) != 1) { + bad <- TRUE + } + if (isTRUE(bad)) { + stop("`notes` includes invalid elements. Please refer to the documentation for details.", call. = FALSE) + } + } + return(notes) } sanitize_replace <- function(replace) { - if (isTRUE(replace)) { - replace <- stats::setNames(list(NA), "") - } else if (isFALSE(replace)) { - replace <- stats::setNames(list(NULL), "") - } else if (isTRUE(check_string(replace))) { - replace <- stats::setNames(list(NA), replace) - } else if (!is.list(replace) || is.null(names(replace))) { - stop("`replace` should be TRUE/FALSE, a single string, or a named list.", call. = FALSE) - } - return(replace) + if (isTRUE(replace)) { + replace <- stats::setNames(list(NA), "") + } else if (isFALSE(replace)) { + replace <- stats::setNames(list(NULL), "") + } else if (isTRUE(check_string(replace))) { + replace <- stats::setNames(list(NA), replace) + } else if (!is.list(replace) || is.null(names(replace))) { + stop("`replace` should be TRUE/FALSE, a single string, or a named list.", call. = FALSE) + } + return(replace) } sanity_num_mark <- function(digits, num_mark_big, num_mark_dec) { - if (is.null(digits)) { - if (num_mark_big != "") stop("`num_mark_big` requires a `digits` value.", call. = FALSE) - if (num_mark_dec != ".") stop("`num_mark_dec` requires a `digits` value.", call. = FALSE) - } + if (is.null(digits)) { + if (num_mark_big != "") stop("`num_mark_big` requires a `digits` value.", call. = FALSE) + if (num_mark_dec != ".") stop("`num_mark_dec` requires a `digits` value.", call. = FALSE) + } } diff --git a/R/save_tt.R b/R/save_tt.R index e68b5cb9..b11caee4 100644 --- a/R/save_tt.R +++ b/R/save_tt.R @@ -10,6 +10,9 @@ #' the images are included in the HTML as base64 encoded string instead of link to a local file. #' @param overwrite A logical value indicating whether to overwrite an existing file. #' @return A string with the table when `output` is a format, and the file path when `output` is a valid path. +#' @template dependencies +#' @template latex_preamble +#' @template global_options #' @export #' @examples #' library(tinytable) @@ -23,7 +26,7 @@ #' tt(mtcars[1:4, 1:4]) |> save_tt(filename) #' save_tt <- function(x, - output, + output, overwrite = get_option("tinytable_save_overwrite", default = FALSE)) { assert_class(x, "tinytable") assert_string(output) @@ -34,8 +37,8 @@ save_tt <- function(x, } if (isTRUE(getOption("tinytable_html_portable", default = FALSE))) { - assert_dependency("base64enc") - x@portable <- TRUE + assert_dependency("base64enc") + x@portable <- TRUE } if (identical(output, "html_portable")) { @@ -97,7 +100,8 @@ save_tt <- function(x, file = output, selector = "body > div > table", zoom = 4, - quiet = TRUE) + quiet = TRUE + ) unlink(tmp) } else if (file_ext == "pdf") { assert_dependency("tinytex") @@ -154,6 +158,7 @@ latex_standalone <- " \\usepackage{rotating} \\usepackage{float} \\usepackage[normalem]{ulem} +\\usepackage[x11names, svgnames]{xcolor} \\UseTblrLibrary{booktabs} \\UseTblrLibrary{siunitx} \\newcommand{\\tinytableTabularrayUnderline}[1]{\\underline{#1}} diff --git a/R/style_bootstrap.R b/R/style_bootstrap.R index fbd2b7b3..d93ef289 100644 --- a/R/style_bootstrap.R +++ b/R/style_bootstrap.R @@ -29,103 +29,104 @@ setMethod( bootstrap_css = NULL, bootstrap_css_rule = NULL, ...) { - - - if (length(x@bootstrap_css_rule) == 1) { - x@table_string <- bootstrap_setting(x@table_string, x@bootstrap_css_rule, component = "css") - } - - sty <- x@style - - sty$alignv[which(sty$alignv == "t")] <- "top" - sty$alignv[which(sty$alignv == "b")] <- "bottom" - sty$alignv[which(sty$alignv == "m")] <- "middle" - - sty$align[which(sty$align == "l")] <- "left" - sty$align[which(sty$align == "c")] <- "center" - sty$align[which(sty$align == "d")] <- "center" - sty$align[which(sty$align == "r")] <- "right" - - rec <- expand.grid( - i = c(-(seq_len(x@nhead) - 1), seq_len(x@nrow)), - j = seq_len(x@ncol) - ) - css <- rep("", nrow(rec)) - - for (row in seq_len(nrow(sty))) { - - # index: sty vs rec - idx_i <- sty$i[row] - if (is.na(idx_i)) idx_i <- unique(rec$i) - idx_j <- sty$j[row] - if (is.na(idx_j)) idx_j <- unique(rec$j) - idx <- rec$i == idx_i & rec$j == idx_j - - if (isTRUE(sty[row, "bold"])) css[idx] <- paste(css[idx], "font-weight: bold;") - if (isTRUE(sty[row, "italic"])) css[idx] <- paste(css[idx], "font-style: italic;") - if (isTRUE(sty[row, "underline"])) css[idx] <- paste(css[idx], "text-decoration: underline;") - if (isTRUE(sty[row, "strikeout"])) css[idx] <- paste(css[idx], "text-decoration: line-through;") - if (isTRUE(sty[row, "monospace"])) css[idx] <- paste(css[idx], "font-family: monospace;") - if (!is.na(sty[row, "color"])) css[idx] <- paste(css[idx], paste0("color: ", sty[row, "color"], ";")) - if (!is.na(sty[row, "background"])) css[idx] <- paste(css[idx], paste0("background-color: ", sty[row, "background"], ";")) - if (!is.na(sty[row, "fontsize"])) css[idx] <- paste(css[idx], paste0("font-size: ", sty[row, "fontsize"], "em;")) - if (!is.na(sty[row, "alignv"])) css[idx] <- paste(css[idx], paste0("vertical-align: ", sty[row, "alignv"], ";")) - if (!is.na(sty[row, "align"])) css[idx] <- paste(css[idx], paste0("text-align: ", sty[row, "align"], ";")) - if (!is.na(sty[row, "indent"])) css[idx] <- paste(css[idx], paste0("padding-left: ", sty[row, "indent"], "em;")) - if (!is.na(sty[row, "bootstrap_css"])) css[idx] <- paste(css[idx], sty[row, "bootstrap_css"]) - - lin <- "" - line <- sty$line[row] - line_width <- sty$line_width[row] - line_color <- sty$line_color[row] - line_color <- if (is.na(line_color)) "black" else line_color - line_width <- if (is.na(line_width)) 0.1 else line_width - left <- grepl("l", line) - right <- grepl("r",line) - top <- grepl("t", line) - bottom <- grepl("b", line) - if (all(c(left, right, top, bottom))) { - template <- "border: solid %s %sem;" - } else if (any(c(left, right, top, bottom))) { - template <- "border: solid %s %sem;" - if (left) template <- "border-left: solid %s %sem;" - if (right) template <- "border-right: solid %s %sem;" - if (top) template <- "border-top: solid %s %sem;" - if (bottom) template <- "border-bottom: solid %s %sem;" - } else { - template <- "" + if (length(x@bootstrap_css_rule) == 1) { + x@table_string <- bootstrap_setting(x@table_string, x@bootstrap_css_rule, component = "css") } - if (template != "") { - lin <- paste(lin, sprintf(template, line_color, line_width)) + + sty <- x@style + + + sty$alignv[which(sty$alignv == "t")] <- "top" + sty$alignv[which(sty$alignv == "b")] <- "bottom" + sty$alignv[which(sty$alignv == "m")] <- "middle" + + sty$align[which(sty$align == "l")] <- "left" + sty$align[which(sty$align == "c")] <- "center" + sty$align[which(sty$align == "d")] <- "center" + sty$align[which(sty$align == "r")] <- "right" + + rec <- expand.grid( + i = c(-(seq_len(x@nhead) - 1), seq_len(x@nrow)), + j = seq_len(x@ncol) + ) + css <- rep("", nrow(rec)) + + for (row in seq_len(nrow(sty))) { + # index: sty vs rec + idx_i <- sty$i[row] + if (is.na(idx_i)) idx_i <- unique(rec$i) + idx_j <- sty$j[row] + if (is.na(idx_j)) idx_j <- unique(rec$j) + idx <- rec$i == idx_i & rec$j == idx_j + + if (isTRUE(sty[row, "bold"])) css[idx] <- paste(css[idx], "font-weight: bold;") + if (isTRUE(sty[row, "italic"])) css[idx] <- paste(css[idx], "font-style: italic;") + if (isTRUE(sty[row, "underline"])) css[idx] <- paste(css[idx], "text-decoration: underline;") + if (isTRUE(sty[row, "strikeout"])) css[idx] <- paste(css[idx], "text-decoration: line-through;") + if (isTRUE(sty[row, "monospace"])) css[idx] <- paste(css[idx], "font-family: monospace;") + if (!is.na(sty[row, "color"])) css[idx] <- paste(css[idx], paste0("color: ", sty[row, "color"], ";")) + if (!is.na(sty[row, "background"])) css[idx] <- paste(css[idx], paste0("background-color: ", sty[row, "background"], ";")) + if (!is.na(sty[row, "fontsize"])) css[idx] <- paste(css[idx], paste0("font-size: ", sty[row, "fontsize"], "em;")) + if (!is.na(sty[row, "alignv"])) css[idx] <- paste(css[idx], paste0("vertical-align: ", sty[row, "alignv"], ";")) + if (!is.na(sty[row, "align"])) css[idx] <- paste(css[idx], paste0("text-align: ", sty[row, "align"], ";")) + if (!is.na(sty[row, "indent"])) css[idx] <- paste(css[idx], paste0("padding-left: ", sty[row, "indent"], "em;")) + if (!is.na(sty[row, "bootstrap_css"])) css[idx] <- paste(css[idx], sty[row, "bootstrap_css"]) + + lin <- "" + line <- sty$line[row] + line_width <- sty$line_width[row] + line_color <- sty$line_color[row] + line_color <- if (is.na(line_color)) "black" else line_color + line_width <- if (is.na(line_width)) 0.1 else line_width + left <- grepl("l", line) + right <- grepl("r", line) + top <- grepl("t", line) + bottom <- grepl("b", line) + if (all(c(left, right, top, bottom))) { + template <- "border: solid %s %sem;" + } else if (any(c(left, right, top, bottom))) { + template <- "border: solid %s %sem;" + if (left) template <- "border-left: solid %s %sem;" + if (right) template <- "border-right: solid %s %sem;" + if (top) template <- "border-top: solid %s %sem;" + if (bottom) template <- "border-bottom: solid %s %sem;" + } else { + template <- "" + } + if (template != "") { + lin <- paste(lin, sprintf(template, line_color, line_width)) + } + css[idx] <- paste(css[idx], lin) } - css[idx] <- paste(css[idx], lin) - } - css <- gsub(" +", " ", trimws(css)) + css <- gsub(" +", " ", trimws(css)) - # JS 0-indexing - rec$i <- rec$i - 1 + x@nhead - rec$j <- rec$j - 1 + # JS 0-indexing + rec$i <- rec$i - 1 + x@nhead + rec$j <- rec$j - 1 - # spans: before styles because we return(x) if there is no style - for (row in seq_len(nrow(sty))) { - rowspan <- if (!is.na(sty$rowspan[row])) sty$rowspan[row] else 1 - colspan <- if (!is.na(sty$colspan[row])) sty$colspan[row] else 1 - if (rowspan > 1 || colspan > 1) { - id <- get_id(stem = "spanCell_") - listener <- " window.addEventListener('load', function () { %s(%s, %s, %s, %s) })" - listener <- sprintf(listener, id, sty$i[row], sty$j[row] - 1, rowspan, colspan) - x@table_string <- lines_insert(x@table_string, listener, "tinytable span after", "after") - # x@table_string <- bootstrap_setting(x@table_string, listener, component = "cell") + # spans: before styles because we return(x) if there is no style + for (row in seq_len(nrow(sty))) { + rowspan <- if (!is.na(sty$rowspan[row])) sty$rowspan[row] else 1 + colspan <- if (!is.na(sty$colspan[row])) sty$colspan[row] else 1 + if (rowspan > 1 || colspan > 1) { + id <- get_id(stem = "spanCell_") + listener <- " window.addEventListener('load', function () { %s(%s, %s, %s, %s) })" + listener <- sprintf(listener, id, sty$i[row], sty$j[row] - 1, rowspan, colspan) + x@table_string <- lines_insert(x@table_string, listener, "tinytable span after", "after") + # x@table_string <- bootstrap_setting(x@table_string, listener, component = "cell") + } } - } - rec$css_arguments <- css - rec <- rec[rec$css_arguments != "", , drop = FALSE] - if (nrow(rec) == 0) return(x) - # rowspan + colspan delete cells + rec$css_arguments <- css + rec <- rec[rec$css_arguments != "", , drop = FALSE] + if (nrow(rec) == 0) { + return(x) + } + + # rowspan + colspan delete cells bad <- data.frame() idx <- which(!is.na(sty$i) & !is.na(sty$j) & (!is.na(sty$rowspan) | !is.na(sty$colspan))) idx <- sty[idx, c("i", "j", "rowspan", "colspan"), drop = FALSE] @@ -149,7 +150,6 @@ setMethod( rec <- rec[-which(rec$deleted == TRUE),] } - # Unique CSS arguments assigne by arrays css_table <- unique(rec[, c("css_arguments"), drop = FALSE]) css_table$id_css <- sapply(seq_len(nrow(css_table)), function(i) get_id(stem = "tinytable_css_")) @@ -167,7 +167,6 @@ setMethod( } } - return(x) -}) - - + return(x) + } +) diff --git a/R/style_grid.R b/R/style_grid.R index ab213ee2..97c8e9fa 100644 --- a/R/style_grid.R +++ b/R/style_grid.R @@ -1,10 +1,10 @@ style_eval_grid <- function(x) { - - out <- x@table_dataframe sty <- x@style - if (nrow(sty) == 0) return(x) + if (nrow(sty) == 0) { + return(x) + } all_i <- seq_len(nrow(x)) idx_g <- x@group_i_idx + cumsum(rep(1, length(x@group_i_idx))) - 1 @@ -15,13 +15,17 @@ style_eval_grid <- function(x) { alli <- data.frame(i = seq_len(nrow(x))) alli <- merge(alli, sty[is.na(sty$i), colnames(sty) != "i"], all = TRUE) sty <- rbind(sty, alli) - sty <- sty[!is.na(sty$i),] - sty <- sty[order(sty$i, sty$j),] + sty <- sty[!is.na(sty$i), ] + sty <- sty[order(sty$i, sty$j), ] } - + last <- function(k) { - if (all(is.na(k))) return(NA) - if (is.logical(k)) return(as.logical(max(k, na.rm = TRUE))) + if (all(is.na(k))) { + return(NA) + } + if (is.logical(k)) { + return(as.logical(max(k, na.rm = TRUE))) + } return(utils::tail(stats::na.omit(k), 1)) } sty <- do.call(rbind, by(sty, list(sty$i, sty$j), function(k) { @@ -29,12 +33,14 @@ style_eval_grid <- function(x) { })) # TODO: style groups - sty <- sty[which(!sty$i %in% idx_g),] + sty <- sty[which(!sty$i %in% idx_g), ] - if (nrow(sty) == 0) return(x) + if (nrow(sty) == 0) { + return(x) + } # user-supplied indices are post-groups - # adjust indices to match original data rows since we only operate on those + # adjust indices to match original data rows since we only operate on those for (g in rev(idx_g)) { sty[sty$i > g, "i"] <- sty[sty$i > g, "i"] - 1 } @@ -83,10 +89,10 @@ style_eval_grid <- function(x) { #' tinytable S4 method -#' +#' #' @keywords internal setMethod( - f = "style_eval", - signature = "tinytable_grid", - definition = style_eval_grid + f = "style_eval", + signature = "tinytable_grid", + definition = style_eval_grid ) diff --git a/R/style_grid_dataframe.R b/R/style_grid_dataframe.R index 7e59d869..03d336ce 100644 --- a/R/style_grid_dataframe.R +++ b/R/style_grid_dataframe.R @@ -1,25 +1,28 @@ #' tinytable S4 method -#' +#' #' @keywords internal -setMethod(f = "style_eval", - signature = "tinytable_dataframe", - definition = style_eval_grid +setMethod( + f = "style_eval", + signature = "tinytable_dataframe", + definition = style_eval_grid ) #' tinytable S4 method -#' +#' #' @keywords internal -setMethod(f = "group_eval", - signature = "tinytable_dataframe", - definition = identity +setMethod( + f = "group_eval", + signature = "tinytable_dataframe", + definition = identity ) #' tinytable S4 method -#' +#' #' @keywords internal -setMethod(f = "finalize", - signature = "tinytable_dataframe", - definition = identity +setMethod( + f = "finalize", + signature = "tinytable_dataframe", + definition = identity ) diff --git a/R/style_notes.R b/R/style_notes.R new file mode 100644 index 00000000..e69de29b diff --git a/R/style_string.R b/R/style_string.R new file mode 100644 index 00000000..4e009fc7 --- /dev/null +++ b/R/style_string.R @@ -0,0 +1,108 @@ +style_string_html <- function(n, styles) { + if (isTRUE(styles[["italic"]])) { + n <- sprintf("%s", n) + } + if (isTRUE(styles[["strikeout"]])) { + n <- sprintf("%s", n) + } + if (isTRUE(styles[["underline"]])) { + n <- sprintf("%s", n) + } + if (isTRUE(styles[["bold"]])) { + n <- sprintf("%s", n) + } + if (isTRUE(styles[["monospace"]])) { + n <- sprintf("%s", n) + } + if (!is.null(styles[["color"]])) { + n <- sprintf("%s", styles[["color"]], n) + } + if (!is.null(styles[["fontsize"]])) { + n <- sprintf("%s", styles[["fontsize"]], n) + } + n +} + + +style_string_latex <- function(n, styles) { + if (isTRUE(styles[["italic"]])) { + n <- sprintf("\\textit{%s}", n) + } + if (isTRUE(styles[["strikeout"]])) { + n <- sprintf("\\sout{%s}", n) + } + if (isTRUE(styles[["underline"]])) { + n <- sprintf("\\underline{%s}", n) + } + if (isTRUE(styles[["bold"]])) { + n <- sprintf("\\textbf{%s}", n) + } + if (isTRUE(styles[["monospace"]])) { + n <- sprintf("\\texttt{%s}", n) + } + if (!is.null(styles[["color"]])) { + n <- sprintf("\\textcolor{%s}{%s}", styles[["color"]], n) + } + if (!is.null(styles[["fontsize"]])) { + n <- sprintf("{\\fontsize{%sem}{%sem}\\selectfont %s}", styles[["fontsize"]], styles[["fontsize"]], n) + } + n +} + + +style_string_typst <- function(n, styles) { + sty <- NULL + if (isTRUE(styles[["italic"]])) { + sty <- c(sty, 'style: "italic"') + } + if (isTRUE(styles[["bold"]])) { + sty <- c(sty, 'weight: "bold"') + } + if (isTRUE(styles[["strikeout"]])) { + # not sure how to do this + } + if (isTRUE(styles[["underline"]])) { + # not sure how to do this + } + if (!is.null(styles[["fontsize"]])) { + fs <- sprintf("size: %sem", styles[["fontsize"]]) + sty <- c(sty, fs) + } + if (!is.null(styles[["color"]])) { + col <- styles[["color"]] + if (grepl("^#", col)) col <- sprintf('rgb("%s")', col) + col <- sprintf("fill: %s", col) + sty <- c(sty, col) + } + template <- paste0("text(", paste(sty, collapse = ", "), ", [%s])") + out <- sprintf(template, n) + out <- sub("text(, ", "text(", out, fixed = TRUE) + return(out) +} + + +style_notes <- function(x) { + fun <- switch(x@output, + "typst" = style_string_typst, + "html" = style_string_html, + "html_portable" = style_string_html, + "latex" = style_string_latex, + function(k, ...) identity(k) + ) + x@notes <- lapply(x@notes, fun, x@style_notes) + return(x) +} + +style_caption <- function(x) { + fun <- switch(x@output, + "typst" = style_string_typst, + "html" = style_string_html, + "html_portable" = style_string_html, + "latex" = style_string_latex, + function(k, ...) identity(k) + ) + if (length(x@caption) > 0) { + x@caption <- fun(x@caption, x@style_caption) + } + return(x) +} diff --git a/R/style_tabularray.R b/R/style_tabularray.R index d6ec2932..c3f14936 100644 --- a/R/style_tabularray.R +++ b/R/style_tabularray.R @@ -23,226 +23,239 @@ setMethod( tabularray_inner = NULL, tabularray_outer = NULL, ...) { - - sty <- x@style - sty$i <- sty$i + x@nhead - - rec <- expand.grid( - i = c(seq_len(x@nrow + x@nhead)), - j = seq_len(x@ncol), - line = NA, - line_color = NA, - line_width = NA - ) - - sty$alignv[which(sty$alignv == "b")] <- "f" - sty$alignv[which(sty$alignv == "t")] <- "h" - sty$alignv[which(sty$alignv == "m")] <- "m" - - for (spec in stats::na.omit(sty$tabularray_inner)) { - x@table_string <- tabularray_insert(x@table_string, content = spec, type = "inner") - } - - for (spec in stats::na.omit(sty$tabularray_outer)) { - x@table_string <- tabularray_insert(x@table_string, content = spec, type = "inner") - } - - set <- span <- rep("", nrow(rec)) - - for (row in seq_len(nrow(sty))) { - - # index: sty vs rec - idx_i <- sty$i[row] - if (is.na(idx_i)) idx_i <- unique(rec$i) - idx_j <- sty$j[row] - if (is.na(idx_j)) idx_j <- unique(rec$j) - idx <- rec$i == idx_i & rec$j == idx_j - - cmd <- "" - if (isTRUE(sty$bold[row])) cmd <- paste0(cmd, "\\bfseries") - if (isTRUE(sty$italic[row])) cmd <- paste0(cmd, "\\textit") - if (isTRUE(sty$underline[row])) cmd <- paste0(cmd, "\\tinytableTabularrayUnderline") - if (isTRUE(sty$strikeout[row])) cmd <- paste0(cmd, "\\tinytableTabularrayStrikeout") - if (isTRUE(sty$monospace[row])) cmd <- paste0(cmd, "\\texttt") - - col <- sty$color[row] - if (!is.na(col)) { - x <- color_to_preamble(x, col) - if (grepl("^#", col)) col <- sub("^#", "c", col) - cmd <- sprintf("%s, fg=%s", cmd, col) - } - - bg <- sty$background[row] - if (!is.na(bg)) { - x <- color_to_preamble(x, bg) - if (grepl("^#", bg)) bg <- sub("^#", "c", bg) - cmd <- sprintf("%s, bg=%s", cmd, bg) + sty <- x@style + sty$i <- sty$i + x@nhead + + rec <- expand.grid( + i = c(seq_len(x@nrow + x@nhead)), + j = seq_len(x@ncol), + line = NA, + line_color = NA, + line_width = NA + ) + + sty$alignv[which(sty$alignv == "b")] <- "f" + sty$alignv[which(sty$alignv == "t")] <- "h" + sty$alignv[which(sty$alignv == "m")] <- "m" + + set <- span <- rep("", nrow(rec)) + + # d-column are column-wise, so we treat them here + if (nrow(sty) > 0) { + dcol_j <- sty[grepl("^d$", sty[["align"]]), "j"] + dcol_j <- if (length(dcol_j) == 0) NULL else unique(dcol_j) + for (idx_j in dcol_j) { + spec <- get_dcolumn(idx_j, x) + spec <- sprintf("column{%s}={%s}\n", idx_j, spec) + x@table_string <- tabularray_insert(x@table_string, content = spec, type = "inner") + for (idx_i in seq_len(x@nhead)) { + spec <- paste(sprintf("cell{%s}{%s}={guard,halign=c,},", idx_i, idx_j), collapse = "\n") + x@table_string <- tabularray_insert(x@table_string, content = spec, type = "inner") + } + } } - if (grepl("^,", cmd)) { + for (row in seq_len(nrow(sty))) { + # index: sty vs rec + idx_i <- sty$i[row] + if (is.na(idx_i)) idx_i <- unique(rec$i) + idx_j <- sty$j[row] + if (is.na(idx_j)) idx_j <- unique(rec$j) + idx <- rec$i == idx_i & rec$j == idx_j + + cmd <- "" + if (isTRUE(sty$bold[row])) cmd <- paste0(cmd, "\\bfseries") + if (isTRUE(sty$italic[row])) cmd <- paste0(cmd, "\\textit") + if (isTRUE(sty$underline[row])) cmd <- paste0(cmd, "\\tinytableTabularrayUnderline") + if (isTRUE(sty$strikeout[row])) cmd <- paste0(cmd, "\\tinytableTabularrayStrikeout") + if (isTRUE(sty$monospace[row])) cmd <- paste0(cmd, "\\texttt") + + col <- sty$color[row] + if (!is.na(col)) { + x <- color_to_preamble(x, col) + if (grepl("^#", col)) col <- sub("^#", "c", col) + cmd <- sprintf("%s, fg=%s", cmd, col) + } + + bg <- sty$background[row] + if (!is.na(bg)) { + x <- color_to_preamble(x, bg) + if (grepl("^#", bg)) bg <- sub("^#", "c", bg) + cmd <- sprintf("%s, bg=%s", cmd, bg) + } + + if (grepl("^,", cmd)) { tmp <- "%s, %s, " - } else { + } else { tmp <- "%s, cmd=%s, " + } + if (trimws(cmd) != "") set[idx] <- sprintf(tmp, set[idx], cmd) + + fontsize <- sty$fontsize[row] + if (!is.na(as.numeric(fontsize))) { + set[idx] <- sprintf( + "%s font=\\fontsize{%sem}{%sem}\\selectfont,", + set[idx], fontsize, fontsize + 0.3 + ) + } + + halign <- sty$align[row] + if (!is.na(halign) && !grepl("d", halign)) { + set[idx] <- sprintf("%s, halign=%s,", set[idx], halign) + } + + alignv <- sty$alignv[row] + if (!is.na(alignv)) { + set[idx] <- sprintf("%s, valign=%s,", set[idx], alignv) + } + + indent <- sty$indent[row] + if (isTRUE(indent > 0)) { + set[idx] <- sprintf("%s preto={\\hspace{%sem}},", set[idx], indent) + } + + if (!is.na(sty$colspan[row])) { + span[idx] <- paste0(span[idx], "c=", sty$colspan[row], ",") + } + + if (!is.na(sty$rowspan[row])) { + span[idx] <- paste0(span[idx], "r=", sty$rowspan[row], ",") + } + + if (!is.na(sty$line[row])) { + rec$line[idx] <- sty$line[row] + } + + if (!is.na(sty$line_color[row])) { + rec$line_color[idx] <- sty$line_color[row] + } + + if (!is.na(sty$line_width[row])) { + rec$line_width[idx] <- sty$line_width[row] + } } - if (trimws(cmd) != "") set[idx] <- sprintf(tmp, set[idx], cmd) - fontsize <- sty$fontsize[row] - if (!is.na(as.numeric(fontsize))) { - set[idx] <- sprintf( - "%s font=\\fontsize{%sem}{%sem}\\selectfont,", - set[idx], fontsize, fontsize + 0.3) + clean <- function(k) { + k <- gsub("\\s*", "", k) + k <- gsub(",+", ",", k) + k <- gsub("^,", "", k, perl = TRUE) + k <- gsub(",", ", ", k) + k <- trimws(k) + return(k) } - halign <- sty$align[row] - if (!is.na(halign)) { - if (!identical(halign, "d")) { - set[idx] <- sprintf("%s, halign=%s,", set[idx], halign) - } else { - dcol <- get_dcolumn(rec[row, "j"], x) - set[idx] <- sprintf("%s, %s", set[idx], dcol) - } - } - - alignv <- sty$alignv[row] - if (!is.na(alignv)) { - set[idx] <- sprintf("%s, valign=%s,", set[idx], alignv) + rec$set <- clean(set) + rec$span <- clean(span) + + all_i <- seq_len(x@nrow + x@nhead) + all_j <- seq_len(x@ncol) + + # complete rows and columns + rec <- do.call(rbind, by(rec, list(rec$j, rec$set, rec$span), function(k) { + transform(k, complete_column = all(all_i %in% k$i)) + })) + rec <- do.call(rbind, by(rec, list(rec$i, rec$set, rec$span), function(k) { + transform(k, complete_row = all(all_j %in% k$j)) + })) + + idx <- rec$span != "" | rec$set != "" + + # complete columns (first because of d-column) + cols <- unique(rec[idx & rec$complete_column, c("j", "set", "span"), drop = FALSE]) + spec <- by(cols, list(cols$set, cols$span), function(k) { + sprintf("column{%s}={%s}{%s}", paste(k$j, collapse = ","), k$span, k$set) + }) + spec <- unique(as.vector(unlist(spec))) + for (s in spec) { + x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") } - indent <- sty$indent[row] - if (isTRUE(indent > 0)) { - set[idx] <- sprintf("%s preto={\\hspace{%sem}},", set[idx], indent) + # complete rows + rows <- unique(rec[ + idx & rec$complete_row & !rec$complete_column, + c("i", "set", "span"), + drop = FALSE + ]) + spec <- by(rows, list(rows$set, rows$span), function(k) { + sprintf("row{%s}={%s}{%s}", paste(k$i, collapse = ","), k$span, k$set) + }) + spec <- unique(as.vector(unlist(spec))) + for (s in spec) { + x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") } - if (!is.na(sty$colspan[row])) { - span[idx] <- paste0(span[idx], "c=", sty$colspan[row], ",") + # cells + cells <- unique(rec[idx & !rec$complete_row & !rec$complete_column, , drop = FALSE]) + spec <- sprintf("cell{%s}{%s}={%s}{%s}", cells$i, cells$j, cells$span, cells$set) + spec <- unique(as.vector(unlist(spec))) + for (s in spec) { + x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") } - if (!is.na(sty$rowspan[row])) { - span[idx] <- paste0(span[idx], "r=", sty$rowspan[row], ",") + # lines + rec$lin <- "solid, " + rec$lin <- ifelse(!is.na(rec$line_color), + paste0(rec$lin, rec$line_color), rec$lin + ) + rec$lin <- ifelse(!is.na(rec$line_width), + paste0(rec$lin, sprintf(", %sem", rec$line_width)), rec$lin + ) + rec$lin[is.na(rec$line)] <- NA + + # horizontal lines + horizontal <- rec[grepl("b|t", rec$line), c("i", "j", "lin", "line"), drop = FALSE] + horizontal <- rbind( + horizontal[grepl("t", horizontal$line), , drop = FALSE], + transform(horizontal[grepl("b", horizontal$line), , drop = FALSE], i = i + 1) + ) + spec <- by(horizontal, list(horizontal$i, horizontal$lin), function(k) { + jval <- paste(sort(unique(k$j)), collapse = ",") + sprintf("hline{%s}={%s}{%s}", k$i, jval, k$lin) + }) + spec <- unique(as.vector(unlist(spec))) + for (s in spec) { + x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") } - if (!is.na(sty$line[row])) { - rec$line[idx] <- sty$line[row] + # vertical lines + vertical <- rec[grepl("l|r", rec$line), c("i", "j", "lin", "line"), drop = FALSE] + vertical <- rbind( + vertical[grepl("l", vertical$line), , drop = FALSE], + transform(vertical[grepl("r", vertical$line), , drop = FALSE], j = j + 1) + ) + spec <- by(vertical, list(vertical$j, vertical$lin), function(k) { + ival <- paste(sort(unique(k$i)), collapse = ",") + sprintf("vline{%s}={%s}{%s}", k$j, ival, k$lin) + }) + spec <- unique(as.vector(unlist(spec))) + for (s in spec) { + x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") } - if (!is.na(sty$line_color[row])) { - rec$line_color[idx] <- sty$line_color[row] + for (spec in unique(stats::na.omit(sty$tabularray_inner))) { + x@table_string <- tabularray_insert(x@table_string, content = spec, type = "inner") } - if (!is.na(sty$line_width[row])) { - rec$line_width[idx] <- sty$line_width[row] + for (spec in unique(stats::na.omit(sty$tabularray_outer))) { + x@table_string <- tabularray_insert(x@table_string, content = spec, type = "inner") } - } - clean <- function(k) { - k <- gsub("\\s*", "", k) - k <- gsub(",+", ",", k) - k <- gsub("^,", "", k, perl = TRUE) - k <- gsub(",", ", ", k) - k <- trimws(k) - return(k) - } - rec$set <- clean(set) - rec$span <- clean(span) - - all_i <- seq_len(x@nrow + x@nhead) - all_j <- seq_len(x@ncol) - - # complete rows and columns - rec <- do.call(rbind, by(rec, list(rec$j, rec$set, rec$span), function(k) { - transform(k, complete_column = all(all_i %in% k$i)) - })) - rec <- do.call(rbind, by(rec, list(rec$i, rec$set, rec$span), function(k) { - transform(k, complete_row = all(all_j %in% k$j)) - })) - - idx <- rec$span != "" | rec$set != "" - - # complete columns (first because of d-column) - cols <- unique(rec[idx & rec$complete_column, c("j", "set", "span"), drop = FALSE]) - spec <- by(cols, list(cols$set, cols$span), function(k) { - sprintf("column{%s}={%s}{%s}", paste(k$j, collapse = ","), k$span, k$set) - }) - spec <- unique(as.vector(unlist(spec))) - for (s in spec) { - x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") + return(x) } - - # complete rows - rows <- unique(rec[ - idx & rec$complete_row & !rec$complete_column, - c("i", "set", "span"), - drop = FALSE]) - spec <- by(rows, list(rows$set, rows$span), function(k) { - sprintf("row{%s}={%s}{%s}", paste(k$i, collapse = ","), k$span, k$set) - }) - spec <- unique(as.vector(unlist(spec))) - for (s in spec) { - x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") - } - - # cells - cells <- unique(rec[idx & !rec$complete_row & !rec$complete_column, , drop = FALSE]) - spec <- sprintf("cell{%s}{%s}={%s}{%s}", cells$i, cells$j, cells$span, cells$set) - spec <- unique(as.vector(unlist(spec))) - for (s in spec) { - x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") - } - - # lines - rec$lin <- "solid, " - rec$lin <- ifelse(!is.na(rec$line_color), - paste0(rec$lin, rec$line_color), rec$lin) - rec$lin <- ifelse(!is.na(rec$line_width), - paste0(rec$lin, sprintf(", %sem", rec$line_width)), rec$lin) - rec$lin[is.na(rec$line)] <- NA - - # horizontal lines - horizontal <- rec[grepl("b|t", rec$line), c("i", "j", "lin", "line"), drop = FALSE] - horizontal <- rbind( - horizontal[grepl("t", horizontal$line),, drop = FALSE], - transform(horizontal[grepl("b", horizontal$line),, drop = FALSE], i = i + 1) - ) - spec <- by(horizontal, list(horizontal$i, horizontal$lin), function(k) { - jval <- paste(sort(unique(k$j)), collapse = ",") - sprintf("hline{%s}={%s}{%s}", k$i, jval, k$lin) - }) - spec <- unique(as.vector(unlist(spec))) - for (s in spec) { - x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") - } - - # vertical lines - vertical <- rec[grepl("l|r", rec$line), c("i", "j", "lin", "line"), drop = FALSE] - vertical <- rbind( - vertical[grepl("l", vertical$line),, drop = FALSE], - transform(vertical[grepl("r", vertical$line),, drop = FALSE], j = j + 1) - ) - spec <- by(vertical, list(vertical$j, vertical$lin), function(k) { - ival <- paste(sort(unique(k$i)), collapse = ",") - sprintf("vline{%s}={%s}{%s}", k$j, ival, k$lin) - }) - spec <- unique(as.vector(unlist(spec))) - for (s in spec) { - x@table_string <- tabularray_insert(x@table_string, content = s, type = "inner") - } - - return(x) - -}) +) tabularray_insert <- function(x, content = NULL, type = "body") { - out <- x out <- strsplit(out, "\n")[[1]] comment <- switch(type, - "body" = "% tabularray inner close", - "outer" = "% tabularray outer close", - "inner" = "% tabularray inner close") + "body" = "% tabularray inner close", + "outer" = "% tabularray outer close", + "inner" = "% tabularray inner close" + ) idx <- grep(comment, out) if (length(content) > 0) { @@ -278,17 +291,17 @@ color_to_preamble <- function(x, col) { get_dcolumn <- function(j, x) { - siunitx <- get_option("tinytable_siunitx_table_format", default = "table-format=-%s.%s,table-align-text-before=false,table-align-text-after=false,input-symbols={-,\\*+()}") - num <- unlist(x@table_dataframe[, j]) - num <- strsplit(num, "\\.") - num <- lapply(num, function(k) if (length(k) == 1) c(k, " ") else k) - left <- sapply(num, function(k) k[[1]]) - right <- sapply(num, function(k) k[[2]]) - left <- max(nchar(gsub("\\D", "", left))) - right <- max(nchar(gsub("\\D", "", right))) - out <- sprintf(siunitx, left, right) - out <- sprintf("si={%s},", out) - return(out) + siunitx <- get_option("tinytable_siunitx_table_format", default = "table-format=-%s.%s,table-align-text-before=false,table-align-text-after=false,input-symbols={-,\\*+()}") + num <- unlist(x@table_dataframe[, j]) + num <- strsplit(num, "\\.") + num <- lapply(num, function(k) if (length(k) == 1) c(k, " ") else k) + left <- sapply(num, function(k) k[[1]]) + right <- sapply(num, function(k) k[[2]]) + left <- max(nchar(gsub("\\D", "", left))) + right <- max(nchar(gsub("\\D", "", right))) + out <- sprintf(siunitx, left, right) + out <- sprintf("si={%s},", out) + return(out) } diff --git a/R/style_tt.R b/R/style_tt.R index 23adc45d..4cec207d 100644 --- a/R/style_tt.R +++ b/R/style_tt.R @@ -3,14 +3,15 @@ #' @details #' This function applies styling to a table created by `tt()`. It allows customization of text style (bold, italic, monospace), text and background colors, font size, cell width, text alignment, column span, and indentation. The function also supports passing native instructions to LaTeX (tabularray) and HTML (bootstrap) formats. #' -#' Note: Markdown and Word tables only support these styles: italic, bold, strikeout. Moreover, the `style_tt()` function cannot be used to style headers inserted by the `group_tt()` function; instead, you should style the headers directly in the header definition using markdown syntax: `group_tt(i = list("*italic header*" = 2))`. These limitations are due to the fact that there is no markdown syntax for the other options, and that we create Word documents by converting a markdown table to .docx via the Pandoc software. -#' #' @param x A table object created by `tt()`. -#' @param i Row indices where the styling should be applied. Can be a single value, a vector, or a logical matrix with the same number of rows and columns as `x`. `i=0` is the header, and negative values are higher level headers. Row indices refer to rows *after* the insertion of row labels by `group_tt()`, when applicable. +#' @param i Numeric vector, logical matrix, or string.. +#' - Numeric vector: Row indices where the styling should be applied. Can be a single value or a vector. +#' - Logical matrix: A matrix with the same number of rows and columns as `x`. `i=0` is the header, and negative values are higher level headers. Row indices refer to rows *after* the insertion of row labels by `group_tt()`, when applicable. +#' - String: "notes" or "caption". #' @param j Column indices where the styling should be applied. Can be: #' + Integer vectors indicating column positions. #' + Character vector indicating column names. -#' + A single string specifying a Perl-style regular expression used to match column names. +#' + A single string specifying a Perl-style regular expression used to match column names. #' @param bold Logical; if `TRUE`, text is styled in bold. #' @param italic Logical; if `TRUE`, text is styled in italic. #' @param monospace Logical; if `TRUE`, text is styled in monospace font. @@ -24,7 +25,7 @@ #' - Hex code composed of # and 6 characters, ex: "#CC79A7". See the section below for instructions to add in LaTeX preambles. #' - Keywords: black, blue, brown, cyan, darkgray, gray, green, lightgray, lime, magenta, olive, orange, pink, purple, red, teal, violet, white, yellow. #' - Color blending using xcolor`, ex: `white!80!blue`, `green!20!red`. -#' - Color names with luminance levels from [the `ninecolors` package](https://mirror.quantum5.ca/CTAN/macros/latex/contrib/ninecolors/ninecolors.pdf) (ex: "azure4", "magenta8", "teal2", "gray1", "olive3"). +#' - Color names with luminance levels from [the `ninecolors` package](https://mirror.quantum5.ca/CTAN/macros/latex/contrib/ninecolors/ninecolors.pdf) (ex: "azure4", "magenta8", "teal2", "gray1", "olive3"). #' @param background Background color. Specified as a color name or hexadecimal code. Can be `NULL` for default color. #' @param fontsize Font size in em units. Can be `NULL` for default size. #' @param align A single character or a string with a number of characters equal to the number of columns in `j`. Valid characters include 'c' (center), 'l' (left), 'r' (right), 'd' (decimal). Decimal alignment is only available in LaTeX via the `siunitx` package. The width of columns is determined by the maximum number of digits to the left and to the right in all cells specified by `i` and `j`. @@ -32,7 +33,7 @@ #' @param colspan Number of columns a cell should span. `i` and `j` must be of length 1. #' @param rowspan Number of rows a cell should span. `i` and `j` must be of length 1. #' @param indent Text indentation in em units. Positive values only. -#' @param line String determines if solid lines (rules or borders) should be drawn around the cell, row, or column. +#' @param line String determines if solid lines (rules or borders) should be drawn around the cell, row, or column. #' + "t": top #' + "b": bottom #' + "l": left @@ -41,39 +42,39 @@ #' @param line_color Color of the line. See the `color` argument for details. #' @param line_width Width of the line in em units (default: 0.1). #' @param finalize A function applied to the table object at the very end of table-building, for post-processing. For example, the function could use regular expressions to add LaTeX commands to the text version of the table hosted in `x@table_string`, or it could programmatically change the caption in `x@caption`. -#' @param bootstrap_css Character vector. CSS style declarations to be applied to every cell defined by `i` and `j` (ex: `"font-weight: bold"`). -#' @param bootstrap_class String. Bootstrap table class such as `"table"`, `"table table-dark"` or `"table table-dark table-hover"`. See the bootstrap documentation. +#' @param bootstrap_css Character vector. CSS style declarations to be applied to every cell defined by `i` and `j` (ex: `"font-weight: bold"`). +#' @param bootstrap_class String. Bootstrap table class such as `"table"`, `"table table-dark"` or `"table table-dark table-hover"`. See the bootstrap documentation. #' @param bootstrap_css_rule String. Complete CSS rules (with curly braces, semicolon, etc.) that apply to the table class specified by the `bootstrap_class` argument. -#' @param tabularray_inner A string that specifies the "inner" settings of a tabularray LaTeX table. +#' @param tabularray_inner A string that specifies the "inner" settings of a tabularray LaTeX table. #' @param tabularray_outer A string that specifies the "outer" settings of a tabularray LaTeX table. -#' @param output Apply style only to the output format specified by this argument. `NULL` means that we apply to all formats. +#' @param output Apply style only to the output format specified by this argument. `NULL` means that we apply to all formats. #' @param ... extra arguments are ignored #' @return An object of class `tt` representing the table. -#' @template latex_preamble +#' @template limitations_word_markdown #' @export #' @examplesIf knitr::is_html_output() #' @examples #' if (knitr::is_html_output()) options(tinytable_print_output = "html") -#' +#' #' library(tinytable) -#' +#' #' tt(mtcars[1:5, 1:6]) -#' +#' #' # Alignment -#' tt(mtcars[1:5, 1:6]) |> +#' tt(mtcars[1:5, 1:6]) |> #' style_tt(j = 1:5, align = "lcccr") -#' +#' #' # Colors and styles -#' tt(mtcars[1:5, 1:6]) |> +#' tt(mtcars[1:5, 1:6]) |> #' style_tt(i = 2:3, background = "black", color = "orange", bold = TRUE) -#' +#' #' # column selection with `j`` -#' tt(mtcars[1:5, 1:6]) |> +#' tt(mtcars[1:5, 1:6]) |> #' style_tt(j = 5:6, background = "pink") -#' +#' #' tt(mtcars[1:5, 1:6]) |> #' style_tt(j = "drat|wt", background = "pink") -#' +#' #' tt(mtcars[1:5, 1:6]) |> #' style_tt(j = c("drat", "wt"), background = "pink") #' @@ -82,27 +83,27 @@ #' i = 2, j = 2, #' colspan = 3, #' rowspan = 2, -#' align="c", +#' align = "c", #' alignv = "m", #' color = "white", #' background = "black", #' bold = TRUE) -#' +#' #' tt(mtcars[1:5, 1:6], theme = "void") |> #' style_tt( -#' i=0:3, -#' j=1:3, -#' line="tblr", -#' line_width=0.4, -#' line_color="teal") -#' +#' i = 0:3, +#' j = 1:3, +#' line = "tblr", +#' line_width = 0.4, +#' line_color = "teal") +#' #' tt(mtcars[1:5, 1:6], theme = "bootstrap") |> -#' style_tt( -#' i = c(2,5), -#' j = 3, -#' strikeout = TRUE, -#' fontsize = 0.7) -#' +#' style_tt( +#' i = c(2, 5), +#' j = 3, +#' strikeout = TRUE, +#' fontsize = 0.7) +#' #' tt(mtcars[1:5, 1:6]) |> #' style_tt(bootstrap_class = "table table-dark table-hover") #' @@ -120,252 +121,261 @@ #' tt(mtcars[1:5, 1:4], theme = "void") |> #' style_tt(tabularray_inner = inner) #' -style_tt <- function (x, - i = NULL, - j = NULL, - bold = FALSE, - italic = FALSE, - monospace = FALSE, - underline = FALSE, - strikeout = FALSE, - color = NULL, - background = NULL, - fontsize = NULL, - align = NULL, - alignv = NULL, - colspan = NULL, - rowspan = NULL, - indent = NULL, - line = NULL, - line_color = "black", - line_width = 0.1, - finalize = NULL, - tabularray_inner = NULL, - tabularray_outer = NULL, - bootstrap_class = NULL, - bootstrap_css = NULL, - bootstrap_css_rule = NULL, - output = NULL, - ...) { +style_tt <- function(x, + i = NULL, + j = NULL, + bold = FALSE, + italic = FALSE, + monospace = FALSE, + underline = FALSE, + strikeout = FALSE, + color = NULL, + background = NULL, + fontsize = NULL, + align = NULL, + alignv = NULL, + colspan = NULL, + rowspan = NULL, + indent = NULL, + line = NULL, + line_color = "black", + line_width = 0.1, + finalize = NULL, + tabularray_inner = NULL, + tabularray_outer = NULL, + bootstrap_class = NULL, + bootstrap_css = NULL, + bootstrap_css_rule = NULL, + output = NULL, + ...) { + out <- x - out <- x + assert_choice(alignv, c("t", "m", "b"), null.ok = TRUE) - assert_choice(alignv, c("t", "m", "b"), null.ok = TRUE) - - assert_style_tt( - x = out, i = i, j = j, bold = bold, italic = italic, monospace = monospace, underline = underline, strikeout = strikeout, - color = color, background = background, fontsize = fontsize, align = align, - colspan = colspan, rowspan = rowspan, indent = indent, - line = line, line_color = line_color, line_width = line_width, - tabularray_inner = tabularray_inner, tabularray_outer = tabularray_outer, bootstrap_css = bootstrap_css, - bootstrap_css_rule = bootstrap_css_rule) + assert_style_tt( + x = out, i = i, j = j, bold = bold, italic = italic, monospace = monospace, underline = underline, strikeout = strikeout, + color = color, background = background, fontsize = fontsize, align = align, + colspan = colspan, rowspan = rowspan, indent = indent, + line = line, line_color = line_color, line_width = line_width, + tabularray_inner = tabularray_inner, tabularray_outer = tabularray_outer, bootstrap_css = bootstrap_css, + bootstrap_css_rule = bootstrap_css_rule) + if (isTRUE(i %in% c("notes", "caption"))) { + tmp <- list( + color = color, + fontsize = fontsize, + italic = italic, + monospace = monospace, + strikeout = strikeout, + underline = underline + ) + if (identical(i, "notes")) out@style_notes <- tmp + if (identical(i, "caption")) out@style_caption <- tmp + return(out) + } - if (!is.null(bootstrap_class)) { - out@bootstrap_class <- bootstrap_class - } - if (!is.null(bootstrap_css_rule)) { - out@bootstrap_css_rule <- bootstrap_css_rule - } + if (!is.null(bootstrap_class)) { + out@bootstrap_class <- bootstrap_class + } + if (!is.null(bootstrap_css_rule)) { + out@bootstrap_css_rule <- bootstrap_css_rule + } - sanity_align(align, i) + sanity_align(align, i) - assert_choice(output, c("typst", "latex", "html", "markdown", "gfm"), null.ok = TRUE) + assert_choice(output, c("typst", "latex", "html", "markdown", "gfm"), null.ok = TRUE) - if ("width" %in% names(list(...))) { - stop("The `width` argument is now in the `tt()` function.", call. = FALSE) - } + if ("width" %in% names(list(...))) { + stop("The `width` argument is now in the `tt()` function.", call. = FALSE) + } - # i is a logical matrix mask - if (is.matrix(i) && is.logical(i) && nrow(i) == nrow(x) && ncol(i) == ncol(x)) { - assert_null(j) - settings <- which(i == TRUE, arr.ind = TRUE) - settings <- stats::setNames(data.frame(settings), c("i", "j")) - } else { - ival <- sanitize_i(i, x) - jval <- sanitize_j(j, x) - # order may be important for recycling - settings <- expand.grid(i = ival, j = jval, tabularray = "") - if (is.null(i) && !is.null(j)) { - settings <- settings[order(settings$i, settings$j), ] - } + # i is a logical matrix mask + if (is.matrix(i) && is.logical(i) && nrow(i) == nrow(x) && ncol(i) == ncol(x)) { + assert_null(j) + settings <- which(i == TRUE, arr.ind = TRUE) + settings <- stats::setNames(data.frame(settings), c("i", "j")) + } else { + ival <- sanitize_i(i, x) + jval <- sanitize_j(j, x) + # order may be important for recycling + settings <- expand.grid(i = ival, j = jval, tabularray = "") + if (is.null(i) && !is.null(j)) { + settings <- settings[order(settings$i, settings$j), ] } + } - settings[["color"]] <- if (is.null(color)) NA else as.vector(color) - settings[["background"]] <- if (is.null(background)) NA else as.vector(background) - settings[["fontsize"]] <- if (is.null(fontsize)) NA else as.vector(fontsize) - settings[["alignv"]] <- if (is.null(alignv)) NA else alignv - settings[["line"]] <- if (is.null(line)) NA else line - settings[["line_color"]] <- if (is.null(line)) NA else line_color - settings[["line_width"]] <- if (is.null(line)) NA else line_width - settings[["bold"]] <- bold - settings[["italic"]] <- italic - settings[["monospace"]] <- monospace - settings[["strikeout"]] <- strikeout - settings[["underline"]] <- underline - settings[["indent"]] <- if (is.null(indent)) NA else as.vector(indent) - settings[["colspan"]] <- if (is.null(colspan)) NA else colspan - settings[["rowspan"]] <- if (is.null(rowspan)) NA else rowspan - settings[["bootstrap_css_rule"]] <- if (!is.null(bootstrap_css_rule)) bootstrap_css_rule else NA - settings[["bootstrap_css"]] <- if (!is.null(bootstrap_css)) bootstrap_css else NA - settings[["tabularray_inner"]] <- if (!is.null(tabularray_inner)) tabularray_inner else NA - settings[["tabularray_outer"]] <- if (!is.null(tabularray_outer)) tabularray_outer else NA + settings[["color"]] <- if (is.null(color)) NA else as.vector(color) + settings[["background"]] <- if (is.null(background)) NA else as.vector(background) + settings[["fontsize"]] <- if (is.null(fontsize)) NA else as.vector(fontsize) + settings[["alignv"]] <- if (is.null(alignv)) NA else alignv + settings[["line"]] <- if (is.null(line)) NA else line + settings[["line_color"]] <- if (is.null(line)) NA else line_color + settings[["line_width"]] <- if (is.null(line)) NA else line_width + settings[["bold"]] <- bold + settings[["italic"]] <- italic + settings[["monospace"]] <- monospace + settings[["strikeout"]] <- strikeout + settings[["underline"]] <- underline + settings[["indent"]] <- if (is.null(indent)) NA else as.vector(indent) + settings[["colspan"]] <- if (is.null(colspan)) NA else colspan + settings[["rowspan"]] <- if (is.null(rowspan)) NA else rowspan + settings[["bootstrap_css_rule"]] <- if (!is.null(bootstrap_css_rule)) bootstrap_css_rule else NA + settings[["bootstrap_css"]] <- if (!is.null(bootstrap_css)) bootstrap_css else NA + settings[["tabularray_inner"]] <- if (!is.null(tabularray_inner)) tabularray_inner else NA + settings[["tabularray_outer"]] <- if (!is.null(tabularray_outer)) tabularray_outer else NA - if (!is.null(align)) { - if (nchar(align) == length(jval)) { - align_string <- strsplit(align, "")[[1]] - if (!all(align_string %in% c("c", "l", "r", "d"))) { - msg <- "`align` must be characters c, l, r, or d." - stop(msg, call. = FALSE) - } - align_string <- data.frame(j = jval, align = align_string) - settings <- merge(settings, align_string, by = "j", all.x = TRUE) - } else if (nchar(align) == 1) { - assert_choice(align, c("c", "l", "r", "d")) - align_string <- data.frame(j = jval, align = align) - settings <- merge(settings, align_string, by = "j", all.x = TRUE) - } else { - msg <- sprintf("`align` must be a single character or a string of length %s.", length(jval)) - stop(msg, call. = FALSE) - } + if (!is.null(align)) { + if (nchar(align) == length(jval)) { + align_string <- strsplit(align, "")[[1]] + if (!all(align_string %in% c("c", "l", "r", "d"))) { + msg <- "`align` must be characters c, l, r, or d." + stop(msg, call. = FALSE) + } + align_string <- data.frame(j = jval, align = align_string) + settings <- merge(settings, align_string, by = "j", all.x = TRUE) + } else if (nchar(align) == 1) { + assert_choice(align, c("c", "l", "r", "d")) + align_string <- data.frame(j = jval, align = align) + settings <- merge(settings, align_string, by = "j", all.x = TRUE) } else { - settings[["align"]] <- NA + msg <- sprintf("`align` must be a single character or a string of length %s.", length(jval)) + stop(msg, call. = FALSE) } + } else { + settings[["align"]] <- NA + } - empty <- settings[, 4:ncol(settings)] - empty <- sapply(empty, function(x) is.na(x) | (is.logical(x) && !any(x))) - if (nrow(settings) == 1) { - empty <- all(empty) - settings <- settings[!empty, , drop = FALSE] - } else { - empty <- apply(empty, 1, all) - settings <- settings[!empty, , drop = FALSE] - } + empty <- settings[, 4:ncol(settings)] + empty <- sapply(empty, function(x) is.na(x) | (is.logical(x) && !any(x))) + if (nrow(settings) == 1) { + empty <- all(empty) + settings <- settings[!empty, , drop = FALSE] + } else { + empty <- apply(empty, 1, all) + settings <- settings[!empty, , drop = FALSE] + } - if (nrow(out@style) > 0 && nrow(settings) > 0 && ncol(out@style) != ncol(settings)) { - a <- out@style - b <- settings - if (!"tabularray" %in% colnames(a)) a$tabularray <- "" - if (!"tabularray" %in% colnames(b)) b$tabularray <- "" - settings <- rbind(a, b[, colnames(a)]) - out@style <- unique(settings) - } else if (nrow(settings) > 0) { - out@style <- rbind(out@style, settings) - } + if (nrow(out@style) > 0 && nrow(settings) > 0 && ncol(out@style) != ncol(settings)) { + a <- out@style + b <- settings + if (!"tabularray" %in% colnames(a)) a$tabularray <- "" + if (!"tabularray" %in% colnames(b)) b$tabularray <- "" + settings <- rbind(a, b[, colnames(a)]) + out@style <- unique(settings) + } else if (nrow(settings) > 0) { + out@style <- rbind(out@style, settings) + } - ## issue #759: reuse object with different styles across RevealJS slides requires new ID every time style_tt is called - # This is a very bad idea. Breaks a ton of things. We need unique IDs. - # out@id <- get_id("tinytable_") + ## issue #759: reuse object with different styles across RevealJS slides requires new ID every time style_tt is called + # This is a very bad idea. Breaks a ton of things. We need unique IDs. + # out@id <- get_id("tinytable_") - assert_function(finalize, null.ok = TRUE) - if (is.function(finalize)) { - out@lazy_finalize <- c(out@lazy_finalize, list(finalize)) - } + assert_function(finalize, null.ok = TRUE) + if (is.function(finalize)) { + out@lazy_finalize <- c(out@lazy_finalize, list(finalize)) + } - return(out) + return(out) } -assert_style_tt <- function (x, - i, - j, - bold, - italic, - monospace, - underline, - strikeout, - color, - background, - fontsize, - align, - colspan, - rowspan, - indent, - line, - line_color, - line_width, - tabularray_inner, - tabularray_outer, - bootstrap_class = NULL, - bootstrap_css = NULL, - bootstrap_css_rule = NULL) { +assert_style_tt <- function(x, + i, + j, + bold, + italic, + monospace, + underline, + strikeout, + color, + background, + fontsize, + align, + colspan, + rowspan, + indent, + line, + line_color, + line_width, + tabularray_inner, + tabularray_outer, + bootstrap_class = NULL, + bootstrap_css = NULL, + bootstrap_css_rule = NULL) { + assert_integerish(colspan, len = 1, lower = 2, null.ok = TRUE) + assert_integerish(rowspan, len = 1, lower = 2, null.ok = TRUE) + assert_numeric(indent, len = 1, lower = 0, null.ok = TRUE) + assert_character(background, null.ok = TRUE) + assert_character(color, null.ok = TRUE) + assert_numeric(fontsize, null.ok = TRUE) + assert_logical(bold) + assert_logical(italic) + assert_logical(monospace) + assert_logical(underline) + assert_logical(strikeout) + assert_string(line, null.ok = TRUE) + assert_string(line_color, null.ok = FALSE) # black default + assert_numeric(line_width, len = 1, lower = 0, null.ok = FALSE) # 0.1 default + assert_character(bootstrap_class, null.ok = TRUE) + assert_character(bootstrap_css, null.ok = TRUE) + assert_string(bootstrap_css_rule, null.ok = TRUE) - assert_integerish(colspan, len = 1, lower = 2, null.ok = TRUE) - assert_integerish(rowspan, len = 1, lower = 2, null.ok = TRUE) - assert_numeric(indent, len = 1, lower = 0, null.ok = TRUE) - assert_character(background, null.ok = TRUE) - assert_character(color, null.ok = TRUE) - assert_numeric(fontsize, null.ok = TRUE) - assert_logical(bold) - assert_logical(italic) - assert_logical(monospace) - assert_logical(underline) - assert_logical(strikeout) - assert_string(line, null.ok = TRUE) - assert_string(line_color, null.ok = FALSE) # black default - assert_numeric(line_width, len = 1, lower = 0, null.ok = FALSE) # 0.1 default - assert_character(bootstrap_class, null.ok = TRUE) - assert_character(bootstrap_css, null.ok = TRUE) - assert_string(bootstrap_css_rule, null.ok = TRUE) - - if (is.character(line)) { - line <- strsplit(line, split = "")[[1]] - if (!all(line %in% c("t", "b", "l", "r"))) { - msg <- "`line` must be a string of characters t, b, l, or r." - stop(msg, call. = FALSE) - } + if (is.character(line)) { + line <- strsplit(line, split = "")[[1]] + if (!all(line %in% c("t", "b", "l", "r"))) { + msg <- "`line` must be a string of characters t, b, l, or r." + stop(msg, call. = FALSE) } + } - ival <- sanitize_i(i, x) - jval <- sanitize_j(j, x) - inull <- isTRUE(attr(ival, "null")) - jnull <- isTRUE(attr(jval, "null")) + ival <- sanitize_i(i, x) + jval <- sanitize_j(j, x) + inull <- isTRUE(attr(ival, "null")) + jnull <- isTRUE(attr(jval, "null")) - # 1 - if (inull && jnull) { - assert_length(color, len = 1, null.ok = TRUE) - assert_length(background, len = 1, null.ok = TRUE) - assert_length(fontsize, len = 1, null.ok = TRUE) - assert_length(bold, len = 1) - assert_length(italic, len = 1) - assert_length(monospace, len = 1) - assert_length(underline, len = 1) - assert_length(strikeout, len = 1) + # 1 + if (inull && jnull) { + assert_length(color, len = 1, null.ok = TRUE) + assert_length(background, len = 1, null.ok = TRUE) + assert_length(fontsize, len = 1, null.ok = TRUE) + assert_length(bold, len = 1) + assert_length(italic, len = 1) + assert_length(monospace, len = 1) + assert_length(underline, len = 1) + assert_length(strikeout, len = 1) # 1 or #rows - } else if (!inull && jnull) { - assert_length(color, len = c(1, length(ival)), null.ok = TRUE) - assert_length(background, len = c(1, length(ival)), null.ok = TRUE) - assert_length(fontsize, len = c(1, length(ival)), null.ok = TRUE) - assert_length(bold, len = c(1, length(ival))) - assert_length(italic, len = c(1, length(ival))) - assert_length(monospace, len = c(1, length(ival))) - assert_length(underline, len = c(1, length(ival))) - assert_length(strikeout, len = c(1, length(ival))) + } else if (!inull && jnull) { + assert_length(color, len = c(1, length(ival)), null.ok = TRUE) + assert_length(background, len = c(1, length(ival)), null.ok = TRUE) + assert_length(fontsize, len = c(1, length(ival)), null.ok = TRUE) + assert_length(bold, len = c(1, length(ival))) + assert_length(italic, len = c(1, length(ival))) + assert_length(monospace, len = c(1, length(ival))) + assert_length(underline, len = c(1, length(ival))) + assert_length(strikeout, len = c(1, length(ival))) # 1 or #cols - } else if (inull && !jnull) { - assert_length(color, len = c(1, length(jval)), null.ok = TRUE) - assert_length(background, len = c(1, length(jval)), null.ok = TRUE) - assert_length(fontsize, len = c(1, length(jval)), null.ok = TRUE) - assert_length(bold, len = c(1, length(jval))) - assert_length(italic, len = c(1, length(jval))) - assert_length(monospace, len = c(1, length(jval))) - assert_length(underline, len = c(1, length(jval))) - assert_length(strikeout, len = c(1, length(jval))) + } else if (inull && !jnull) { + assert_length(color, len = c(1, length(jval)), null.ok = TRUE) + assert_length(background, len = c(1, length(jval)), null.ok = TRUE) + assert_length(fontsize, len = c(1, length(jval)), null.ok = TRUE) + assert_length(bold, len = c(1, length(jval))) + assert_length(italic, len = c(1, length(jval))) + assert_length(monospace, len = c(1, length(jval))) + assert_length(underline, len = c(1, length(jval))) + assert_length(strikeout, len = c(1, length(jval))) # 1 or #cells - } else if (!inull && !jnull) { - assert_length(color, len = c(1, length(ival) * length(jval)), null.ok = TRUE) - assert_length(background, len = c(1, length(ival) * length(jval)), null.ok = TRUE) - assert_length(fontsize, len = c(1, length(ival) * length(jval)), null.ok = TRUE) - assert_length(bold, len = c(1, length(ival) * length(jval))) - assert_length(italic, len = c(1, length(ival) * length(jval))) - assert_length(monospace, len = c(1, length(ival) * length(jval))) - assert_length(underline, len = c(1, length(ival) * length(jval))) - assert_length(strikeout, len = c(1, length(ival) * length(jval))) - } + } else if (!inull && !jnull) { + assert_length(color, len = c(1, length(ival) * length(jval)), null.ok = TRUE) + assert_length(background, len = c(1, length(ival) * length(jval)), null.ok = TRUE) + assert_length(fontsize, len = c(1, length(ival) * length(jval)), null.ok = TRUE) + assert_length(bold, len = c(1, length(ival) * length(jval))) + assert_length(italic, len = c(1, length(ival) * length(jval))) + assert_length(monospace, len = c(1, length(ival) * length(jval))) + assert_length(underline, len = c(1, length(ival) * length(jval))) + assert_length(strikeout, len = c(1, length(ival) * length(jval))) + } } - - diff --git a/R/style_typst.R b/R/style_typst.R index 941b6f83..6fd24350 100644 --- a/R/style_typst.R +++ b/R/style_typst.R @@ -25,13 +25,11 @@ setMethod( indent = 0, midrule = FALSE, # undocumented, only used by `group_tt()` ...) { - - sty <- x@style # gutters are used for group_tt(j) but look ugly with cell fill if (!all(is.na(sty$background))) { - x@table_string <- lines_drop(x@table_string, "column-gutter:", fixed = TRUE) + x@table_string <- lines_drop(x@table_string, "column-gutter:", fixed = TRUE) } sty$align[which(sty$align == "l")] <- "left" @@ -44,54 +42,55 @@ setMethod( if (length(x@names) == 0) sty$i <- sty$i + 1 rec <- expand.grid( - i = seq_len(x@nhead + x@nrow + x@ngroupi) - 1, - j = seq_len(x@ncol) - 1 + i = seq_len(x@nhead + x@nrow) - 1, + j = seq_len(x@ncol) - 1 ) css <- rep("", nrow(rec)) insert_field <- function(x, name = "bold", value = "true") { - old <- sprintf("%s: [^,]*,", name) - new <- sprintf("%s: %s,", name, value) - out <- ifelse(grepl(old, x), - sub(old, new, x), - sprintf("%s, %s", x, new)) - return(out) + old <- sprintf("%s: [^,]*,", name) + new <- sprintf("%s: %s,", name, value) + out <- ifelse(grepl(old, x), + sub(old, new, x), + sprintf("%s, %s", x, new) + ) + return(out) } for (row in seq_len(nrow(sty))) { - idx_i <- sty$i[row] - if (is.na(idx_i)) idx_i <- unique(rec$i) - idx_j <- sty$j[row] - if (is.na(idx_j)) idx_j <- unique(rec$j) - idx <- rec$i == idx_i & rec$j == idx_j - if (isTRUE(sty[row, "bold"])) css[idx] <- insert_field(css[idx], "bold", "true") - if (isTRUE(sty[row, "italic"])) css[idx] <- insert_field(css[idx], "italic", "true") - if (isTRUE(sty[row, "underline"])) css[idx] <- insert_field(css[idx], "underline", "true") - if (isTRUE(sty[row, "strikeout"])) css[idx] <- insert_field(css[idx], "strikeout", "true") - if (isTRUE(sty[row, "monospace"])) css[idx] <- insert_field(css[idx], "monospace", "true") - if (!is.na(sty[row, "align"])) css[idx] <- insert_field(css[idx], "align", sty[row, "align"]) - - fs <- sty[row, "indent"] - if (!is.na(fs)) { - css[idx] <- insert_field(css[idx], "indent", sprintf("%sem", fs)) - } - - fs <- sty[row, "fontsize"] - if (!is.na(fs)) { - css[idx] <- insert_field(css[idx], "fontsize", sprintf("%sem", fs)) - } - - col <- sty[row, "color"] - if (!is.na(col)) { - if (grepl("^#", col)) col <- sprintf('rgb("%s")', col) - css[idx] <- insert_field(css[idx], "color", col) - } - - bg <- sty[row, "background"] - if (!is.na(bg)) { - if (grepl("^#", bg)) bg <- sprintf('rgb("%s")', bg) - css[idx] <- insert_field(css[idx], "background", bg) - } + idx_i <- sty$i[row] + if (is.na(idx_i)) idx_i <- unique(rec$i) + idx_j <- sty$j[row] + if (is.na(idx_j)) idx_j <- unique(rec$j) + idx <- rec$i == idx_i & rec$j == idx_j + if (isTRUE(sty[row, "bold"])) css[idx] <- insert_field(css[idx], "bold", "true") + if (isTRUE(sty[row, "italic"])) css[idx] <- insert_field(css[idx], "italic", "true") + if (isTRUE(sty[row, "underline"])) css[idx] <- insert_field(css[idx], "underline", "true") + if (isTRUE(sty[row, "strikeout"])) css[idx] <- insert_field(css[idx], "strikeout", "true") + if (isTRUE(sty[row, "monospace"])) css[idx] <- insert_field(css[idx], "monospace", "true") + if (!is.na(sty[row, "align"])) css[idx] <- insert_field(css[idx], "align", sty[row, "align"]) + + fs <- sty[row, "indent"] + if (!is.na(fs)) { + css[idx] <- insert_field(css[idx], "indent", sprintf("%sem", fs)) + } + + fs <- sty[row, "fontsize"] + if (!is.na(fs)) { + css[idx] <- insert_field(css[idx], "fontsize", sprintf("%sem", fs)) + } + + col <- sty[row, "color"] + if (!is.na(col)) { + if (grepl("^#", col)) col <- sprintf('rgb("%s")', col) + css[idx] <- insert_field(css[idx], "color", col) + } + + bg <- sty[row, "background"] + if (!is.na(bg)) { + if (grepl("^#", bg)) bg <- sprintf('rgb("%s")', bg) + css[idx] <- insert_field(css[idx], "background", bg) + } } css <- gsub(" +", " ", trimws(css)) @@ -106,96 +105,96 @@ setMethod( pairs <- sapply(uni, function(x) paste(sprintf("(%s, %s),", x$j, x$i), collapse = " ")) styles <- sapply(uni, function(x) x$css[1]) - styles <- sprintf("(pairs: (%s), %s),", pairs, styles) + styles <- sprintf("(pairs: (%s), %s),", pairs, styles) for (s in styles) { - x@table_string <- lines_insert(x@table_string, s, "tinytable cell style after", "after") - # x@table_string <- lines_insert(x@table_string, s, "tinytable cell align after", "after") + x@table_string <- lines_insert(x@table_string, s, "tinytable cell style after", "after") } - lin <- sty[grepl("b|t", sty$line),, drop = FALSE] + lin <- sty[grepl("b|t", sty$line), , drop = FALSE] if (nrow(lin) > 0) { - lin <- split(lin, list(lin$i, lin$line, lin$line_color, lin$line_width)) - lin <- Filter(function(x) nrow(x) > 0, lin) - lin <- lapply(lin, hlines) - for (l in lin) { - x@table_string <- lines_insert(x@table_string, l, "tinytable lines before", "before") - } + lin <- split(lin, list(lin$i, lin$line, lin$line_color, lin$line_width)) + lin <- Filter(function(x) nrow(x) > 0, lin) + lin <- lapply(lin, hlines) + for (l in lin) { + x@table_string <- lines_insert(x@table_string, l, "tinytable lines before", "before") + } } - lin <- sty[grepl("l|r", sty$line),, drop = FALSE] + lin <- sty[grepl("l|r", sty$line), , drop = FALSE] if (nrow(lin) > 0) { - lin <- split(lin, list(lin$j, lin$line, lin$line_color, lin$line_width)) - lin <- Filter(function(x) nrow(x) > 0, lin) - lin <- lapply(lin, vlines) - for (l in lin) { - x@table_string <- lines_insert(x@table_string, l, "tinytable lines before", "before") - } + lin <- split(lin, list(lin$j, lin$line, lin$line_color, lin$line_width)) + lin <- Filter(function(x) nrow(x) > 0, lin) + lin <- lapply(lin, vlines) + for (l in lin) { + x@table_string <- lines_insert(x@table_string, l, "tinytable lines before", "before") + } } return(x) -}) + } +) split_chunks <- function(x) { - x <- sort(x) - breaks <- c(0, which(diff(x) != 1), length(x)) - result <- list() - for (i in seq_along(breaks)[-length(breaks)]) { - chunk <- x[(breaks[i] + 1):breaks[i + 1]] - result[[i]] <- c(min = min(chunk), max = max(chunk)) - } - out <- data.frame(do.call(rbind, result)) - out$max <- out$max + 1 - return(out) + x <- sort(x) + breaks <- c(0, which(diff(x) != 1), length(x)) + result <- list() + for (i in seq_along(breaks)[-length(breaks)]) { + chunk <- x[(breaks[i] + 1):breaks[i + 1]] + result[[i]] <- c(min = min(chunk), max = max(chunk)) + } + out <- data.frame(do.call(rbind, result)) + out$max <- out$max + 1 + return(out) } hlines <- function(k) { - xmin <- split_chunks(k$j)$min - xmax <- split_chunks(k$j)$max - ymin <- k$i[1] - ymax <- k$i[1] + 1 - line <- k$line[1] - color <- if (is.na(k$line_color[1])) "black" else k$line_color[1] - if (grepl("^#", color)) color <- sprintf('rgb("%s")', color) - width <- if (is.na(k$line_width[1])) 0.1 else k$line_width[1] - width <- sprintf("%sem", width) - out <- "" - if (grepl("t", line)) { - tmp <- "table.hline(y: %s, start: %s, end: %s, stroke: %s + %s)," - tmp <- sprintf(tmp, ymin, xmin, xmax, width, color) - out <- paste(out, tmp) - } - if (grepl("b", line)) { - tmp <- "table.hline(y: %s, start: %s, end: %s, stroke: %s + %s)," - tmp <- sprintf(tmp, ymax, xmin, xmax, width, color) - out <- paste(out, tmp) - } - return(out) + xmin <- split_chunks(k$j)$min + xmax <- split_chunks(k$j)$max + ymin <- k$i[1] + ymax <- k$i[1] + 1 + line <- k$line[1] + color <- if (is.na(k$line_color[1])) "black" else k$line_color[1] + if (grepl("^#", color)) color <- sprintf('rgb("%s")', color) + width <- if (is.na(k$line_width[1])) 0.1 else k$line_width[1] + width <- sprintf("%sem", width) + out <- "" + if (grepl("t", line)) { + tmp <- "table.hline(y: %s, start: %s, end: %s, stroke: %s + %s)," + tmp <- sprintf(tmp, ymin, xmin, xmax, width, color) + out <- paste(out, tmp) + } + if (grepl("b", line)) { + tmp <- "table.hline(y: %s, start: %s, end: %s, stroke: %s + %s)," + tmp <- sprintf(tmp, ymax, xmin, xmax, width, color) + out <- paste(out, tmp) + } + return(out) } vlines <- function(k) { - ymin <- split_chunks(k$i)$min - ymax <- split_chunks(k$i)$max - xmin <- k$j[1] - xmax <- xmin + 1 - line <- k$line[1] - color <- if (is.na(k$line_color[1])) "black" else k$line_color[1] - width <- if (is.na(k$line_width[1])) 0.1 else k$line_width[1] - width <- sprintf("%sem", width) - out <- "" - if (grepl("l", line)) { - tmp <- "table.vline(x: %s, start: %s, end: %s, stroke: %s + %s)," - tmp <- sprintf(tmp, xmin, ymin, ymax, width, color) - out <- paste(out, tmp) - } - if (grepl("r", line)) { - tmp <- "table.vline(x: %s, start: %s, end: %s, stroke: %s + %s)," - tmp <- sprintf(tmp, xmax, ymin, ymax, width, color) - out <- paste(out, tmp) - } - return(out) + ymin <- split_chunks(k$i)$min + ymax <- split_chunks(k$i)$max + xmin <- k$j[1] + xmax <- xmin + 1 + line <- k$line[1] + color <- if (is.na(k$line_color[1])) "black" else k$line_color[1] + width <- if (is.na(k$line_width[1])) 0.1 else k$line_width[1] + width <- sprintf("%sem", width) + out <- "" + if (grepl("l", line)) { + tmp <- "table.vline(x: %s, start: %s, end: %s, stroke: %s + %s)," + tmp <- sprintf(tmp, xmin, ymin, ymax, width, color) + out <- paste(out, tmp) + } + if (grepl("r", line)) { + tmp <- "table.vline(x: %s, start: %s, end: %s, stroke: %s + %s)," + tmp <- sprintf(tmp, xmax, ymin, ymax, width, color) + out <- paste(out, tmp) + } + return(out) } diff --git a/R/theme_bootstrap.R b/R/theme_bootstrap.R index 55dab118..ddd51c4b 100644 --- a/R/theme_bootstrap.R +++ b/R/theme_bootstrap.R @@ -1,26 +1,27 @@ theme_bootstrap <- function(x, ...) { + fn <- theme_placement_factory( + horizontal = get_option("tinytable_theme_default_horizontal", "c"), + latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL) + ) + x <- style_tt(x, finalize = fn) - fn <- theme_placement_factory( - horizontal = get_option("tinytable_theme_default_horizontal", "c"), - latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) - x <- style_tt(x, finalize = fn) - - fn <- function(table) { - if (isTRUE(table@output == "markdown")) { - tab <- table@table_string - tab <- strsplit(tab, "\n")[[1]] - tab <- tab[!grepl("^[\\+|-]+$", tab)] - tab <- gsub("|", " ", tab, fixed = TRUE) - table@table_string <- paste(tab, collapse = "\n") - } else if (isTRUE(table@output == "typst")) { - table <- style_tt(table, i = 0:nrow(table), line = "bt", line_width = 0.05, line_color = "silver") - } - return(table) + fn <- function(table) { + if (isTRUE(table@output == "markdown")) { + tab <- table@table_string + tab <- strsplit(tab, "\n")[[1]] + tab <- tab[!grepl("^[\\+|-]+$", tab)] + tab <- gsub("|", " ", tab, fixed = TRUE) + table@table_string <- paste(tab, collapse = "\n") + } else if (isTRUE(table@output == "typst")) { + table <- style_tt(table, i = 0:nrow(table), line = "bt", line_width = 0.05, line_color = "silver") } - x <- style_tt(x, finalize = theme_void_fn) # only affects LaTeX - x <- style_tt(x, - tabularray_inner = "hlines={gray8},", - bootstrap_class = "table", - finalize = fn) - return(x) + return(table) + } + x <- style_tt(x, finalize = theme_void_fn) # only affects LaTeX + x <- style_tt(x, + tabularray_inner = "hlines={gray8},", + bootstrap_class = "table", + finalize = fn + ) + return(x) } diff --git a/R/theme_default.R b/R/theme_default.R index e5b09b33..17b625f5 100644 --- a/R/theme_default.R +++ b/R/theme_default.R @@ -1,24 +1,40 @@ theme_default <- function(x, ...) { - fn <- theme_placement_factory( horizontal = get_option("tinytable_theme_default_horizontal", "c"), - latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) + latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL) + ) x <- style_tt(x, finalize = fn) if (isTRUE(x@output %in% c("html", "typst"))) { + col <- if (x@output == "typst") "black" else "#d3d8dc" bc <- if (length(x@bootstrap_class) == 0) "table table-borderless" else x@bootstrap_class - x <- style_tt(x, + # top + x <- style_tt(x, bootstrap_class = bc, - i = nrow(x) + x@ngroupi, - line = "b", - line_color = "#d3d8dc", - line_width = 0.1) - x <- style_tt(x, + i = -x@nhead + 1, + line = "t", + line_color = col, + line_width = 0.1 + ) + # mid + if (length(x@names) > 0) { + x <- style_tt(x, + bootstrap_class = bc, + i = 0, + line = "b", + line_color = col, + line_width = 0.05 + ) + } + # bottom + x <- style_tt(x, bootstrap_class = bc, - i = 0, - line = "bt", - line_color = "#d3d8dc", - line_width = 0.1) + i = nrow(x), + line = "b", + line_color = col, + line_width = 0.1 + ) } + return(x) } diff --git a/R/theme_grid.R b/R/theme_grid.R index dcbf3ee3..4b78f675 100644 --- a/R/theme_grid.R +++ b/R/theme_grid.R @@ -1,23 +1,26 @@ theme_grid <- function(x, ...) { + fn <- theme_placement_factory( + horizontal = get_option("tinytable_theme_default_horizontal", "c"), + latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL) + ) + x <- style_tt(x, finalize = fn) - fn <- theme_placement_factory( - horizontal = get_option("tinytable_theme_default_horizontal", "c"), - latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) - x <- style_tt(x, finalize = fn) - - fn <- function(table) { - if (isTRUE(table@output == "latex")) { - table <- theme_void_fn(table) - } else if (isTRUE(table@output == "typst")) { - table@table_string <- sub( - "stroke: none,", - "stroke: (paint: black),", - table@table_string) - } - return(table) + fn <- function(table) { + if (isTRUE(table@output == "latex")) { + table <- theme_void_fn(table) + } else if (isTRUE(table@output == "typst")) { + table@table_string <- sub( + "stroke: none,", + "stroke: (paint: black),", + table@table_string + ) } + return(table) + } - x <- style_tt(x, tabularray_inner = "hlines, vlines,", finalize = fn, - bootstrap_class = "table table-bordered") - return(x) + x <- style_tt(x, + tabularray_inner = "hlines, vlines,", finalize = fn, + bootstrap_class = "table table-bordered" + ) + return(x) } diff --git a/R/theme_multipage.R b/R/theme_multipage.R index 6d28635a..e5231a68 100644 --- a/R/theme_multipage.R +++ b/R/theme_multipage.R @@ -1,41 +1,41 @@ -theme_multipage <- function(x, - rowhead = get_option("tinytable_theme_multipage_rowhead", 0L), - rowfoot = get_option("tinytable_theme_multipage_rowfoot", 0L), +theme_multipage <- function(x, + rowhead = get_option("tinytable_theme_multipage_rowhead", 0L), + rowfoot = get_option("tinytable_theme_multipage_rowfoot", 0L), ...) { - # do not change the defaul theme - if (identical(x@theme[[1]], "multipage")) x@theme <- list("default") - assert_integerish(rowhead, lower = 0, len = 1) - assert_integerish(rowfoot, lower = 0, len = 1) - # cap <- sprintf("caption={%s}", x@caption) - # x@caption <- "" - fn <- function(table) { - if (!isTRUE(table@output == "latex")) return(table) - - tab <- table@table_string - tab <- sub("\\\\begin\\{talltblr", "\\\\begin\\{longtblr", tab) - tab <- sub("\\\\end\\{talltblr", "\\\\end\\{longtblr", tab) - - tab <- strsplit(tab, "\n")[[1]] - idx <- grepl("^\\\\caption\\{|^\\\\begin\\{table|^\\\\end\\{table|^\\\\centering", trimws(tab)) - tab <- tab[!idx] - tab <- paste(tab, collapse = "\n") + # do not change the defaul theme + if (identical(x@theme[[1]], "multipage")) x@theme <- list("default") + assert_integerish(rowhead, lower = 0, len = 1) + assert_integerish(rowfoot, lower = 0, len = 1) + # cap <- sprintf("caption={%s}", x@caption) + # x@caption <- "" + fn <- function(table) { + if (!isTRUE(table@output == "latex")) { + return(table) + } - table@table_string <- tab + tab <- table@table_string + tab <- sub("\\\\begin\\{talltblr", "\\\\begin\\{longtblr", tab) + tab <- sub("\\\\end\\{talltblr", "\\\\end\\{longtblr", tab) - # table <- style_tt(table, tabularray_outer = cap) + tab <- strsplit(tab, "\n")[[1]] + idx <- grepl("^\\\\caption\\{|^\\\\begin\\{table|^\\\\end\\{table|^\\\\centering", trimws(tab)) + tab <- tab[!idx] + tab <- paste(tab, collapse = "\n") - if (rowhead > 0) { - table <- style_tt(table, tabularray_inner = sprintf("rowhead=%s", rowhead)) - } + table@table_string <- tab - if (rowfoot > 0) { - table <- style_tt(table, tabularray_inner = sprintf("rowfoot=%s", rowfoot)) - } + # table <- style_tt(table, tabularray_outer = cap) - return(table) + if (rowhead > 0) { + table <- style_tt(table, tabularray_inner = sprintf("rowhead=%s", rowhead)) } - x <- style_tt(x, finalize = fn) - return(x) -} + if (rowfoot > 0) { + table <- style_tt(table, tabularray_inner = sprintf("rowfoot=%s", rowfoot)) + } + return(table) + } + x <- style_tt(x, finalize = fn) + return(x) +} diff --git a/R/theme_placement.R b/R/theme_placement.R index 21d17cc8..1937b8ba 100644 --- a/R/theme_placement.R +++ b/R/theme_placement.R @@ -1,36 +1,34 @@ theme_placement_factory <- function( horizontal = get_option("tinytable_theme_placement_horizontal", default = NULL), latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) { - - function(x) { - tab <- x@table_string - if (x@output == "latex" && !is.null(latex_float)) { - assert_string(latex_float, null.ok = TRUE) - tab <- sub( - "\\\\begin\\{table\\}([^\\[])", - sprintf("\\\\begin{table}[%s]\\1", latex_float), - tab) - } else if (x@output == "typst" && !is.null(horizontal)) { - assert_choice(horizontal, c("l", "c", "r")) - if (horizontal == "l") { - tab <- sub("#align(center,", "#align(left,", tab, fixed = TRUE) - } else if (horizontal == "r") { - tab <- sub("#align(center,", "#align(right,", tab, fixed = TRUE) - } - } - x@table_string <- tab - return(x) + function(x) { + tab <- x@table_string + if (x@output == "latex" && !is.null(latex_float)) { + assert_string(latex_float, null.ok = TRUE) + tab <- sub( + "\\\\begin\\{table\\}([^\\[])", + sprintf("\\\\begin{table}[%s]\\1", latex_float), + tab + ) + } else if (x@output == "typst" && !is.null(horizontal)) { + assert_choice(horizontal, c("l", "c", "r")) + if (horizontal == "l") { + tab <- sub("#align(center,", "#align(left,", tab, fixed = TRUE) + } else if (horizontal == "r") { + tab <- sub("#align(center,", "#align(right,", tab, fixed = TRUE) + } } + x@table_string <- tab + return(x) + } } theme_placement <- function( - x, + x, horizontal = get_option("tinytable_theme_placement_horizontal", default = NULL), latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) { - fn <- theme_placement_factory(horizontal = horizontal, latex_float = latex_float) - x <- style_tt(x, finalize = fn) - return(x) + fn <- theme_placement_factory(horizontal = horizontal, latex_float = latex_float) + x <- style_tt(x, finalize = fn) + return(x) } - - diff --git a/R/theme_resize.R b/R/theme_resize.R index f56d2c2f..345ea029 100644 --- a/R/theme_resize.R +++ b/R/theme_resize.R @@ -1,44 +1,44 @@ -theme_resize <- function(x, - width = get_option("tinytable_theme_resize_width", 1), - direction = get_option("tinytable_theme_resize_direction", "down"), +theme_resize <- function(x, + width = get_option("tinytable_theme_resize_width", 1), + direction = get_option("tinytable_theme_resize_direction", "down"), ...) { + fn <- theme_placement_factory( + horizontal = get_option("tinytable_theme_default_horizontal", "c"), + latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL) + ) + x <- style_tt(x, finalize = fn) + + assert_numeric(width, len = 1, lower = 0.01, upper = 1) + assert_choice(direction, c("down", "up", "both")) + # do not change the default theme + if (identical(x@theme[[1]], "resize")) x@theme <- list("default") + fn <- function(table) { + if (!isTRUE(table@output == "latex")) { + return(table) + } - fn <- theme_placement_factory( - horizontal = get_option("tinytable_theme_default_horizontal", "c"), - latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) - x <- style_tt(x, finalize = fn) - - assert_numeric(width, len = 1, lower = 0.01, upper = 1) - assert_choice(direction, c("down", "up", "both")) - # do not change the default theme - if (identical(x@theme[[1]], "resize")) x@theme <- list("default") - fn <- function(table) { - if (!isTRUE(table@output == "latex")) return(table) + tab <- table@table_string - tab <- table@table_string + if (direction == "both") { + new <- sprintf("\\resizebox{%s\\linewidth}{!}{", width) + } else if (direction == "down") { + new <- sprintf("\\resizebox{\\ifdim\\width>\\linewidth %s\\linewidth\\else\\width\\fi}{!}{", width) + } else if (direction == "up") { + new <- sprintf("\\resizebox{\\ifdim\\width<\\linewidth %s\\linewidth\\else\\width\\fi}{!}{", width) + } - if (direction == "both") { - new <- sprintf("\\resizebox{%s\\linewidth}{!}{", width) - } else if (direction == "down") { - new <- sprintf("\\resizebox{\\ifdim\\width>\\linewidth %s\\linewidth\\else\\width\\fi}{!}{", width) - } else if (direction == "up") { - new <- sprintf("\\resizebox{\\ifdim\\width<\\linewidth %s\\linewidth\\else\\width\\fi}{!}{", width) - } + reg <- "\\\\begin\\{tblr\\}|\\\\begin\\{talltblr\\}" + tab <- lines_insert(tab, regex = reg, new = new, position = "before") - reg <- "\\\\begin\\{tblr\\}|\\\\begin\\{talltblr\\}" - tab <- lines_insert(tab, regex = reg, new = new, position = "before") + new <- "}" + reg <- "\\\\end\\{tblr\\}|\\\\end\\{talltblr\\}" + tab <- lines_insert(tab, regex = reg, new = new, position = "after") - new <- "}" - reg <- "\\\\end\\{tblr\\}|\\\\end\\{talltblr\\}" - tab <- lines_insert(tab, regex = reg, new = new, position = "after") + table@table_string <- tab - table@table_string <- tab + return(table) + } - return(table) - } - - x <- style_tt(x, finalize = fn) - return(x) + x <- style_tt(x, finalize = fn) + return(x) } - - diff --git a/R/theme_revealjs.R b/R/theme_revealjs.R new file mode 100644 index 00000000..5be2cab4 --- /dev/null +++ b/R/theme_revealjs.R @@ -0,0 +1,44 @@ +theme_revealjs <- function( + x, + fontsize = get_option("tinytable_theme_revealjs_fontsize", default = 0.8), + fontsize_caption = get_option("tinytable_theme_revealjs_fontsize_caption", default = 1)) { + css <- " +// tables + +.reveal table { + // height: auto; /* Adjust table width to fit content up to the available slide space */ + margin: auto; + border-collapse: collapse; + border-spacing: 0; +} + +.reveal table th, +.reveal table td { + border: none; + padding: .23em; + font-weight: lighter; + font-size: %sem; +} + +/* Adds a bottom border to the table header row for distinction */ +.reveal table thead th, +.reveal .slides table tr:last-child td, +.reveal .slides table { + border-bottom: 2px solid #D3D3D3; +} + +/* Make column headers bold */ +.reveal table thead th { +/* font-weight: bold; */ +} + +/* Styling table captions */ +.reveal table caption { + color: #666666; /* Dark grey color for the caption */ + font-size: %emem; +} +" + css <- sprintf(css, fontsize, fontsize_caption) + x <- style_tt(x, bootstrap_css_rule = css) + return(x) +} diff --git a/R/theme_rotate.R b/R/theme_rotate.R index d04ca483..0db5403b 100644 --- a/R/theme_rotate.R +++ b/R/theme_rotate.R @@ -1,35 +1,38 @@ theme_rotate <- function(x, angle = 90, ...) { - assert_numeric(angle, len = 1, lower = 0, upper = 360) - fn <- function(table) { - if (isTRUE(table@output == "latex")) { - rot <- sprintf("\\begin{table}\n\\rotatebox{%s}{", angle) - table@table_string <- sub( - "\\begin{table}", - rot, - table@table_string, - fixed = TRUE) - table@table_string <- sub( - "\\end{table}", - "}\n\\end{table}", - table@table_string, - fixed = TRUE) - } else if (isTRUE(table@output == "typst")) { - rot <- sprintf("#rotate(-%sdeg, reflow: true, [\n #figure(", angle) - table@table_string <- sub( - "#figure(", - rot, - table@table_string, - fixed = TRUE) - table@table_string <- sub( - ") // end figure", - ") ]) // end figure", - table@table_string, - fixed = TRUE) - } - table <- style_tt(table, finalize = fn) - return(table) + assert_numeric(angle, len = 1, lower = 0, upper = 360) + fn <- function(table) { + if (isTRUE(table@output == "latex")) { + rot <- sprintf("\\begin{table}\n\\rotatebox{%s}{", angle) + table@table_string <- sub( + "\\begin{table}", + rot, + table@table_string, + fixed = TRUE + ) + table@table_string <- sub( + "\\end{table}", + "}\n\\end{table}", + table@table_string, + fixed = TRUE + ) + } else if (isTRUE(table@output == "typst")) { + rot <- sprintf("#rotate(-%sdeg, reflow: true, [\n #figure(", angle) + table@table_string <- sub( + "#figure(", + rot, + table@table_string, + fixed = TRUE + ) + table@table_string <- sub( + ") // end figure", + ") ]) // end figure", + table@table_string, + fixed = TRUE + ) } - x <- style_tt(x, finalize = fn) - return(x) + table <- style_tt(table, finalize = fn) + return(table) + } + x <- style_tt(x, finalize = fn) + return(x) } - diff --git a/R/theme_spacing.R b/R/theme_spacing.R new file mode 100644 index 00000000..10c1153c --- /dev/null +++ b/R/theme_spacing.R @@ -0,0 +1,48 @@ +theme_spacing <- function(x, + rowsep = get_option("tinytable_theme_spacing_rowsep", 0.1), + colsep = get_option("tinytable_theme_spacing_colsep", 0.5), + ...) { + # placement + fn <- theme_placement_factory( + horizontal = get_option("tinytable_theme_default_horizontal", "c"), + latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL) + ) + x <- style_tt(x, finalize = fn) + + # rules + if (isTRUE(x@output %in% c("html", "typst"))) { + bc <- if (length(x@bootstrap_class) == 0) "table table-borderless" else x@bootstrap_class + x <- style_tt(x, + bootstrap_class = bc, + i = nrow(x), + line = "b", + line_color = "#d3d8dc", + line_width = 0.1 + ) + x <- style_tt(x, + bootstrap_class = bc, + i = 0, + line = "bt", + line_color = "#d3d8dc", + line_width = 0.1 + ) + } + + # spacing + x <- style_tt(x, + tabularray_inner = sprintf("rowsep={%sem}, colsep = {%sem}", rowsep, colsep) + ) + x <- style_tt(x, + tabularray_inner = sprintf("rowsep={%sem}, colsep = {%sem}", rowsep, colsep) + ) + x <- style_tt(x, + j = seq_len(ncol(x) - 1), + bootstrap_css = sprintf("padding-right: %sem;", colsep) + ) + x <- style_tt(x, + i = -5:(nrow(x) - 1), + bootstrap_css = sprintf("padding-bottom: %sem;", rowsep) + ) + + return(x) +} diff --git a/R/theme_striped.R b/R/theme_striped.R index 375ecd9a..80d9ee28 100644 --- a/R/theme_striped.R +++ b/R/theme_striped.R @@ -1,32 +1,36 @@ theme_striped <- function(x, ...) { + fn <- theme_placement_factory( + horizontal = get_option("tinytable_theme_default_horizontal", "c"), + latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL) + ) + x <- style_tt(x, finalize = fn) - fn <- theme_placement_factory( - horizontal = get_option("tinytable_theme_default_horizontal", "c"), - latex_float = get_option("tinytable_theme_placement_latex_float", default = NULL)) - x <- style_tt(x, finalize = fn) + x <- style_tt(x, + tabularray_inner = "row{even}={bg=black!5!white}", + bootstrap_class = "table table-striped", + output = "latex" + ) - x <- style_tt(x, - tabularray_inner = "row{even}={bg=black!5!white}", - bootstrap_class = "table table-striped", - output = "latex") - - x <- style_tt(x, - i = seq(1, nrow(x), by = 2), - background = "#ededed", - output = "typst") + x <- style_tt(x, + i = seq(1, nrow(x), by = 2), + background = "#ededed", + output = "typst" + ) - # theme_default - if (isTRUE(x@output %in% c("html", "typst"))) { - x <- style_tt(x, - i = nrow(x), - line = "b", - line_color = "#d3d8dc", - line_width = 0.1) - x <- style_tt(x, - i = 0, - line = "bt", - line_color = "#d3d8dc", - line_width = 0.1) - } - return(x) + # theme_default + if (isTRUE(x@output %in% c("html", "typst"))) { + x <- style_tt(x, + i = nrow(x), + line = "b", + line_color = "#d3d8dc", + line_width = 0.1 + ) + x <- style_tt(x, + i = 0, + line = "bt", + line_color = "#d3d8dc", + line_width = 0.1 + ) + } + return(x) } diff --git a/R/theme_tabular.R b/R/theme_tabular.R index 5e7442fb..d50548fa 100644 --- a/R/theme_tabular.R +++ b/R/theme_tabular.R @@ -1,55 +1,50 @@ -theme_tabular <- function(x, - style = get_option("tinytable_theme_tabular_style", "tabular"), +theme_tabular <- function(x, + style = get_option("tinytable_theme_tabular_style", "tabular"), ...) { - - assert_choice(style, c("tabular", "tabularray")) - - # do not change the default theme - if (identical(x@theme[[1]], "tabular")) x@theme <- list("default") - - fn <- function(table) { - tab <- table@table_string - - if (isTRUE(table@output == "latex")) { - tab <- lines_drop(tab, regex = "\\\\begin\\{table\\}", position = "before") - tab <- lines_drop(tab, regex = "\\\\begin\\{table\\}", position = "equal") - tab <- lines_drop(tab, regex = "\\\\end\\{table\\}", position = "after") - tab <- lines_drop(tab, regex = "\\\\end\\{table\\}", position = "equal") - tab <- lines_drop(tab, regex = "\\\\centering", position = "equal") - if (style == "tabular") { - tab <- lines_drop_between(tab, regex_start = "tabularray outer open", regex_end = "tabularray inner close") - tab <- lines_drop(tab, regex = "tabularray outer close", position = "equal") - tab <- lines_drop(tab, regex = "tabularray inner open", position = "equal") - tab <- lines_drop(tab, regex = "tabularray inner close", position = "equal") - tab <- lines_drop(tab, regex = "^colspec=\\{", position = "equal") - tab <- gsub("cmidrule\\[(.*?)\\]", "cmidrule(\\1)", tab) - tab <- gsub("\\{tblr\\}\\[*", "{tabular}", tab) - tab <- gsub("\\{talltblr\\}\\[", "{tabular}", tab) - tab <- gsub("\\{talltblr\\}", "{tabular}", tab) - tab <- gsub("\\{longtblr\\}\\[", "{tabular}", tab) - tab <- gsub("\\{longtblr\\}", "{tabular}", tab) - tab <- gsub("\\\\toprule|\\\\midrule|\\\\bottomrule", "\\\\hline", tab) - tab <- sub("\\s*%% tabularray outer open", "", tab) - tab <- sub("\\s*%% TinyTableHeader", "", tab) - # align - a <- sprintf("begin{tabular}{%s}", strrep("l", ncol(table))) - tab <- sub("begin{tabular}", a, tab, fixed = TRUE) - } - - } else if (isTRUE(table@output == "html")) { - tab <- lines_drop(tab, regex = " theme_tt("striped") -#' +#' #' # resize w/ argument -#' x <- cbind(mtcars[1:10,], mtcars[1:10,]) +#' x <- cbind(mtcars[1:10, ], mtcars[1:10, ]) #' tt(x) |> #' theme_tt("resize", width = .9) |> #' print("latex") -#' +#' #' @return A modified `tinytable` object #' @export theme_tt <- function(x, theme, ...) { - assert_class(x, "tinytable") - if (is.null(theme)) return(x) - if (is.function(theme)) return(theme(x, ...)) - td <- theme_dictionary - na <- unique(sort(names(td))) - assert_choice(theme, na) - fn <- td[[theme]] - out <- list(list(fn, list(...))) - x@lazy_theme <- c(x@lazy_theme, out) + assert_class(x, "tinytable") + if (is.null(theme)) { return(x) + } + if (is.function(theme)) { + return(theme(x, ...)) + } + td <- theme_dictionary + na <- unique(sort(names(td))) + assert_choice(theme, na) + fn <- td[[theme]] + out <- list(list(fn, list(...))) + x@lazy_theme <- c(x@lazy_theme, out) + return(x) } - diff --git a/R/tt.R b/R/tt.R index c7487273..cc31de18 100644 --- a/R/tt.R +++ b/R/tt.R @@ -15,8 +15,8 @@ #' @param x A data frame or data table to be rendered as a table. #' @param digits Number of significant digits to keep for numeric variables. When `digits` is an integer, `tt()` calls `format_tt(x, digits = digits)` before proceeding to draw the table. Note that this will apply all default argument values of `format_tt()`, such as replacing `NA` by "". Users who need more control can use the `format_tt()` function instead. #' @param caption A string that will be used as the caption of the table. This argument should *not* be used in Quarto or Rmarkdown documents. In that context, please use the appropriate chunk options. -#' @param width Table or column width. -#' - Single numeric value smaller than or equal to 1 determines the full table width, in proportion of line width. +#' @param width Table or column width. +#' - Single numeric value smaller than or equal to 1 determines the full table width, in proportion of line width. #' - Numeric vector of length equal to the number of columns in `x` determines the width of each column, in proportion of line width. If the sum of `width` exceeds 1, each element is divided by `sum(width)`. This makes the table full-width with relative column sizes. #' @param theme Function or string. #' - String: `r paste(setdiff(names(theme_dictionary), "default"), collapse = ", ")` @@ -30,31 +30,33 @@ #' @param escape Logical. If `TRUE`, escape special characters in the table. Equivalent to `format_tt(tt(x), escape = TRUE)`. #' @param ... Additional arguments are ignored #' @return An object of class `tt` representing the table. -#' +#' #' The table object has S4 slots which hold information about the structure of the table. Relying on or modifying the contents of these slots is strongly discouraged. Their names and contents could change at any time, and the `tinytable` developers do not consider changes to the internal structure of the output object to be a "breaking change" for versioning or changelog purposes. +#' @template dependencies #' @template latex_preamble +#' @template limitations_word_markdown #' @template global_options -#' +#' #' @examples #' library(tinytable) #' x <- mtcars[1:4, 1:5] #' #' tt(x) -#' +#' #' tt(x, -#' theme = "striped", -#' width = 0.5, -#' caption = "Data about cars.") -#' +#' theme = "striped", +#' width = 0.5, +#' caption = "Data about cars.") +#' #' tt(x, notes = "Hello World!") #' #' fn <- list(i = 0:1, j = 2, text = "Hello World!") #' tab <- tt(x, notes = list("*" = fn)) #' print(tab, "latex") -#' +#' #' k <- data.frame(x = c(0.000123456789, 12.4356789)) -#' tt(k, digits=2) -#' +#' tt(k, digits = 2) +#' #' @export tt <- function(x, digits = get_option("tinytable_tt_digits", default = NULL), @@ -65,8 +67,6 @@ tt <- function(x, rownames = get_option("tinytable_tt_rownames", default = FALSE), escape = get_option("tinytable_tt_escape", default = FALSE), ...) { - - dots <- list(...) # sanity checks @@ -90,20 +90,20 @@ tt <- function(x, # it might be dangerous to leave non-numerics, but what about dates and other character-coercibles? for (i in seq_along(x)) { if (is.factor(x[[i]])) { - x[[i]] <- as.character(x[[i]]) + x[[i]] <- as.character(x[[i]]) } } assert_numeric(width, lower = 0, null.ok = TRUE) if (!length(width) %in% c(0, 1, ncol(x))) { - msg <- sprintf("The `width` argument must have length 1 or %s.", ncol(x)) - stop(msg, call. = FALSE) + msg <- sprintf("The `width` argument must have length 1 or %s.", ncol(x)) + stop(msg, call. = FALSE) } if (sum(width) > 1) { - width <- width / sum(width) + width <- width / sum(width) } - # bind the row names if the user explicitly asks for it in global option. + # bind the row names if the user explicitly asks for it in global option. # Same name as tibble::rownames_to_column() assert_flag(rownames) if (isTRUE(rownames) && !is.null(row.names(x))) { @@ -123,6 +123,7 @@ tt <- function(x, # twice because format() leaves Date type, which cannot be partially reasigned # with indexed format_tt(i) tab <- data.frame(lapply(tab, format)) + tab <- data.frame(lapply(tab, trimws)) colnames(tab) <- colnames(x) out <- methods::new("tinytable", @@ -131,7 +132,8 @@ tt <- function(x, caption = caption, notes = notes, theme = list(theme), - width = width) + width = width + ) if (is.null(theme)) { out <- theme_tt(out, theme = "default") diff --git a/R/tt_bootstrap.R b/R/tt_bootstrap.R index 4fa11522..331d3b9b 100644 --- a/R/tt_bootstrap.R +++ b/R/tt_bootstrap.R @@ -2,176 +2,182 @@ setMethod( f = "tt_eval", signature = "tinytable_bootstrap", definition = function(x, ...) { + template <- readLines(system.file("templates/bootstrap.html", package = "tinytable")) + + mathjax <- get_option("tinytable_html_mathjax", default = FALSE) + assert_flag(mathjax, name = "tinytable_html_mathjax") + if (isFALSE(mathjax)) { + template <- paste(template, collapse = "\n") + sta <- " " + end <- " " + template <- lines_drop_between(template, sta, end, fixed = TRUE) + template <- strsplit(template, "\n")[[1]] + } - template <- readLines(system.file("templates/bootstrap.html", package = "tinytable")) - - mathjax <- get_option("tinytable_html_mathjax", default = FALSE) - assert_flag(mathjax, name = "tinytable_html_mathjax") - if (isFALSE(mathjax)) { - template <- paste(template, collapse = "\n") - sta <- " " - end <- " " - template <- lines_drop_between(template, sta, end, fixed = TRUE) - template <- strsplit(template, "\n")[[1]] - } - - quartoprocessing <- get_option("tinytable_quarto_disable_processing", default = TRUE) - assert_flag(quartoprocessing, name = "tinytable_quarto_disable_processing") - if (isFALSE(quartoprocessing)) { + quartoprocessing <- get_option("tinytable_quarto_disable_processing", default = TRUE) + assert_flag(quartoprocessing, name = "tinytable_quarto_disable_processing") + if (isFALSE(quartoprocessing)) { template <- sub("data-quarto-disable-processing='true'", - "data-quarto-disable-processing='false'", - template, - fixed = TRUE) - } + "data-quarto-disable-processing='false'", + template, + fixed = TRUE + ) + } - # caption - if (length(x@caption) != 1) { - template <- sub( - "$tinytable_BOOTSTRAP_CAPTION", - "", - template, - fixed = TRUE - ) - } else { - template <- sub( - "$tinytable_BOOTSTRAP_CAPTION", - sprintf("", x@caption), - template, - fixed = TRUE - ) - } + # caption + if (length(x@caption) != 1) { + template <- sub( + "$tinytable_BOOTSTRAP_CAPTION", + "", + template, + fixed = TRUE + ) + } else { + template <- sub( + "$tinytable_BOOTSTRAP_CAPTION", + sprintf("", x@caption), + template, + fixed = TRUE + ) + } - # note - if (length(x@notes) == 0) { - template <- sub( - "$tinytable_BOOTSTRAP_NOTE", - "", - template, - fixed = TRUE - ) - } else { - notes_tmp <- NULL - for (k in seq_along(x@notes)) { - if (!is.null(names(x@notes))) { - if (is.list(x@notes[[k]])) { - tmp <- sprintf("", - ncol(x), - names(x@notes)[k], - x@notes[[k]]$text) - # note is a string + # note + if (length(x@notes) == 0) { + template <- sub( + "$tinytable_BOOTSTRAP_NOTE", + "", + template, + fixed = TRUE + ) + } else { + notes_tmp <- NULL + for (k in seq_along(x@notes)) { + if (!is.null(names(x@notes))) { + if (is.list(x@notes[[k]])) { + tmp <- sprintf( + "", + ncol(x), + names(x@notes)[k], + x@notes[[k]]$text + ) + # note is a string + } else { + tmp <- sprintf( + "", + ncol(x), + names(x@notes)[k], + x@notes[k] + ) + } } else { - tmp <- sprintf("", - ncol(x), - names(x@notes)[k], - x@notes[k]) + tmp <- sprintf("", ncol(x), x@notes[[k]]) } - } else { - tmp <- sprintf("", ncol(x), x@notes[[k]]) + notes_tmp <- c(notes_tmp, tmp) } - notes_tmp <- c(notes_tmp, tmp) - } - notes <- paste(notes_tmp, collapse = "\n") - notes <- paste0("", notes, "") - template <- sub( - "$tinytable_BOOTSTRAP_NOTE", - notes, - template, - fixed = TRUE - ) - for (ii in seq_along(notes)) { + notes <- paste(notes_tmp, collapse = "\n") + notes <- paste0("", notes, "") + template <- sub( + "$tinytable_BOOTSTRAP_NOTE", + notes, + template, + fixed = TRUE + ) + for (ii in seq_along(notes)) { x <- style_tt(x, i = nrow(x) + ii, align = "l") + } } - } - # width - if (length(x@width) == 1) { - template <- sub( - "width: auto;", - sprintf('table-layout: fixed; width: %s%% !important;', round(x@width * 100)), - template, - fixed = TRUE + # width + if (length(x@width) == 1) { + template <- sub( + "width: auto;", + sprintf("table-layout: fixed; width: %s%% !important;", round(x@width * 100)), + template, + fixed = TRUE + ) + } else if (length(x@width) > 1) { + template <- sub( + "width: auto;", + sprintf("table-layout: fixed; width: %s%% !important;", round(sum(x@width) * 100)), + template, + fixed = TRUE + ) + } + + # (pseudo-)unique table IDs + id <- get_id("") + x@id <- id + + # table and styling function in JS must have different names when there is more than one table on a page. + template <- gsub("styleCell", paste0("styleCell_", id), template, fixed = TRUE) + template <- gsub("spanCell", paste0("spanCell_", id), template, fixed = TRUE) + template <- gsub("$tinytable_TABLE_ID", paste0("tinytable_", id), template, fixed = TRUE) + + # header + idx <- grep("$tinytable_BOOTSTRAP_HEADER", template, fixed = TRUE) + if (length(colnames(x)) > 0) { + header <- sprintf(' ', colnames(x)) + header <- c(" ", header, " ") + header <- paste(strrep(" ", 11), header) + } else { + header <- NULL + } + template <- c( + template[1:(idx - 1)], + header, + template[(idx + 1):length(template)] ) - } else if (length(x@width) > 1) { - template <- sub( - "width: auto;", - sprintf('table-layout: fixed; width: %s%% !important;', round(sum(x@width) * 100)), - template, - fixed = TRUE + # body + makerow <- function(k) { + out <- c( + " ", + sprintf(" ", k), + " " + ) + return(out) + } + body <- apply(x@table_dataframe, 1, makerow) + idx <- grep("$tinytable_BOOTSTRAP_BODY", template, fixed = TRUE) + template <- c( + template[1:(idx - 1)], + paste(strrep(" ", 13), body), + template[(idx + 1):length(template)] ) - } - # (pseudo-)unique table IDs - id <- get_id("") - x@id <- id - - # table and styling function in JS must have different names when there is more than one table on a page. - template <- gsub("styleCell", paste0("styleCell_", id), template, fixed = TRUE) - template <- gsub("spanCell", paste0("spanCell_", id), template, fixed = TRUE) - template <- gsub("$tinytable_TABLE_ID", paste0("tinytable_", id), template, fixed = TRUE) - - # header - idx <- grep("$tinytable_BOOTSTRAP_HEADER", template, fixed = TRUE) - if (length(colnames(x)) > 0) { - header <- sprintf(' ', colnames(x)) - header <- c(" ", header, " ") - header <- paste(strrep(" ", 11), header) - } else { - header <- NULL - } - template <- c( - template[1:(idx - 1)], - header, - template[(idx + 1):length(template)] - ) - # body - makerow <- function(k) { - out <- c( - " ", - sprintf(' ', k), - " ") - return(out) - } - body <- apply(x@table_dataframe, 1, makerow) - idx <- grep("$tinytable_BOOTSTRAP_BODY", template, fixed = TRUE) - template <- c( - template[1:(idx - 1)], - paste(strrep(" ", 13), body), - template[(idx + 1):length(template)] - ) - - out <- paste(template, collapse = "\n") - - # before style_eval() - x@table_string <- out - - if (length(x@bootstrap_class) == 0) { - if (is.null(x@theme[[1]]) || is.function(x@theme[[1]]) || isTRUE("default" %in% x@theme[[1]])) { - x <- theme_tt(x, "default") + out <- paste(template, collapse = "\n") + + # before style_eval() + x@table_string <- out + + if (length(x@bootstrap_class) == 0) { + if (is.null(x@theme[[1]]) || is.function(x@theme[[1]]) || isTRUE("default" %in% x@theme[[1]])) { + x <- theme_tt(x, "default") + } + } else if ("bootstrap" %in% x@theme[[1]]) { + x <- style_tt(x, bootstrap_class = "table") + } else if ("striped" %in% x@theme[[1]]) { + x <- style_tt(x, bootstrap_class = "table table-striped") + } else if ("grid" %in% x@theme[[1]]) { + x <- style_tt(x, bootstrap_class = "table table-bordered") + } else if ("void" %in% x@theme[[1]]) { + x <- style_tt(x, bootstrap_class = "table table-borderless") } - } else if ("bootstrap" %in% x@theme[[1]]) { - x <- style_tt(x, bootstrap_class = "table") - } else if ("striped" %in% x@theme[[1]]) { - x <- style_tt(x, bootstrap_class = "table table-striped") - } else if ("grid" %in% x@theme[[1]]) { - x <- style_tt(x, bootstrap_class = "table table-bordered") - } else if ("void" %in% x@theme[[1]]) { - x <- style_tt(x, bootstrap_class = "table table-borderless") - } - if (length(x@width) > 1) { + if (length(x@width) > 1) { for (j in seq_len(ncol(x))) { - css <- sprintf("width: %s%%;", x@width[j] / sum(x@width) * 100) - x <- style_tt(x, j = j, bootstrap_css = css) + css <- sprintf("width: %s%%;", x@width[j] / sum(x@width) * 100) + x <- style_tt(x, j = j, bootstrap_css = css) } - } + } - return(x) -}) + return(x) + } +) bootstrap_setting <- function(x, new, component = "row") { - att <- attributes(x) + att <- attributes(x) out <- strsplit(x, "\n")[[1]] if (component == "row") { idx <- grep("tinytable rows before this", out) diff --git a/R/tt_grid.R b/R/tt_grid.R index ba67c2af..40bc5aca 100755 --- a/R/tt_grid.R +++ b/R/tt_grid.R @@ -6,8 +6,7 @@ grid_line <- function(width_cols, char = "-") { } -tt_eval_grid <- function(x, width_cols = NULL, ...) { - +tt_eval_grid <- function(x, width_cols = NULL, ...) { is_matrix <- is.matrix(x) if (is_matrix) { tab <- x @@ -16,7 +15,7 @@ tt_eval_grid <- function(x, width_cols = NULL, ...) { } if (is.null(width_cols)) { - width_cols <- x@width_cols + width_cols <- x@width_cols } tthead <- inherits(x, "tinytable") && isTRUE(x@nhead > 0) @@ -81,7 +80,9 @@ tt_eval_grid <- function(x, width_cols = NULL, ...) { out <- paste(tab, collapse = "\n") - if (is_matrix) return(out) + if (is_matrix) { + return(out) + } # rebuild output x@width_cols <- width_cols @@ -140,14 +141,17 @@ grid_hlines <- function(x) { setMethod( f = "tt_eval", signature = "tinytable_grid", - definition = tt_eval_grid) + definition = tt_eval_grid +) setMethod( f = "tt_eval", signature = "matrix", - definition = tt_eval_grid) + definition = tt_eval_grid +) setMethod( f = "tt_eval", signature = "tinytable_dataframe", - definition = tt_eval_grid) + definition = tt_eval_grid +) diff --git a/R/tt_tabularray.R b/R/tt_tabularray.R index 76e2cf16..21f86972 100644 --- a/R/tt_tabularray.R +++ b/R/tt_tabularray.R @@ -2,115 +2,111 @@ setMethod( f = "tt_eval", signature = "tinytable_tabularray", definition = function(x, ...) { + template <- readLines(system.file("templates/tabularray.tex", package = "tinytable")) - template <- readLines(system.file("templates/tabularray.tex", package = "tinytable")) + ncols <- ncol(x) + nrows <- nrow(x) - ncols <- ncol(x) - nrows <- nrow(x) + tall <- FALSE + if (length(x@caption) > 0) tall <- TRUE + if (length(x@notes) > 0) tall <- TRUE - tall <- FALSE - if (length(x@caption) > 0) tall <- TRUE - if (length(x@notes) > 0) tall <- TRUE + # placement + if (length(x@placement) == 1) { + assert_string(x@placement) + # dollar sign to avoid [H][H] when we style multiple times + template <- sub("\\\\begin\\{table\\}", sprintf("\\\\begin{table}[%s]\n", x@placement), template) + } - # placement - if (length(x@placement) == 1) { - assert_string(x@placement) - # dollar sign to avoid [H][H] when we style multiple times - template <- sub("\\\\begin\\{table\\}", sprintf("\\\\begin{table}[%s]\n", x@placement), template) - } - - # body: main - if (length(colnames(x)) > 0) { - header <- paste(colnames(x), collapse = " & ") - header <- paste(header, "\\\\") - } else { - header <- NULL - } - body <- apply(as.data.frame(x@table_dataframe), 1, paste, collapse = " & ") - body <- paste(body, "\\\\") - - # theme: booktabs - th <- x@theme[[1]] - if (is.null(th) || is.function(th) || isTRUE(th %in% c("default", "striped"))) { + # body: main if (length(colnames(x)) > 0) { - # %% are important to distinguish between potentially redundant data rows - header[length(header)] <- paste(header[length(header)], "\\midrule %% TinyTableHeader") + header <- paste(colnames(x), collapse = " & ") + header <- paste(header, "\\\\") + } else { + header <- NULL + } + body <- apply(as.data.frame(x@table_dataframe), 1, paste, collapse = " & ") + body <- paste(body, "\\\\") + + # theme: booktabs + th <- x@theme[[1]] + if (is.null(th) || is.function(th) || isTRUE(th %in% c("default", "striped"))) { + if (length(colnames(x)) > 0) { + # %% are important to distinguish between potentially redundant data rows + header[length(header)] <- paste(header[length(header)], "\\midrule %% TinyTableHeader") + } } - } - - # body: finish - idx <- grep("\\$tinytable_BODY", template) - out <- c( - template[1:(idx - 1)], - header, - body, - template[(idx + 1):length(template)] - ) - out <- trimws(out) - out <- paste(out, collapse = "\n") + # body: finish + idx <- grep("\\$tinytable_BODY", template) + out <- c( + template[1:(idx - 1)], + header, + body, + template[(idx + 1):length(template)] + ) - if (length(x@caption) > 0) { - spec <- sprintf("caption={%s},", x@caption[1]) - out <- tabularray_insert(out, content = spec, type = "outer") - } + out <- trimws(out) + out <- paste(out, collapse = "\n") - if (length(x@width) == 0) { - tabularray_cols <- rep("Q[]", ncol(x)) - - } else if (length(x@width) == 1) { - tabularray_cols <- rep("X[]", ncol(x)) - spec <- sprintf("width={%s\\linewidth},", round(x@width, 4)) - out <- tabularray_insert(out, content = spec, type = "inner") + if (length(x@caption) > 0) { + spec <- sprintf("caption={%s},", x@caption[1]) + out <- tabularray_insert(out, content = spec, type = "outer") + } - } else if (length(x@width) > 1) { - tabularray_cols <- sprintf("X[%s]", x@width) - spec <- sprintf("width={%s\\linewidth},", round(sum(x@width), 4)) - out <- tabularray_insert(out, content = spec, type = "inner") - } + if (length(x@width) == 0) { + tabularray_cols <- rep("Q[]", ncol(x)) + } else if (length(x@width) == 1) { + tabularray_cols <- rep("X[]", ncol(x)) + spec <- sprintf("width={%s\\linewidth},", round(x@width, 4)) + out <- tabularray_insert(out, content = spec, type = "inner") + } else if (length(x@width) > 1) { + tabularray_cols <- sprintf("X[%s]", x@width) + spec <- sprintf("width={%s\\linewidth},", round(sum(x@width), 4)) + out <- tabularray_insert(out, content = spec, type = "inner") + } - # colspec (we don't need rowspec) - colspec <- sprintf("colspec={%s},", paste(tabularray_cols, collapse = "")) - out <- tabularray_insert(out, content = colspec, type = "inner") + # colspec (we don't need rowspec) + colspec <- sprintf("colspec={%s},", paste(tabularray_cols, collapse = "")) + out <- tabularray_insert(out, content = colspec, type = "inner") - # notes - if (length(x@notes) > 0) { - if (length(x@caption) == 0) { + # notes + if (length(x@notes) > 0) { + if (length(x@caption) == 0) { # otherwise an empty caption is created automatically out <- tabularray_insert(out, content = "entry=none,label=none", type = "outer") - } - if (is.null(names(x@notes))) { - lab <- sapply(seq_along(x@notes), function(k) strrep(" ", k - 1)) - } else { - lab <- NULL - pad <- 0 - for (i in seq_along(x@notes)) { - # tabularray requires unique labels, but multiple blanks work - if (names(x@notes)[i] == "") { - lab[i] <- strrep(" ", pad) # not sure why -1 is necessary in tabularray - pad <- pad + 1 - } else { - lab[i] <- names(x@notes)[i] + } + if (is.null(names(x@notes))) { + lab <- sapply(seq_along(x@notes), function(k) strrep(" ", k - 1)) + } else { + lab <- NULL + pad <- 0 + for (i in seq_along(x@notes)) { + # tabularray requires unique labels, but multiple blanks work + if (names(x@notes)[i] == "") { + lab[i] <- strrep(" ", pad) # not sure why -1 is necessary in tabularray + pad <- pad + 1 + } else { + lab[i] <- names(x@notes)[i] + } } } + notes <- sapply(x@notes, function(n) if (is.list(n)) n$text else n) + for (k in seq_along(notes)) { + spec <- sprintf("note{%s}={%s}", lab[k], notes[k]) + out <- tabularray_insert(out, content = spec, type = "outer") + } } - notes <- sapply(x@notes, function(n) if (is.list(n)) n$text else n) - for (k in seq_along(notes)) { - spec <- sprintf("note{%s}={%s}", lab[k], notes[k]) - out <- tabularray_insert(out, content = spec, type = "outer") - } - } - - if (isTRUE(tall)) { - out <- sub("\\begin{tblr}", "\\begin{talltblr}", out, fixed = TRUE) - out <- sub("\\end{tblr}", "\\end{talltblr}", out, fixed = TRUE) - } - x@table_string <- out - x@body <- body - - return(x) -}) + if (isTRUE(tall)) { + out <- sub("\\begin{tblr}", "\\begin{talltblr}", out, fixed = TRUE) + out <- sub("\\end{tblr}", "\\end{talltblr}", out, fixed = TRUE) + } + x@table_string <- out + x@body <- body + return(x) + } +) diff --git a/R/tt_typst.R b/R/tt_typst.R index 1cd347c9..b41530dd 100644 --- a/R/tt_typst.R +++ b/R/tt_typst.R @@ -2,86 +2,95 @@ setMethod( f = "tt_eval", signature = "tinytable_typst", definition = function(x, ...) { - out <- readLines(system.file("templates/typst.typ", package = "tinytable")) - out <- paste(out, collapse = "\n") + out <- readLines(system.file("templates/typst.typ", package = "tinytable")) + out <- paste(out, collapse = "\n") - # body - body <- apply(x@table_dataframe, 2, function(k) paste0("[", k, "]")) - if (nrow(x@table_dataframe) && is.null(dim(body))) { - body <- matrix(body) - } - header <- !is.null(colnames(x)) && length(colnames(x)) > 0 - if (header) { - header <- paste(paste0("[", colnames(x), "]"), collapse = ", ") - header <- paste0(header, ",") - out <- lines_insert(out, header, "repeat: true", "after") - } - body <- apply(body, 1, paste, collapse = ", ", simplify = FALSE) - body <- paste(body, collapse = ",\n") - body <- paste0(body, ",\n") - out <- typst_insert(out, body, type = "body") + # body + body <- apply(x@table_dataframe, 2, function(k) paste0("[", k, "]")) + if (nrow(x@table_dataframe) && is.null(dim(body))) { + body <- matrix(body) + } + header <- !is.null(colnames(x)) && length(colnames(x)) > 0 + if (header) { + header <- paste(paste0("[", colnames(x), "]"), collapse = ", ") + header <- paste0(header, ",") + out <- lines_insert(out, header, "repeat: true", "after") + } + body <- apply(body, 1, paste, collapse = ", ", simplify = FALSE) + body <- paste(body, collapse = ",\n") + body <- paste0(body, ",\n") + out <- typst_insert(out, body, type = "body") - if (length(x@width) == 0) { - width <- rep("auto", ncol(x)) - } else if (length(x@width) == 1) { - width <- rep(sprintf("%.2f%%", x@width / ncol(x) * 100), ncol(x)) - } else { - width <- sprintf("%.2f%%", x@width * 100) - } - width <- sprintf(" columns: (%s),", paste(width, collapse = ", ")) - out <- lines_insert(out, width, "tinytable table start", "after") + if (length(x@width) == 0) { + width <- rep("auto", ncol(x)) + } else if (length(x@width) == 1) { + width <- rep(sprintf("%.2f%%", x@width / ncol(x) * 100), ncol(x)) + } else { + width <- sprintf("%.2f%%", x@width * 100) + } + width <- sprintf(" columns: (%s),", paste(width, collapse = ", ")) + out <- lines_insert(out, width, "tinytable table start", "after") - # notes - if (length(x@notes) > 0) { - ft <- " + # notes + if (length(x@notes) > 0) { + ft <- " table.footer( repeat: false, // tinytable notes after ), " - out <- lines_insert(out, ft, "tinytable footer after", "after") - notes <- rev(x@notes) - # otherwise an empty caption is created automatically - if (is.null(names(notes))) { - lab <- rep("", length(notes)) - } else { - lab <- names(notes) - } - notes <- sapply(notes, function(n) if (is.list(n)) n$text else n) - for (k in seq_along(notes)) { - if (lab[k] == "") { - tmp <- sprintf(" table.cell(align: left, colspan: %s, [%s]),", ncol(x), notes[k]) + out <- lines_insert(out, ft, "tinytable footer after", "after") + notes <- rev(x@notes) + # otherwise an empty caption is created automatically + if (is.null(names(notes))) { + lab <- rep("", length(notes)) } else { - tmp <- sprintf(" table.cell(align: left, colspan: %s, [#super[%s] %s]),", ncol(x), lab[k], notes[k]) + lab <- names(notes) + } + notes <- sapply(notes, function(n) if (is.list(n)) n$text else n) + for (k in seq_along(notes)) { + if (lab[k] == "") { + tmp <- sprintf(" table.cell(align: left, colspan: %s, %s),", ncol(x), notes[k]) + } else { + n <- notes[k] + l <- sprintf("[#super[%s] ", lab[k]) + n <- sub("[", l, n, fixed = TRUE) + tmp <- sprintf(" table.cell(align: left, colspan: %s, %s),", ncol(x), n) + } + tmp <- sub("text(, ", "text(", tmp, fixed = TRUE) + out <- lines_insert(out, tmp, "tinytable notes after", "after") } - out <- lines_insert(out, tmp, "tinytable notes after", "after") } - } - # default alignment - align_default <- sprintf( - " #let align-default-array = ( %s, ) // tinytable align-default-array here", - paste(rep("left", ncol(x)), collapse = ", ")) - out <- lines_insert( - out, - align_default, - "// tinytable align-default-array before", - "after") + # default alignment + align_default <- sprintf( + " #let align-default-array = ( %s, ) // tinytable align-default-array here", + paste(rep("left", ncol(x)), collapse = ", ") + ) + out <- lines_insert( + out, + align_default, + "// tinytable align-default-array before", + "after" + ) - x@table_string <- out + x@table_string <- out - return(x) -}) + return(x) + } +) typst_insert <- function(x, content = NULL, type = "body") { - if (is.null(content)) return(x) + if (is.null(content)) { + return(x) + } out <- strsplit(x, "\n")[[1]] comment <- switch(type, - "lines" = "tinytable lines before", - "style" = "tinytable cell style before", - "body" = "tinytable cell content after" + "lines" = "tinytable lines before", + "style" = "tinytable cell style before", + "body" = "tinytable cell content after" ) idx <- grep(comment, out) diff --git a/R/utils.R b/R/utils.R index 70bc5435..39f5bdcf 100644 --- a/R/utils.R +++ b/R/utils.R @@ -36,7 +36,7 @@ lines_drop_consecutive_empty <- function(x) { lines <- strsplit(x, "\n")[[1]] tmp <- rle(lines) tmp$lengths[trimws(tmp$values) == ""] <- 1 - lines <- inverse.rle(tmp) + lines <- inverse.rle(tmp) x <- paste0(lines, collapse = "\n") return(x) } @@ -78,7 +78,7 @@ lines_drop_between <- function(text, regex_start, regex_end, fixed = FALSE) { if (idx_start >= idx_end) { stop("`regex_start` matches a line after `regex_end`.", call. = FALSE) } - lines_to_keep <- c(1:(idx_start-1), (idx_end+1):length(lines)) + lines_to_keep <- c(1:(idx_start - 1), (idx_end + 1):length(lines)) output <- lines[lines_to_keep] out <- paste(output, collapse = "\n") return(out) @@ -86,19 +86,19 @@ lines_drop_between <- function(text, regex_start, regex_end, fixed = FALSE) { lines_insert <- function(old, new, regex, position = "before") { - lines <- strsplit(old, "\n")[[1]] - idx <- grep(regex, lines) - if (length(idx) != 1 || anyNA(idx)) { - stop("The `regex` supplied `lines_insert()` did not match a unique line.", call. = FALSE) - } - if (position == "before") { - top <- lines[1:(idx - 1)] - bot <- lines[idx:length(lines)] - } else if (position == "after") { - top <- lines[1:idx] - bot <- lines[(idx + 1):length(lines)] - } - lines <- c(top, new, bot) - out <- paste(lines, collapse = "\n") - return(out) + lines <- strsplit(old, "\n")[[1]] + idx <- grep(regex, lines) + if (length(idx) != 1 || anyNA(idx)) { + stop("The `regex` supplied `lines_insert()` did not match a unique line.", call. = FALSE) + } + if (position == "before") { + top <- lines[1:(idx - 1)] + bot <- lines[idx:length(lines)] + } else if (position == "after") { + top <- lines[1:idx] + bot <- lines[(idx + 1):length(lines)] + } + lines <- c(top, new, bot) + out <- paste(lines, collapse = "\n") + return(out) } diff --git a/R/zzz.R b/R/zzz.R index add21f67..d4564bd9 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -1,5 +1,8 @@ -.onLoad <- function(libname, pkgname) { - if(requireNamespace("knitr", quietly = TRUE)) { - registerS3method("knit_print", "tinytable", knit_print.tinytable, envir = asNamespace("knitr")) - } -} +# replaced this with @rawNamespace S3method(knitr::knit_print, tinytable) in print.R + + +# .onLoad <- function(libname, pkgname) { +# if (requireNamespace("knitr", quietly = TRUE)) { +# registerS3method("knit_print", "tinytable", knit_print.tinytable, envir = asNamespace("knitr")) +# } +# } diff --git a/README.md b/README.md index 32116079..17a7fe8c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@

+
@@ -12,7 +13,7 @@ ## What? `tinytable` is a small but powerful `R` package to draw beautiful tables -in a variety of formats: HTML, LaTeX, Word, PDF, PNG, Markdown, and +in a variety of formats: HTML, LaTeX, Word[^1], PDF, PNG, Markdown, and Typst. The user interface is minimalist and easy to learn, while giving users access to powerful frameworks to create endlessly customizable tables. @@ -26,25 +27,24 @@ ecosystem. Why release a new one? As [the maintainer of `modelsummary`](https://modelsummary.com), I needed a table-drawing package which was: -- *Simple*: Streamlined, consistent, and uncluttered user interface, - with few functions to learn. -- *Flexible*: Expressive frameworks to customize tables in HTML and - LaTeX formats.[1] -- *Zero-dependency*: Avoid importing any other `R` package.[2] -- *Concise*: Draw beautiful tables without typing a lot of code. -- *Safe*: User inputs are checked thoroughly, and informative errors - are returned early. -- *Maintainable*: A small code base which does not rely on too many - complex regular expressions. -- *Readable*: HTML and LaTeX code should be human-readable and - editable. -- *Free*: This package will always be free. Tiny tables for a tiny - price! +- *Simple*: Streamlined, consistent, and uncluttered user interface, + with few functions to learn. +- *Flexible*: Expressive frameworks to customize tables in HTML and + LaTeX formats.[^2] +- *Zero-dependency*: Avoid importing any other `R` package.[^3] +- *Concise*: Draw beautiful tables without typing a lot of code. +- *Safe*: User inputs are checked thoroughly, and informative errors are + returned early. +- *Maintainable*: A small code base which does not rely on too many + complex regular expressions. +- *Readable*: HTML and LaTeX code should be human-readable and editable. +- *Free*: This package will always be free. Tiny tables for a tiny + price! To achieve these goals, the design philosophy of `tinytable` rests on three pillars: -1. *Data is separate from style.* The code that this package creates +1) *Data is separate from style.* The code that this package creates keeps the content of a table separate from the style sheet that applies to its cells. This is in contrast to other `R` packages that modify the actual text in each cell to style it. Keeping data and @@ -53,13 +53,13 @@ three pillars: developers to keep a simpler code base, with minimal use of messy regular expressions. -2. *Flexibility.* Users’ needs are extremely varied, and a +2) *Flexibility.* Users’ needs are extremely varied, and a table-drawing package must be flexible enough to accomodate different ideas. To achieve this, `tinytable` builds on battle-tested and versatile frameworks like `Bootstrap` for HTML and `tabularray` for LaTeX. -3. [*Lightweight is the right weight.*](https://www.tinyverse.org/) +3) [*Lightweight is the right weight.*](https://www.tinyverse.org/) Some of the most popular table-drawing packages in the `R` ecosystem are very heavy: A single `library()` call can sometimes load upwards of 65 `R` packages. In contrast, `tinytable` imports zero 3rd party @@ -131,29 +131,34 @@ tt(x, ## Tutorial -The `tinytable` 0.5.0.1 tutorial will take you much further. It is +The `tinytable` 0.6.1.3 tutorial will take you much further. It is available in two formats: -- [Tutorial - (PDF)](https://vincentarelbundock.github.io/tinytable/vignettes/tinytable_tutorial.pdf) -- Tutorial (HTML): - - [Tiny - tables](https://vincentarelbundock.github.io/tinytable/vignettes/tinytable.html) - - [Format](https://vincentarelbundock.github.io/tinytable/vignettes/format.html) - - [Style](https://vincentarelbundock.github.io/tinytable/vignettes/style.html) - - [Group - labels](https://vincentarelbundock.github.io/tinytable/vignettes/group.html) - - [Plots and - images](https://vincentarelbundock.github.io/tinytable/vignettes/plot.html) - - [Themes](https://vincentarelbundock.github.io/tinytable/vignettes/theme.html) - - [Customization](https://vincentarelbundock.github.io/tinytable/vignettes/custom.html) - - [FAQ](https://vincentarelbundock.github.io/tinytable/vignettes/faq.html) - - [Alternatives](https://vincentarelbundock.github.io/tinytable/vignettes/alternatives.html) - -[1] Other formats like Markdown and Typst are also available, but less -flexible. - -[2] Some extra packages can be imported to access specific -functionality, such as integration with Quarto, inserting `ggplot2` -objects as inline plots, and saving tables to PNG images or PDF -documents. +- [Tutorial + (PDF)](https://vincentarelbundock.github.io/tinytable/vignettes/tinytable_tutorial.pdf) +- Tutorial (HTML): + - [Tiny + tables](https://vincentarelbundock.github.io/tinytable/vignettes/tinytable.html) + - [Format](https://vincentarelbundock.github.io/tinytable/vignettes/format.html) + - [Style](https://vincentarelbundock.github.io/tinytable/vignettes/style.html) + - [Group + labels](https://vincentarelbundock.github.io/tinytable/vignettes/group.html) + - [Plots and + images](https://vincentarelbundock.github.io/tinytable/vignettes/plot.html) + - [Themes](https://vincentarelbundock.github.io/tinytable/vignettes/theme.html) + - [Notebooks (Quarto, Rmarkdown, Bookdown, + etc.)](https://vincentarelbundock.github.io/tinytable/vignettes/notebooks.html) + - [Customization](https://vincentarelbundock.github.io/tinytable/vignettes/custom.html) + - [FAQ](https://vincentarelbundock.github.io/tinytable/vignettes/faq.html) + - [Alternatives](https://vincentarelbundock.github.io/tinytable/vignettes/alternatives.html) + +[^1]: Styling options in Word are somewhat limited. See the FAQ page and + the `style_tt()` documentation for details. + +[^2]: Other formats like Markdown and Typst are also available, but less + flexible. + +[^3]: Some extra packages can be imported to access specific + functionality, such as integration with Quarto, inserting `ggplot2` + objects as inline plots, and saving tables to PNG images or PDF + documents. diff --git a/README.qmd b/README.qmd index 779999ee..6725cde1 100644 --- a/README.qmd +++ b/README.qmd @@ -1,4 +1,6 @@ - +--- +format: gfm +---

@@ -12,7 +14,7 @@ ## What? -`tinytable` is a small but powerful `R` package to draw beautiful tables in a variety of formats: HTML, LaTeX, Word, PDF, PNG, Markdown, and Typst. The user interface is minimalist and easy to learn, while giving users access to powerful frameworks to create endlessly customizable tables. +`tinytable` is a small but powerful `R` package to draw beautiful tables in a variety of formats: HTML, LaTeX, Word^[Styling options in Word are somewhat limited. See the FAQ page and the `style_tt()` documentation for details.], PDF, PNG, Markdown, and Typst. The user interface is minimalist and easy to learn, while giving users access to powerful frameworks to create endlessly customizable tables. @@ -20,10 +22,10 @@ ```{r, include=FALSE} db <- tools::CRAN_package_db() -dep_ke <- tools::package_dependencies(c("kableExtra"), recursive=TRUE, db=db)[[1]] |> length() -dep_hux <- tools::package_dependencies(c("huxtable"), recursive=TRUE, db=db)[[1]] |> length() -dep_dt <- tools::package_dependencies(c("DT"), recursive=TRUE, db=db)[[1]] |> length() -dep_gt <- tools::package_dependencies(c("gt"), recursive=TRUE, db=db)[[1]] |> length() +dep_ke <- tools::package_dependencies(c("kableExtra"), recursive = TRUE, db = db)[[1]] |> length() +dep_hux <- tools::package_dependencies(c("huxtable"), recursive = TRUE, db = db)[[1]] |> length() +dep_dt <- tools::package_dependencies(c("DT"), recursive = TRUE, db = db)[[1]] |> length() +dep_gt <- tools::package_dependencies(c("gt"), recursive = TRUE, db = db)[[1]] |> length() ``` There are already many excellent table-drawing packages in the `R` ecosystem. Why release a new one? As [the maintainer of `modelsummary`](https://modelsummary.com), I needed a table-drawing package which was: @@ -117,6 +119,7 @@ The `tinytable` `r packageVersion("tinytable")` tutorial will take you much furt - [Group labels](https://vincentarelbundock.github.io/tinytable/vignettes/group.html) - [Plots and images](https://vincentarelbundock.github.io/tinytable/vignettes/plot.html) - [Themes](https://vincentarelbundock.github.io/tinytable/vignettes/theme.html) + - [Notebooks (Quarto, Rmarkdown, Bookdown, etc.)](https://vincentarelbundock.github.io/tinytable/vignettes/notebooks.html) - [Customization](https://vincentarelbundock.github.io/tinytable/vignettes/custom.html) - [FAQ](https://vincentarelbundock.github.io/tinytable/vignettes/faq.html) - [Alternatives](https://vincentarelbundock.github.io/tinytable/vignettes/alternatives.html) diff --git a/altdoc/quarto_website.yml b/altdoc/quarto_website.yml index 3db87d35..85d6660d 100644 --- a/altdoc/quarto_website.yml +++ b/altdoc/quarto_website.yml @@ -20,7 +20,7 @@ website: - vignettes/plot.qmd - vignettes/theme.qmd - vignettes/custom.qmd - - vignettes/options.qmd + - vignettes/notebooks.qmd - vignettes/faq.qmd - text: Tutorial (PDF) file: vignettes/tinytable_tutorial.pdf @@ -34,24 +34,26 @@ website: contents: - section: Tutorial contents: - - text: Tiny tables - file: vignettes/tinytable.qmd - - text: Format - file: vignettes/format.qmd - - text: Style - file: vignettes/style.qmd - - text: Group labels - file: vignettes/group.qmd - - text: Plots and images - file: vignettes/plot.qmd - - text: Themes - file: vignettes/theme.qmd - - text: Customization - file: vignettes/custom.qmd - - text: FAQ - file: vignettes/faq.qmd - - text: Alternatives - file: vignettes/alternatives.qmd + - text: Tiny tables + file: vignettes/tinytable.qmd + - text: Format + file: vignettes/format.qmd + - text: Style + file: vignettes/style.qmd + - text: Group labels + file: vignettes/group.qmd + - text: Plots and images + file: vignettes/plot.qmd + - text: Themes + file: vignettes/theme.qmd + - text: Customization + file: vignettes/custom.qmd + - text: Notebooks + file: vignettes/notebooks.qmd + - text: FAQ + file: vignettes/faq.qmd + - text: Alternatives + file: vignettes/alternatives.qmd - text: "Tutorial (PDF)" file: vignettes/tinytable_tutorial.pdf - section: Functions diff --git a/inst/templates/typst.typ b/inst/templates/typst.typ index f5bb8e1e..1fddd737 100644 --- a/inst/templates/typst.typ +++ b/inst/templates/typst.typ @@ -42,27 +42,19 @@ block[ // start block #table( // tinytable table start stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, // tinytable lines before diff --git a/inst/tinytest/_tinysnapshot/docx-issue98_01.txt b/inst/tinytest/_tinysnapshot/docx-issue98_01.txt index 46ab5adf..eed3351e 100644 --- a/inst/tinytest/_tinysnapshot/docx-issue98_01.txt +++ b/inst/tinytest/_tinysnapshot/docx-issue98_01.txt @@ -7,7 +7,7 @@ +------+-----+------+-----+------+ | 21.0 | 6 | 160 | 110 | 3.90 | +------+-----+------+-----+------+ -| 22.8 | 4 | 108 | 93 | 3.85 | +| 22.8 | 4 | 108 | 93 | 3.85 | +------+-----+------+-----+------+ | 21.4 | 6 | 258 | 110 | 3.08 | +------+-----+------+-----+------+ diff --git a/inst/tinytest/_tinysnapshot/docx-issue98_02.txt b/inst/tinytest/_tinysnapshot/docx-issue98_02.txt index 8f4baa5a..023da336 100644 --- a/inst/tinytest/_tinysnapshot/docx-issue98_02.txt +++ b/inst/tinytest/_tinysnapshot/docx-issue98_02.txt @@ -1,12 +1,12 @@ -+-----------+-----+------+-----+------+ -| mpg | cyl | disp | hp | drat | -+===========+=====+======+=====+======+ -| $\sigma$ | 6 | 160 | 110 | 3.90 | -+-----------+-----+------+-----+------+ -| 21 | 6 | 160 | 110 | 3.90 | -+-----------+-----+------+-----+------+ -| 22.8 | 4 | 108 | 93 | 3.85 | -+-----------+-----+------+-----+------+ -| 21.4 | 6 | 258 | 110 | 3.08 | -+-----------+-----+------+-----+------+ ++----------+-----+------+-----+------+ +| mpg | cyl | disp | hp | drat | ++==========+=====+======+=====+======+ +| $\sigma$ | 6 | 160 | 110 | 3.90 | ++----------+-----+------+-----+------+ +| 21 | 6 | 160 | 110 | 3.90 | ++----------+-----+------+-----+------+ +| 22.8 | 4 | 108 | 93 | 3.85 | ++----------+-----+------+-----+------+ +| 21.4 | 6 | 258 | 110 | 3.08 | ++----------+-----+------+-----+------+ diff --git a/inst/tinytest/_tinysnapshot/docx-issue98_03.txt b/inst/tinytest/_tinysnapshot/docx-issue98_03.txt index e57ef8e7..e4204181 100644 --- a/inst/tinytest/_tinysnapshot/docx-issue98_03.txt +++ b/inst/tinytest/_tinysnapshot/docx-issue98_03.txt @@ -1,12 +1,12 @@ -+-----------+-----+------+-----+------+ -| $\sigma$ | cyl | disp | hp | drat | -+===========+=====+======+=====+======+ -| $\sigma$ | 6 | 160 | 110 | 3.90 | -+-----------+-----+------+-----+------+ -| 21 | 6 | 160 | 110 | 3.90 | -+-----------+-----+------+-----+------+ -| 22.8 | 4 | 108 | 93 | 3.85 | -+-----------+-----+------+-----+------+ -| 21.4 | 6 | 258 | 110 | 3.08 | -+-----------+-----+------+-----+------+ ++----------+-----+------+-----+------+ +| $\sigma$ | cyl | disp | hp | drat | ++==========+=====+======+=====+======+ +| $\sigma$ | 6 | 160 | 110 | 3.90 | ++----------+-----+------+-----+------+ +| 21 | 6 | 160 | 110 | 3.90 | ++----------+-----+------+-----+------+ +| 22.8 | 4 | 108 | 93 | 3.85 | ++----------+-----+------+-----+------+ +| 21.4 | 6 | 258 | 110 | 3.08 | ++----------+-----+------+-----+------+ diff --git a/inst/tinytest/_tinysnapshot/docx-issue98_04.txt b/inst/tinytest/_tinysnapshot/docx-issue98_04.txt index 7b7ca7b3..19db6fdd 100644 --- a/inst/tinytest/_tinysnapshot/docx-issue98_04.txt +++ b/inst/tinytest/_tinysnapshot/docx-issue98_04.txt @@ -6,7 +6,7 @@ +----------+-----+------+-----+------+ | 21 | 6 | 160 | 110 | 3.90 | +----------+-----+------+-----+------+ -| 22.8 | 4 | 108 | 93 | 3.85 | +| 22.8 | 4 | 108 | 93 | 3.85 | +----------+-----+------+-----+------+ | 21.4 | 6 | 258 | 110 | 3.08 | +----------+-----+------+-----+------+ diff --git a/inst/tinytest/_tinysnapshot/format_tt-vignette_html_markdown.html b/inst/tinytest/_tinysnapshot/format_tt-vignette_html_markdown.html index ada79f99..2465ff75 100644 --- a/inst/tinytest/_tinysnapshot/format_tt-vignette_html_markdown.html +++ b/inst/tinytest/_tinysnapshot/format_tt-vignette_html_markdown.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 2, j: 0 }, ], css_id: 'tinytable_css_ps3hrarwxnclv9tvdcq0',}, + { positions: [ { i: 0, j: 0 }, ], css_id: 'tinytable_css_ps3hrarwxnclv9tvdcq0',}, + { positions: [ { i: 2, j: 0 }, ], css_id: 'tinytable_css_fe9hmaas4mta0vfcevu8',}, { positions: [ { i: 1, j: 0 }, ], css_id: 'tinytable_css_9jxgyitf4or5kg1sue01',}, ]; @@ -77,7 +78,8 @@

diff --git a/inst/tinytest/_tinysnapshot/group_tt-3level.md b/inst/tinytest/_tinysnapshot/group_tt-3level.md index 738e2465..85b85238 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-3level.md +++ b/inst/tinytest/_tinysnapshot/group_tt-3level.md @@ -11,5 +11,5 @@ +------+-----+------+-----+------+ | 21.0 | 6 | 160 | 110 | 3.90 | +------+-----+------+-----+------+ -| 22.8 | 4 | 108 | 93 | 3.85 | +| 22.8 | 4 | 108 | 93 | 3.85 | +------+-----+------+-----+------+ diff --git a/inst/tinytest/_tinysnapshot/group_tt-3level.tex b/inst/tinytest/_tinysnapshot/group_tt-3level.tex index 88113122..fe4dea48 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-3level.tex +++ b/inst/tinytest/_tinysnapshot/group_tt-3level.tex @@ -18,7 +18,7 @@ mpg & cyl & disp & hp & drat \\ \midrule %% TinyTableHeader 21.0 & 6 & 160 & 110 & 3.90 \\ 21.0 & 6 & 160 & 110 & 3.90 \\ -22.8 & 4 & 108 & 93 & 3.85 \\ +22.8 & 4 & 108 & 93 & 3.85 \\ \bottomrule \end{tblr} \end{table} diff --git a/inst/tinytest/_tinysnapshot/group_tt-3level.typ b/inst/tinytest/_tinysnapshot/group_tt-3level.typ index 7db8b309..8d62befd 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-3level.typ +++ b/inst/tinytest/_tinysnapshot/group_tt-3level.typ @@ -46,31 +46,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 7, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 3, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 4, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 4, start: 0, end: 5, stroke: 0.05em + black), + table.hline(y: 7, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( @@ -84,7 +77,7 @@ table.cell(stroke: (bottom: .05em + black), colspan: 2, align: center)[c],table. // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/group_tt-html_tutorial_01.html b/inst/tinytest/_tinysnapshot/group_tt-html_tutorial_01.html index eb6bfc04..8a06a8a2 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-html_tutorial_01.html +++ b/inst/tinytest/_tinysnapshot/group_tt-html_tutorial_01.html @@ -65,8 +65,9 @@ var cellsToStyle = [ // tinytable style arrays after { positions: [ { i: 0, j: 0 }, { i: 0, j: 4 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 13, j: 3 }, { i: 13, j: 2 }, { i: 13, j: 1 }, { i: 13, j: 4 }, ], css_id: 'tinytable_css_iox90hlcz6p88f470o4c',}, { positions: [ { i: 5, j: 0 }, { i: 6, j: 0 }, { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 9, j: 0 }, { i: 11, j: 0 }, { i: 7, j: 0 }, { i: 8, j: 0 }, { i: 12, j: 0 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, - { positions: [ { i: 1, j: 0 }, { i: 13, j: 2 }, { i: 13, j: 1 }, { i: 1, j: 2 }, { i: 1, j: 1 }, { i: 1, j: 4 }, { i: 1, j: 3 }, { i: 13, j: 4 }, { i: 13, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 1, j: 0 }, { i: 1, j: 4 }, { i: 1, j: 3 }, { i: 1, j: 2 }, { i: 1, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, { positions: [ { i: 0, j: 2 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_87pizrt6gpue7tq68k7m',}, { positions: [ { i: 13, j: 0 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; @@ -82,10 +83,11 @@
@@ -125,7 +127,7 @@
- + @@ -160,14 +162,14 @@ - + - + diff --git a/inst/tinytest/_tinysnapshot/group_tt-issue165_extra_row.txt b/inst/tinytest/_tinysnapshot/group_tt-issue165_extra_row.txt index b5143573..fbf04924 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-issue165_extra_row.txt +++ b/inst/tinytest/_tinysnapshot/group_tt-issue165_extra_row.txt @@ -9,7 +9,7 @@ +------------+-----+------+-----+ | **21.000** | *6* | 160 | 110 | +------------+-----+------+-----+ -| 22.800 | *4* | 108 | 93 | +| 22.800 | *4* | 108 | 93 | +------------+-----+------+-----+ | 21.400 | *6* | 258 | 110 | +------------+-----+------+-----+ diff --git a/inst/tinytest/_tinysnapshot/group_tt-issue165_html_centering_style.html b/inst/tinytest/_tinysnapshot/group_tt-issue165_html_centering_style.html index 98eac8bf..4ef77abd 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-issue165_html_centering_style.html +++ b/inst/tinytest/_tinysnapshot/group_tt-issue165_html_centering_style.html @@ -65,14 +65,16 @@ // tinytable style arrays after { positions: [ { i: 0, j: 1 }, ], css_id: 'tinytable_css_vaw2hfkppewiyp5c5w5m',}, { positions: [ { i: 0, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 7, j: 1 }, { i: 1, j: 1 }, ], css_id: 'tinytable_css_u5i4tb8acz516c5lsr29',}, - { positions: [ { i: 0, j: 2 }, { i: 0, j: 4 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_jelmvubahbw3b3gkec4r',}, + { positions: [ { i: 1, j: 1 }, ], css_id: 'tinytable_css_u5i4tb8acz516c5lsr29',}, + { positions: [ { i: 7, j: 1 }, ], css_id: 'tinytable_css_jelmvubahbw3b3gkec4r',}, { positions: [ { i: 7, j: 0 }, ], css_id: 'tinytable_css_iox90hlcz6p88f470o4c',}, { positions: [ { i: 2, j: 0 }, { i: 4, j: 0 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, - { positions: [ { i: 1, j: 0 }, { i: 7, j: 3 }, { i: 7, j: 2 }, { i: 1, j: 3 }, { i: 1, j: 2 }, { i: 1, j: 4 }, { i: 7, j: 4 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 1, j: 0 }, { i: 1, j: 4 }, { i: 1, j: 3 }, { i: 1, j: 2 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, { positions: [ { i: 5, j: 0 }, { i: 6, j: 0 }, ], css_id: 'tinytable_css_87pizrt6gpue7tq68k7m',}, + { positions: [ { i: 0, j: 2 }, { i: 0, j: 3 }, { i: 0, j: 4 }, ], css_id: 'tinytable_css_7eqhzcv7sizz32zmnli7',}, { positions: [ { i: 5, j: 1 }, { i: 2, j: 1 }, { i: 3, j: 1 }, { i: 4, j: 1 }, { i: 6, j: 1 }, ], css_id: 'tinytable_css_5ksktliasr5ex8ow1hyj',}, { positions: [ { i: 3, j: 0 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, + { positions: [ { i: 7, j: 3 }, { i: 7, j: 2 }, { i: 7, j: 4 }, ], css_id: 'tinytable_css_0gay8omxmz5hgo5gx59n',}, ]; // Loop over the arrays to style the cells @@ -86,16 +88,18 @@
%s%s
%s %s
%s %s
%s %s
%s %s
%s
%s
%s
%s
%s
%s
22.8 4 108.0 9393 3.85
24.4 4 146.7 6262 3.69
22.8 4 140.8 9595 3.92
diff --git a/inst/tinytest/_tinysnapshot/group_tt-issue258_01_html.html b/inst/tinytest/_tinysnapshot/group_tt-issue258_01_html.html index ee26f6c5..0abe661e 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-issue258_01_html.html +++ b/inst/tinytest/_tinysnapshot/group_tt-issue258_01_html.html @@ -63,9 +63,10 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 4, j: 0 }, { i: 5, j: 0 }, { i: 6, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 3, j: 0 }, { i: 5, j: 0 }, { i: 2, j: 0 }, { i: 4, j: 0 }, { i: 6, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, { positions: [ { i: 7, j: 0 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, - { positions: [ { i: 0, j: 0 }, { i: 0, j: 2 }, { i: 7, j: 2 }, { i: 0, j: 1 }, { i: 7, j: 1 }, { i: 0, j: 4 }, { i: 7, j: 4 }, { i: 0, j: 3 }, { i: 7, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 2 }, { i: 0, j: 1 }, { i: 0, j: 4 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 7, j: 1 }, { i: 7, j: 2 }, { i: 7, j: 3 }, { i: 7, j: 4 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -81,7 +82,8 @@ /* tinytable css entries after */ .table td.tinytable_css_ue01fe9hmaas4mta0vfc, .table th.tinytable_css_ue01fe9hmaas4mta0vfc { padding-left: 1em; } .table td.tinytable_css_evu8i6m1snsv5kmmasu3, .table th.tinytable_css_evu8i6m1snsv5kmmasu3 { padding-left: 1em; border-bottom: solid #d3d8dc 0.1em; } - .table td.tinytable_css_dcq09jxgyitf4or5kg1s, .table th.tinytable_css_dcq09jxgyitf4or5kg1s { border-bottom: solid #d3d8dc 0.1em; } + .table td.tinytable_css_dcq09jxgyitf4or5kg1s, .table th.tinytable_css_dcq09jxgyitf4or5kg1s { border-top: solid #d3d8dc 0.1em; border-bottom: solid #d3d8dc 0.05em; } + .table td.tinytable_css_5jsz1u1bau6rax203jg7, .table th.tinytable_css_5jsz1u1bau6rax203jg7 { border-bottom: solid #d3d8dc 0.1em; }
diff --git a/inst/tinytest/_tinysnapshot/group_tt-issue258_01_typst.txt b/inst/tinytest/_tinysnapshot/group_tt-issue258_01_typst.txt index 455cf232..1da1fb9a 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-issue258_01_typst.txt +++ b/inst/tinytest/_tinysnapshot/group_tt-issue258_01_typst.txt @@ -13,7 +13,7 @@ block[ // start block #let style-array = ( // tinytable cell style after (pairs: ((0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7),), indent: 1em,), -(pairs: ((0, 0), (0, 1), (0, 8), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8),), ), +(pairs: ((0, 0), (0, 1), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7),), ), ) // tinytable align-default-array before @@ -46,31 +46,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 8, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 5, stroke: 0.05em + black), + table.hline(y: 8, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( diff --git a/inst/tinytest/_tinysnapshot/group_tt-issue258_02_html.html b/inst/tinytest/_tinysnapshot/group_tt-issue258_02_html.html index d2a7811e..d53f3ea3 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-issue258_02_html.html +++ b/inst/tinytest/_tinysnapshot/group_tt-issue258_02_html.html @@ -64,9 +64,10 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 1, j: 0 }, { i: 4, j: 0 }, { i: 5, j: 0 }, { i: 6, j: 0 }, { i: 7, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 4, j: 0 }, { i: 6, j: 0 }, { i: 1, j: 0 }, { i: 5, j: 0 }, { i: 7, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, { positions: [ { i: 8, j: 0 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, - { positions: [ { i: 0, j: 0 }, { i: 0, j: 2 }, { i: 8, j: 2 }, { i: 0, j: 1 }, { i: 8, j: 1 }, { i: 0, j: 4 }, { i: 8, j: 4 }, { i: 0, j: 3 }, { i: 8, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 2 }, { i: 0, j: 1 }, { i: 0, j: 4 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 8, j: 1 }, { i: 8, j: 2 }, { i: 8, j: 3 }, { i: 8, j: 4 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -82,7 +83,8 @@ /* tinytable css entries after */ .table td.tinytable_css_ue01fe9hmaas4mta0vfc, .table th.tinytable_css_ue01fe9hmaas4mta0vfc { padding-left: 1em; } .table td.tinytable_css_evu8i6m1snsv5kmmasu3, .table th.tinytable_css_evu8i6m1snsv5kmmasu3 { padding-left: 1em; border-bottom: solid #d3d8dc 0.1em; } - .table td.tinytable_css_dcq09jxgyitf4or5kg1s, .table th.tinytable_css_dcq09jxgyitf4or5kg1s { border-bottom: solid #d3d8dc 0.1em; } + .table td.tinytable_css_dcq09jxgyitf4or5kg1s, .table th.tinytable_css_dcq09jxgyitf4or5kg1s { border-top: solid #d3d8dc 0.1em; border-bottom: solid #d3d8dc 0.05em; } + .table td.tinytable_css_5jsz1u1bau6rax203jg7, .table th.tinytable_css_5jsz1u1bau6rax203jg7 { border-bottom: solid #d3d8dc 0.1em; }
diff --git a/inst/tinytest/_tinysnapshot/group_tt-issue258_02_typst.txt b/inst/tinytest/_tinysnapshot/group_tt-issue258_02_typst.txt index c352e332..0e1c7e9e 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-issue258_02_typst.txt +++ b/inst/tinytest/_tinysnapshot/group_tt-issue258_02_typst.txt @@ -13,7 +13,7 @@ block[ // start block #let style-array = ( // tinytable cell style after (pairs: ((0, 1), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8),), indent: 1em,), -(pairs: ((0, 0), (0, 2), (0, 3), (0, 9), (0, 10), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10),), ), +(pairs: ((0, 0), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8),), ), ) // tinytable align-default-array before @@ -46,31 +46,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 9, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 5, stroke: 0.05em + black), + table.hline(y: 9, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( diff --git a/inst/tinytest/_tinysnapshot/group_tt-vector_row_labels.md b/inst/tinytest/_tinysnapshot/group_tt-vector_row_labels.md index c5ac09dc..89490c32 100644 --- a/inst/tinytest/_tinysnapshot/group_tt-vector_row_labels.md +++ b/inst/tinytest/_tinysnapshot/group_tt-vector_row_labels.md @@ -5,23 +5,23 @@ +-------------+------------+ | -0.65470589 | -0.1692089 | +-------------+------------+ -| -0.49824606 | 0.5763153 | +| -0.49824606 | 0.5763153 | +-------------+------------+ -| 0.33230864 | -0.5149627 | +| 0.33230864 | -0.5149627 | +-------------+------------+ | b | +-------------+------------+ -| 1.12146881 | -0.4805023 | +| 1.12146881 | -0.4805023 | +-------------+------------+ -| -0.06394603 | 0.7634626 | +| -0.06394603 | 0.7634626 | +-------------+------------+ | c | +-------------+------------+ -| 1.53760239 | 0.7914405 | +| 1.53760239 | 0.7914405 | +-------------+------------+ | a | +-------------+------------+ -| -0.11144127 | 1.7435388 | +| -0.11144127 | 1.7435388 | +-------------+------------+ -| 0.24231271 | 1.6937668 | +| 0.24231271 | 1.6937668 | +-------------+------------+ diff --git a/inst/tinytest/_tinysnapshot/html-alignment.html b/inst/tinytest/_tinysnapshot/html-alignment.html index 9f29e0b6..d11681da 100644 --- a/inst/tinytest/_tinysnapshot/html-alignment.html +++ b/inst/tinytest/_tinysnapshot/html-alignment.html @@ -62,12 +62,15 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 1 }, { i: 3, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 0, j: 0 }, { i: 3, j: 0 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 1, j: 1 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 3, j: 2 }, ], css_id: 'tinytable_css_vaw2hfkppewiyp5c5w5m',}, + { positions: [ { i: 3, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 1, j: 2 }, { i: 2, j: 2 }, ], css_id: 'tinytable_css_u5i4tb8acz516c5lsr29',}, + { positions: [ { i: 0, j: 0 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 2 }, ], css_id: 'tinytable_css_iox90hlcz6p88f470o4c',}, + { positions: [ { i: 0, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, { positions: [ { i: 1, j: 0 }, { i: 2, j: 0 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, - { positions: [ { i: 1, j: 2 }, { i: 2, j: 2 }, ], css_id: 'tinytable_css_87pizrt6gpue7tq68k7m',}, - { positions: [ { i: 0, j: 2 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, + { positions: [ { i: 3, j: 1 }, ], css_id: 'tinytable_css_87pizrt6gpue7tq68k7m',}, + { positions: [ { i: 1, j: 1 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -81,12 +84,15 @@
@@ -101,14 +107,14 @@ - - - + + + - - - + + + diff --git a/inst/tinytest/_tinysnapshot/html-bootstrap_css.html b/inst/tinytest/_tinysnapshot/html-bootstrap_css.html index b6c753e9..40006718 100644 --- a/inst/tinytest/_tinysnapshot/html-bootstrap_css.html +++ b/inst/tinytest/_tinysnapshot/html-bootstrap_css.html @@ -62,9 +62,11 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 1 }, { i: 4, j: 1 }, { i: 0, j: 2 }, { i: 4, j: 2 }, { i: 0, j: 3 }, { i: 4, j: 3 }, { i: 0, j: 4 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 0, j: 0 }, { i: 4, j: 0 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 4, j: 0 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 1 }, { i: 0, j: 2 }, { i: 0, j: 3 }, { i: 0, j: 4 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, { positions: [ { i: 1, j: 0 }, { i: 2, j: 0 }, { i: 3, j: 0 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 4, j: 1 }, { i: 4, j: 2 }, { i: 4, j: 3 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -78,9 +80,11 @@
a b c abc
aa bb cc aabbcc
aaa
@@ -114,7 +118,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-borders.html b/inst/tinytest/_tinysnapshot/html-borders.html index 46277ef6..573cb434 100644 --- a/inst/tinytest/_tinysnapshot/html-borders.html +++ b/inst/tinytest/_tinysnapshot/html-borders.html @@ -110,7 +110,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-caption.html b/inst/tinytest/_tinysnapshot/html-caption.html index 482c0c30..4ca263fe 100644 --- a/inst/tinytest/_tinysnapshot/html-caption.html +++ b/inst/tinytest/_tinysnapshot/html-caption.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 3, j: 0 }, { i: 0, j: 1 }, { i: 3, j: 1 }, { i: 0, j: 2 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 3, j: 0 }, { i: 3, j: 1 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
22.8 4 108 9393 3.85
22.8 4 108 9393 3.85
diff --git a/inst/tinytest/_tinysnapshot/html-conditional_styling.html b/inst/tinytest/_tinysnapshot/html-conditional_styling.html index e411f6c3..8f60dcc8 100644 --- a/inst/tinytest/_tinysnapshot/html-conditional_styling.html +++ b/inst/tinytest/_tinysnapshot/html-conditional_styling.html @@ -62,8 +62,9 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, { i: 10, j: 0 }, { i: 10, j: 1 }, { i: 10, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 7, j: 0 }, { i: 5, j: 1 }, { i: 7, j: 1 }, { i: 3, j: 0 }, { i: 5, j: 0 }, { i: 3, j: 2 }, { i: 5, j: 2 }, { i: 7, j: 2 }, { i: 3, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 10, j: 0 }, { i: 10, j: 1 }, { i: 10, j: 2 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 7, j: 0 }, { i: 7, j: 1 }, { i: 3, j: 0 }, { i: 5, j: 0 }, { i: 5, j: 1 }, { i: 5, j: 2 }, { i: 7, j: 2 }, { i: 3, j: 1 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -77,7 +78,8 @@
diff --git a/inst/tinytest/_tinysnapshot/html-font_size.html b/inst/tinytest/_tinysnapshot/html-font_size.html index 3a0ee3c4..246b0266 100644 --- a/inst/tinytest/_tinysnapshot/html-font_size.html +++ b/inst/tinytest/_tinysnapshot/html-font_size.html @@ -62,9 +62,11 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 4, j: 1 }, { i: 0, j: 2 }, { i: 4, j: 2 }, { i: 0, j: 1 }, { i: 0, j: 4 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 0, j: 0 }, { i: 0, j: 3 }, { i: 4, j: 0 }, { i: 4, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 1, j: 3 }, { i: 2, j: 3 }, { i: 3, j: 3 }, { i: 1, j: 0 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 4, j: 0 }, { i: 4, j: 3 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 4 }, { i: 0, j: 2 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 3, j: 3 }, { i: 1, j: 0 }, { i: 1, j: 3 }, { i: 2, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 4, j: 2 }, { i: 4, j: 1 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -78,9 +80,11 @@
@@ -114,7 +118,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-footnote.html b/inst/tinytest/_tinysnapshot/html-footnote.html index 954e904d..01e21546 100644 --- a/inst/tinytest/_tinysnapshot/html-footnote.html +++ b/inst/tinytest/_tinysnapshot/html-footnote.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 3, j: 0 }, { i: 0, j: 1 }, { i: 3, j: 1 }, { i: 0, j: 2 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 3, j: 0 }, { i: 3, j: 1 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
22.8 4 108 9393 3.85
diff --git a/inst/tinytest/_tinysnapshot/html-formatting.html b/inst/tinytest/_tinysnapshot/html-formatting.html index 70cfdb70..fde80143 100644 --- a/inst/tinytest/_tinysnapshot/html-formatting.html +++ b/inst/tinytest/_tinysnapshot/html-formatting.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 3, j: 0 }, { i: 0, j: 1 }, { i: 3, j: 1 }, { i: 0, j: 2 }, { i: 3, j: 2 }, { i: 0, j: 3 }, { i: 3, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 3, j: 0 }, { i: 3, j: 1 }, { i: 3, j: 2 }, { i: 3, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
@@ -93,19 +95,19 @@ - + - + - + - + diff --git a/inst/tinytest/_tinysnapshot/html-heatmap.html b/inst/tinytest/_tinysnapshot/html-heatmap.html index 63248244..eca60ce6 100644 --- a/inst/tinytest/_tinysnapshot/html-heatmap.html +++ b/inst/tinytest/_tinysnapshot/html-heatmap.html @@ -126,7 +126,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-images-portable.html b/inst/tinytest/_tinysnapshot/html-images-portable.html index db178a95..1c952edd 100644 --- a/inst/tinytest/_tinysnapshot/html-images-portable.html +++ b/inst/tinytest/_tinysnapshot/html-images-portable.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 2, j: 0 }, { i: 0, j: 1 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 2, j: 0 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
1430021.43 1.43 1972-09-26True True
201399 201.4 1971-11-07True True
1001880.13 0.13 1970-01-04 False
1 5 99 13 17
@@ -90,12 +92,12 @@ - - + + - +
bar bar
line
diff --git a/inst/tinytest/_tinysnapshot/html-images.html b/inst/tinytest/_tinysnapshot/html-images.html index 16685908..9c00d399 100644 --- a/inst/tinytest/_tinysnapshot/html-images.html +++ b/inst/tinytest/_tinysnapshot/html-images.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 2, j: 0 }, { i: 0, j: 1 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 2, j: 0 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
@@ -90,7 +92,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-individual_cells.html b/inst/tinytest/_tinysnapshot/html-individual_cells.html index 88dc91e5..d748a82f 100644 --- a/inst/tinytest/_tinysnapshot/html-individual_cells.html +++ b/inst/tinytest/_tinysnapshot/html-individual_cells.html @@ -62,8 +62,9 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 4, j: 1 }, { i: 0, j: 2 }, { i: 4, j: 0 }, { i: 0, j: 1 }, { i: 4, j: 2 }, { i: 0, j: 3 }, { i: 4, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 2, j: 2 }, { i: 3, j: 2 }, { i: 3, j: 0 }, { i: 2, j: 3 }, { i: 3, j: 3 }, { i: 2, j: 0 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 4, j: 1 }, { i: 4, j: 2 }, { i: 4, j: 0 }, { i: 4, j: 3 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 2 }, { i: 0, j: 1 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 2, j: 0 }, { i: 2, j: 2 }, { i: 2, j: 3 }, { i: 3, j: 2 }, { i: 3, j: 0 }, { i: 3, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -77,7 +78,8 @@
@@ -109,7 +111,7 @@
- + diff --git a/inst/tinytest/_tinysnapshot/html-issue297.txt b/inst/tinytest/_tinysnapshot/html-issue297.txt index 16685908..9c00d399 100644 --- a/inst/tinytest/_tinysnapshot/html-issue297.txt +++ b/inst/tinytest/_tinysnapshot/html-issue297.txt @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 2, j: 0 }, { i: 0, j: 1 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 2, j: 0 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
Spider Spider
22.8 4 108 9393
21.4
@@ -90,7 +92,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-issue58.html b/inst/tinytest/_tinysnapshot/html-issue58.html index 174ed324..b129762d 100644 --- a/inst/tinytest/_tinysnapshot/html-issue58.html +++ b/inst/tinytest/_tinysnapshot/html-issue58.html @@ -62,10 +62,11 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 2, j: 0 }, { i: 5, j: 0 }, { i: 6, j: 0 }, { i: 3, j: 0 }, { i: 4, j: 0 }, { i: 5, j: 1 }, { i: 2, j: 1 }, { i: 3, j: 1 }, { i: 4, j: 1 }, { i: 8, j: 0 }, { i: 6, j: 1 }, { i: 7, j: 1 }, { i: 7, j: 0 }, { i: 2, j: 3 }, { i: 2, j: 2 }, { i: 3, j: 2 }, { i: 4, j: 2 }, { i: 5, j: 2 }, { i: 6, j: 2 }, { i: 7, j: 2 }, { i: 8, j: 2 }, { i: 8, j: 1 }, { i: 9, j: 1 }, { i: 9, j: 0 }, { i: 10, j: 0 }, { i: 2, j: 4 }, { i: 3, j: 4 }, { i: 3, j: 3 }, { i: 4, j: 3 }, { i: 5, j: 3 }, { i: 6, j: 3 }, { i: 7, j: 3 }, { i: 8, j: 3 }, { i: 9, j: 3 }, { i: 9, j: 2 }, { i: 10, j: 2 }, { i: 10, j: 1 }, { i: 5, j: 4 }, { i: 6, j: 4 }, { i: 7, j: 4 }, { i: 4, j: 4 }, { i: 9, j: 4 }, { i: 10, j: 4 }, { i: 10, j: 3 }, { i: 8, j: 4 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 1, j: 0 }, { i: 11, j: 2 }, { i: 11, j: 1 }, { i: 11, j: 4 }, { i: 11, j: 3 }, { i: 1, j: 4 }, { i: 11, j: 0 }, { i: 1, j: 1 }, { i: 1, j: 3 }, { i: 1, j: 2 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 0, j: 4 }, { i: 0, j: 3 }, { i: 0, j: 2 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 4, j: 0 }, { i: 6, j: 0 }, { i: 7, j: 0 }, { i: 8, j: 0 }, { i: 5, j: 0 }, { i: 2, j: 1 }, { i: 3, j: 1 }, { i: 4, j: 1 }, { i: 5, j: 1 }, { i: 6, j: 1 }, { i: 7, j: 1 }, { i: 8, j: 1 }, { i: 9, j: 1 }, { i: 9, j: 0 }, { i: 10, j: 0 }, { i: 2, j: 4 }, { i: 2, j: 3 }, { i: 2, j: 2 }, { i: 3, j: 2 }, { i: 4, j: 2 }, { i: 5, j: 2 }, { i: 6, j: 2 }, { i: 7, j: 2 }, { i: 8, j: 2 }, { i: 9, j: 2 }, { i: 10, j: 2 }, { i: 10, j: 1 }, { i: 4, j: 3 }, { i: 5, j: 3 }, { i: 3, j: 4 }, { i: 3, j: 3 }, { i: 8, j: 3 }, { i: 9, j: 3 }, { i: 6, j: 3 }, { i: 7, j: 3 }, { i: 4, j: 4 }, { i: 5, j: 4 }, { i: 10, j: 3 }, { i: 7, j: 4 }, { i: 8, j: 4 }, { i: 9, j: 4 }, { i: 6, j: 4 }, { i: 10, j: 4 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 1, j: 0 }, { i: 1, j: 4 }, { i: 1, j: 3 }, { i: 1, j: 2 }, { i: 1, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 11, j: 3 }, { i: 11, j: 1 }, { i: 11, j: 0 }, { i: 11, j: 4 }, { i: 11, j: 2 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 0, j: 4 }, { i: 0, j: 3 }, { i: 0, j: 2 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -80,9 +81,10 @@
Spider Spider
diff --git a/inst/tinytest/_tinysnapshot/html-issue88.html b/inst/tinytest/_tinysnapshot/html-issue88.html index 02674bf3..c4794b81 100644 --- a/inst/tinytest/_tinysnapshot/html-issue88.html +++ b/inst/tinytest/_tinysnapshot/html-issue88.html @@ -62,8 +62,9 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, { i: 0, j: 3 }, { i: 10, j: 0 }, { i: 10, j: 1 }, { i: 10, j: 2 }, { i: 10, j: 3 }, { i: 0, j: 4 }, { i: 10, j: 4 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 4, j: 0 }, { i: 4, j: 2 }, { i: 2, j: 1 }, { i: 3, j: 1 }, { i: 4, j: 1 }, { i: 3, j: 3 }, { i: 4, j: 3 }, { i: 2, j: 2 }, { i: 3, j: 2 }, { i: 2, j: 4 }, { i: 3, j: 4 }, { i: 4, j: 4 }, { i: 2, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 10, j: 0 }, { i: 10, j: 1 }, { i: 10, j: 2 }, { i: 10, j: 3 }, { i: 10, j: 4 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, { i: 0, j: 3 }, { i: 0, j: 4 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 2, j: 0 }, { i: 3, j: 0 }, { i: 4, j: 0 }, { i: 4, j: 1 }, { i: 4, j: 2 }, { i: 2, j: 1 }, { i: 3, j: 1 }, { i: 3, j: 2 }, { i: 3, j: 3 }, { i: 4, j: 3 }, { i: 2, j: 2 }, { i: 2, j: 3 }, { i: 2, j: 4 }, { i: 3, j: 4 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -77,7 +78,8 @@
diff --git a/inst/tinytest/_tinysnapshot/html-issue92.html b/inst/tinytest/_tinysnapshot/html-issue92.html index c4a53297..ab538b55 100644 --- a/inst/tinytest/_tinysnapshot/html-issue92.html +++ b/inst/tinytest/_tinysnapshot/html-issue92.html @@ -62,9 +62,11 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 1, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 0, j: 0 }, { i: 2, j: 0 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 0, j: 1 }, { i: 2, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 0, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 0, j: 0 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 1, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 2, j: 0 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 2, j: 1 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -78,9 +80,11 @@
@@ -98,8 +102,8 @@ - - + +
Some text
123 456 123456
diff --git a/inst/tinytest/_tinysnapshot/html-line_break.html b/inst/tinytest/_tinysnapshot/html-line_break.html index 78395267..8bb65b36 100644 --- a/inst/tinytest/_tinysnapshot/html-line_break.html +++ b/inst/tinytest/_tinysnapshot/html-line_break.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 1, j: 0 }, { i: 0, j: 1 }, { i: 1, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 1, j: 0 }, { i: 1, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
diff --git a/inst/tinytest/_tinysnapshot/html-merge_cells.html b/inst/tinytest/_tinysnapshot/html-merge_cells.html index f06fcff0..c6c88717 100644 --- a/inst/tinytest/_tinysnapshot/html-merge_cells.html +++ b/inst/tinytest/_tinysnapshot/html-merge_cells.html @@ -63,8 +63,9 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 2, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 0, j: 0 }, { i: 4, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 3 }, { i: 4, j: 1 }, { i: 0, j: 2 }, { i: 4, j: 2 }, { i: 4, j: 3 }, { i: 0, j: 4 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 4, j: 1 }, { i: 4, j: 2 }, { i: 4, j: 3 }, { i: 4, j: 0 }, { i: 4, j: 4 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 2, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 2 }, { i: 0, j: 1 }, { i: 0, j: 3 }, { i: 0, j: 4 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -78,8 +79,9 @@
@@ -113,7 +115,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-missing_value.html b/inst/tinytest/_tinysnapshot/html-missing_value.html index a448ed63..d1d0da8f 100644 --- a/inst/tinytest/_tinysnapshot/html-missing_value.html +++ b/inst/tinytest/_tinysnapshot/html-missing_value.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 3, j: 0 }, { i: 0, j: 1 }, { i: 3, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 3, j: 0 }, { i: 3, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
22.8 4 108 9393 3.85
@@ -91,15 +93,15 @@ - + - + - - + +
- 33
11 -
2 525
diff --git a/inst/tinytest/_tinysnapshot/html-omit_headers.html b/inst/tinytest/_tinysnapshot/html-omit_headers.html index c9625d07..a66b9c24 100644 --- a/inst/tinytest/_tinysnapshot/html-omit_headers.html +++ b/inst/tinytest/_tinysnapshot/html-omit_headers.html @@ -62,7 +62,8 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 3, j: 0 }, { i: 3, j: 1 }, { i: 3, j: 2 }, { i: 3, j: 3 }, { i: 3, j: 4 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, { i: 0, j: 3 }, { i: 0, j: 4 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 3, j: 0 }, { i: 3, j: 1 }, { i: 3, j: 2 }, { i: 3, j: 3 }, { i: 3, j: 4 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, ]; // Loop over the arrays to style the cells @@ -76,7 +77,8 @@
@@ -103,7 +105,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-spanning_cells.html b/inst/tinytest/_tinysnapshot/html-spanning_cells.html index dd12a9ad..39bce58e 100644 --- a/inst/tinytest/_tinysnapshot/html-spanning_cells.html +++ b/inst/tinytest/_tinysnapshot/html-spanning_cells.html @@ -65,8 +65,9 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 6, j: 1 }, { i: 0, j: 2 }, { i: 6, j: 0 }, { i: 6, j: 2 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, - { positions: [ { i: 1, j: 0 }, { i: 3, j: 0 }, { i: 5, j: 0 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 1 }, { i: 0, j: 2 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 6, j: 0 }, { i: 6, j: 1 }, { i: 6, j: 2 }, ], css_id: 'tinytable_css_87pizrt6gpue7tq68k7m',}, + { positions: [ { i: 3, j: 0 }, { i: 1, j: 0 }, { i: 5, j: 0 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -80,7 +81,8 @@
diff --git a/inst/tinytest/_tinysnapshot/html-striped.html b/inst/tinytest/_tinysnapshot/html-striped.html index 12d5121b..caba5b5c 100644 --- a/inst/tinytest/_tinysnapshot/html-striped.html +++ b/inst/tinytest/_tinysnapshot/html-striped.html @@ -112,7 +112,7 @@
- + diff --git a/inst/tinytest/_tinysnapshot/html-striped_orange.html b/inst/tinytest/_tinysnapshot/html-striped_orange.html index 5daa8daa..8be0009e 100644 --- a/inst/tinytest/_tinysnapshot/html-striped_orange.html +++ b/inst/tinytest/_tinysnapshot/html-striped_orange.html @@ -114,7 +114,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/html-vectorized_color_j.html b/inst/tinytest/_tinysnapshot/html-vectorized_color_j.html index 6e6f65be..1cb500a3 100644 --- a/inst/tinytest/_tinysnapshot/html-vectorized_color_j.html +++ b/inst/tinytest/_tinysnapshot/html-vectorized_color_j.html @@ -62,11 +62,14 @@ window.addEventListener('load', function () { var cellsToStyle = [ // tinytable style arrays after - { positions: [ { i: 1, j: 1 }, { i: 2, j: 1 }, { i: 3, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, - { positions: [ { i: 0, j: 0 }, { i: 4, j: 0 }, { i: 0, j: 4 }, { i: 4, j: 4 }, { i: 0, j: 3 }, { i: 4, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, - { positions: [ { i: 0, j: 2 }, { i: 4, j: 2 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, - { positions: [ { i: 0, j: 1 }, { i: 4, j: 1 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, - { positions: [ { i: 1, j: 2 }, { i: 2, j: 2 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, + { positions: [ { i: 0, j: 1 }, ], css_id: 'tinytable_css_ue01fe9hmaas4mta0vfc',}, + { positions: [ { i: 4, j: 2 }, ], css_id: 'tinytable_css_u5i4tb8acz516c5lsr29',}, + { positions: [ { i: 0, j: 0 }, { i: 0, j: 4 }, { i: 0, j: 3 }, ], css_id: 'tinytable_css_qnddps3hrarwxnclv9tv',}, + { positions: [ { i: 1, j: 2 }, { i: 2, j: 2 }, { i: 3, j: 2 }, ], css_id: 'tinytable_css_iox90hlcz6p88f470o4c',}, + { positions: [ { i: 1, j: 1 }, { i: 2, j: 1 }, { i: 3, j: 1 }, ], css_id: 'tinytable_css_evu8i6m1snsv5kmmasu3',}, + { positions: [ { i: 4, j: 0 }, { i: 4, j: 4 }, { i: 4, j: 3 }, ], css_id: 'tinytable_css_dcq09jxgyitf4or5kg1s',}, + { positions: [ { i: 0, j: 2 }, ], css_id: 'tinytable_css_87pizrt6gpue7tq68k7m',}, + { positions: [ { i: 4, j: 1 }, ], css_id: 'tinytable_css_5jsz1u1bau6rax203jg7',}, ]; // Loop over the arrays to style the cells @@ -80,11 +83,14 @@
22.8 4 108 9393 3.85
22.8 4 108 9393 3.85
22.8 4 108 9393 3.85
@@ -118,7 +124,7 @@ - + diff --git a/inst/tinytest/_tinysnapshot/latex-align_d.txt b/inst/tinytest/_tinysnapshot/latex-align_d.txt index 9cfead4f..0c4b0aea 100644 --- a/inst/tinytest/_tinysnapshot/latex-align_d.txt +++ b/inst/tinytest/_tinysnapshot/latex-align_d.txt @@ -4,7 +4,8 @@ ] %% tabularray outer close { %% tabularray inner open colspec={Q[]}, -column{1}={}{si={table-format=-6.5, table-align-text-before=false, table-align-text-after=false, input-symbols={-, \*+()}},}, +column{1}={si={table-format=-6.5,table-align-text-before=false,table-align-text-after=false,input-symbols={-,\*+()}},}, +cell{1}{1}={guard,halign=c,}, } %% tabularray inner close \toprule pi \\ \midrule %% TinyTableHeader diff --git a/inst/tinytest/_tinysnapshot/latex-align_d_02.txt b/inst/tinytest/_tinysnapshot/latex-align_d_02.txt new file mode 100644 index 00000000..0c4b0aea --- /dev/null +++ b/inst/tinytest/_tinysnapshot/latex-align_d_02.txt @@ -0,0 +1,18 @@ +\begin{table} +\centering +\begin{tblr}[ %% tabularray outer open +] %% tabularray outer close +{ %% tabularray inner open +colspec={Q[]}, +column{1}={si={table-format=-6.5,table-align-text-before=false,table-align-text-after=false,input-symbols={-,\*+()}},}, +cell{1}{1}={guard,halign=c,}, +} %% tabularray inner close +\toprule +pi \\ \midrule %% TinyTableHeader +314.15927 \\ +3141.5927 \\ +31415.927 \\ +314159.27 \\ +\bottomrule +\end{tblr} +\end{table} diff --git a/inst/tinytest/_tinysnapshot/latex-align_d_03.txt b/inst/tinytest/_tinysnapshot/latex-align_d_03.txt new file mode 100644 index 00000000..0c4b0aea --- /dev/null +++ b/inst/tinytest/_tinysnapshot/latex-align_d_03.txt @@ -0,0 +1,18 @@ +\begin{table} +\centering +\begin{tblr}[ %% tabularray outer open +] %% tabularray outer close +{ %% tabularray inner open +colspec={Q[]}, +column{1}={si={table-format=-6.5,table-align-text-before=false,table-align-text-after=false,input-symbols={-,\*+()}},}, +cell{1}{1}={guard,halign=c,}, +} %% tabularray inner close +\toprule +pi \\ \midrule %% TinyTableHeader +314.15927 \\ +3141.5927 \\ +31415.927 \\ +314159.27 \\ +\bottomrule +\end{tblr} +\end{table} diff --git a/inst/tinytest/_tinysnapshot/latex-theme_grid.txt b/inst/tinytest/_tinysnapshot/latex-theme_grid.txt index 81f546cc..4fdd5315 100644 --- a/inst/tinytest/_tinysnapshot/latex-theme_grid.txt +++ b/inst/tinytest/_tinysnapshot/latex-theme_grid.txt @@ -5,15 +5,11 @@ { %% tabularray inner open colspec={Q[]Q[]Q[]Q[]Q[]}, hlines, vlines, -hlines, vlines, -hlines, vlines, -hlines, vlines, -hlines, vlines, } %% tabularray inner close mpg & cyl & disp & hp & drat \\ 21.0 & 6 & 160 & 110 & 3.90 \\ 21.0 & 6 & 160 & 110 & 3.90 \\ -22.8 & 4 & 108 & 93 & 3.85 \\ +22.8 & 4 & 108 & 93 & 3.85 \\ 21.4 & 6 & 258 & 110 & 3.08 \\ \end{tblr} \end{table} diff --git a/inst/tinytest/_tinysnapshot/latex-theme_striped.txt b/inst/tinytest/_tinysnapshot/latex-theme_striped.txt index 4e6dcac5..f92c2781 100644 --- a/inst/tinytest/_tinysnapshot/latex-theme_striped.txt +++ b/inst/tinytest/_tinysnapshot/latex-theme_striped.txt @@ -4,19 +4,15 @@ ] %% tabularray outer close { %% tabularray inner open colspec={Q[]Q[]Q[]Q[]Q[]}, -row{even}={bg=black!5!white}, -row{even}={bg=black!5!white}, -row{even}={bg=black!5!white}, -row{even}={bg=black!5!white}, -row{even}={bg=black!5!white}, row{2,4}={}{bg=cededed,}, +row{even}={bg=black!5!white}, } %% tabularray inner close \tinytableDefineColor{cededed}{HTML}{ededed} \toprule mpg & cyl & disp & hp & drat \\ \midrule %% TinyTableHeader 21.0 & 6 & 160 & 110 & 3.90 \\ 21.0 & 6 & 160 & 110 & 3.90 \\ -22.8 & 4 & 108 & 93 & 3.85 \\ +22.8 & 4 & 108 & 93 & 3.85 \\ 21.4 & 6 & 258 & 110 & 3.08 \\ \bottomrule \end{tblr} diff --git a/inst/tinytest/_tinysnapshot/markdown-bold_columns.txt b/inst/tinytest/_tinysnapshot/markdown-bold_columns.txt index c01869e1..0b9082d6 100644 --- a/inst/tinytest/_tinysnapshot/markdown-bold_columns.txt +++ b/inst/tinytest/_tinysnapshot/markdown-bold_columns.txt @@ -6,7 +6,7 @@ +------+-------+-------+---------+------+ | 21.0 | **6** | 160.0 | **110** | 3.90 | +------+-------+-------+---------+------+ -| 22.8 | **4** | 108.0 | ** 93** | 3.85 | +| 22.8 | **4** | 108.0 | **93** | 3.85 | +------+-------+-------+---------+------+ | 21.4 | **6** | 258.0 | **110** | 3.08 | +------+-------+-------+---------+------+ @@ -16,5 +16,5 @@ +------+-------+-------+---------+------+ | 14.3 | **8** | 360.0 | **245** | 3.21 | +------+-------+-------+---------+------+ -| 24.4 | **4** | 146.7 | ** 62** | 3.69 | +| 24.4 | **4** | 146.7 | **62** | 3.69 | +------+-------+-------+---------+------+ diff --git a/inst/tinytest/_tinysnapshot/markdown-group_tt.txt b/inst/tinytest/_tinysnapshot/markdown-group_tt.txt index 02e1cc5f..42959676 100644 --- a/inst/tinytest/_tinysnapshot/markdown-group_tt.txt +++ b/inst/tinytest/_tinysnapshot/markdown-group_tt.txt @@ -9,7 +9,7 @@ +------+-----+-------+-----+------+ | Hello | +------+-----+-------+-----+------+ -| 22.8 | 4 | 108.0 | 93 | 3.85 | +| 22.8 | 4 | 108.0 | 93 | 3.85 | +------+-----+-------+-----+------+ | 21.4 | 6 | 258.0 | 110 | 3.08 | +------+-----+-------+-----+------+ @@ -21,9 +21,9 @@ +------+-----+-------+-----+------+ | World | +------+-----+-------+-----+------+ -| 24.4 | 4 | 146.7 | 62 | 3.69 | +| 24.4 | 4 | 146.7 | 62 | 3.69 | +------+-----+-------+-----+------+ -| 22.8 | 4 | 140.8 | 95 | 3.92 | +| 22.8 | 4 | 140.8 | 95 | 3.92 | +------+-----+-------+-----+------+ | 19.2 | 6 | 167.6 | 123 | 3.92 | +------+-----+-------+-----+------+ diff --git a/inst/tinytest/_tinysnapshot/markdown-issue105.txt b/inst/tinytest/_tinysnapshot/markdown-issue105.txt index 29a9b553..fadb3961 100644 --- a/inst/tinytest/_tinysnapshot/markdown-issue105.txt +++ b/inst/tinytest/_tinysnapshot/markdown-issue105.txt @@ -9,7 +9,7 @@ +------+-----+-------+-----+------+-------+-------+----+----+------+------+ | blah | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ -| 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 | +| 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ @@ -19,9 +19,9 @@ +------+-----+-------+-----+------+-------+-------+----+----+------+------+ | 14.3 | 8 | 360.0 | 245 | 3.21 | 3.570 | 15.84 | 0 | 0 | 3 | 4 | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ -| 24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 | +| 24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ -| 22.8 | 4 | 140.8 | 95 | 3.92 | 3.150 | 22.90 | 1 | 0 | 4 | 2 | +| 22.8 | 4 | 140.8 | 95 | 3.92 | 3.150 | 22.90 | 1 | 0 | 4 | 2 | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ | blah | +------+-----+-------+-----+------+-------+-------+----+----+------+------+ diff --git a/inst/tinytest/_tinysnapshot/tibble-latex_pillar_num.txt b/inst/tinytest/_tinysnapshot/tibble-latex_pillar_num.txt index cdc1c279..7e984080 100644 --- a/inst/tinytest/_tinysnapshot/tibble-latex_pillar_num.txt +++ b/inst/tinytest/_tinysnapshot/tibble-latex_pillar_num.txt @@ -7,9 +7,9 @@ colspec={Q[]Q[]Q[]}, } %% tabularray inner close \toprule x3 & x4 & x5 \\ \midrule %% TinyTableHeader -900. & 900.5 & 900.5 \\ -1000. & 1000. & 1000.5 \\ -1100. & 1100. & 1100.5 \\ +900. & 900.5 & 900.5 \\ +1000. & 1000. & 1000.5 \\ +1100. & 1100. & 1100.5 \\ \bottomrule \end{tblr} \end{table} diff --git a/inst/tinytest/_tinysnapshot/tibble-markdown_tibble_issue141.txt b/inst/tinytest/_tinysnapshot/tibble-markdown_tibble_issue141.txt index 07427816..dd6e7902 100644 --- a/inst/tinytest/_tinysnapshot/tibble-markdown_tibble_issue141.txt +++ b/inst/tinytest/_tinysnapshot/tibble-markdown_tibble_issue141.txt @@ -2,7 +2,7 @@ +------+------+------+ | x3 | x4 | x5 | +======+======+======+ -| 900 | 900 | 900 | +| 900 | 900 | 900 | +------+------+------+ | 1000 | 1000 | 1000 | +------+------+------+ diff --git a/inst/tinytest/_tinysnapshot/tibble-typst_pillar_num.txt b/inst/tinytest/_tinysnapshot/tibble-typst_pillar_num.txt index 0e228e66..60a93cc9 100644 --- a/inst/tinytest/_tinysnapshot/tibble-typst_pillar_num.txt +++ b/inst/tinytest/_tinysnapshot/tibble-typst_pillar_num.txt @@ -45,31 +45,24 @@ block[ // start block columns: (auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 4, start: 0, end: 3, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 3, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 3, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 3, stroke: 0.05em + black), + table.hline(y: 4, start: 0, end: 3, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 3, stroke: 0.1em + black), // tinytable lines before table.header( @@ -78,9 +71,9 @@ block[ // start block ), // tinytable cell content after -[ 900.], [ 900.5], [ 900.5], -[1000.], [1000. ], [1000.5], -[1100.], [1100. ], [1100.5], +[900.], [900.5], [900.5], +[1000.], [1000.], [1000.5], +[1100.], [1100.], [1100.5], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-complicated.txt b/inst/tinytest/_tinysnapshot/typst-complicated.txt index 7fd688f4..96292cd8 100644 --- a/inst/tinytest/_tinysnapshot/typst-complicated.txt +++ b/inst/tinytest/_tinysnapshot/typst-complicated.txt @@ -1,6 +1,6 @@ #show figure: set block(breakable: true) #figure( // start figure preamble - caption: [Hello World], + caption: text([Hello World]), kind: "tinytable", supplement: "Table", // end figure preamble @@ -49,31 +49,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 6, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 2, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 2, start: 0, end: 5, stroke: 0.05em + black), + table.hline(y: 6, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( @@ -85,7 +78,7 @@ block[ // start block // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], [21.4], [6], [258], [110], [3.08], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-font_size.txt b/inst/tinytest/_tinysnapshot/typst-font_size.txt index 70b1eb49..712a5c2d 100644 --- a/inst/tinytest/_tinysnapshot/typst-font_size.txt +++ b/inst/tinytest/_tinysnapshot/typst-font_size.txt @@ -46,31 +46,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 5, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 5, stroke: 0.05em + black), + table.hline(y: 5, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( @@ -81,7 +74,7 @@ block[ // start block // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], [21.4], [6], [258], [110], [3.08], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-formatting.txt b/inst/tinytest/_tinysnapshot/typst-formatting.txt index b2dd00c0..f5d4017e 100644 --- a/inst/tinytest/_tinysnapshot/typst-formatting.txt +++ b/inst/tinytest/_tinysnapshot/typst-formatting.txt @@ -45,31 +45,24 @@ block[ // start block columns: (auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 4, start: 0, end: 4, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 4, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 4, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 4, stroke: 0.05em + black), + table.hline(y: 4, start: 0, end: 4, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 4, stroke: 0.1em + black), // tinytable lines before table.header( @@ -78,9 +71,9 @@ block[ // start block ), // tinytable cell content after -[143002], [1.43 ], [1972-06-16], [True ], -[201399], [201.4], [1970-08-21], [True ], -[100188], [0.13 ], [1970-07-18], [False], +[143002], [1.43], [1972-06-16], [True], +[201399], [201.4], [1970-08-21], [True], +[100188], [0.13], [1970-07-18], [False], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-grid.txt b/inst/tinytest/_tinysnapshot/typst-grid.txt index e0fe4e6c..f318524a 100644 --- a/inst/tinytest/_tinysnapshot/typst-grid.txt +++ b/inst/tinytest/_tinysnapshot/typst-grid.txt @@ -45,27 +45,19 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: (paint: black), align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, // tinytable lines before @@ -78,7 +70,7 @@ block[ // start block // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], [21.4], [6], [258], [110], [3.08], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-group_rows.txt b/inst/tinytest/_tinysnapshot/typst-group_rows.txt index fe03d2c9..50755c59 100644 --- a/inst/tinytest/_tinysnapshot/typst-group_rows.txt +++ b/inst/tinytest/_tinysnapshot/typst-group_rows.txt @@ -13,7 +13,7 @@ block[ // start block #let style-array = ( // tinytable cell style after (pairs: ((0, 1), (0, 2), (0, 4), (0, 6), (0, 7), (0, 8), (0, 10), (0, 11), (0, 12),), indent: 1em,), -(pairs: ((0, 0), (0, 3), (0, 5), (0, 9), (0, 13), (0, 14), (0, 15), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (3, 14), (3, 15), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (5, 13), (5, 14), (5, 15), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (7, 10), (7, 11), (7, 12), (7, 13), (7, 14), (7, 15),), ), +(pairs: ((0, 0), (0, 3), (0, 5), (0, 9), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (7, 10), (7, 11), (7, 12),), ), ) // tinytable align-default-array before @@ -46,31 +46,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 13, start: 0, end: 8, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 8, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 8, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 8, stroke: 0.05em + black), + table.hline(y: 13, start: 0, end: 8, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 8, stroke: 0.1em + black), // tinytable lines before table.header( @@ -82,15 +75,15 @@ block[ // start block [21.0], [6], [160.0], [110], [3.90], [2.620], [16.46], [0], [21.0], [6], [160.0], [110], [3.90], [2.875], [17.02], [0], table.cell(colspan: 8)[I like (fake) hamburgers], -[22.8], [4], [108.0], [ 93], [3.85], [2.320], [18.61], [1], +[22.8], [4], [108.0], [93], [3.85], [2.320], [18.61], [1], table.cell(colspan: 8)[She prefers halloumi], [21.4], [6], [258.0], [110], [3.08], [3.215], [19.44], [1], [18.7], [8], [360.0], [175], [3.15], [3.440], [17.02], [0], [18.1], [6], [225.0], [105], [2.76], [3.460], [20.22], [1], table.cell(colspan: 8)[They love tofu], [14.3], [8], [360.0], [245], [3.21], [3.570], [15.84], [0], -[24.4], [4], [146.7], [ 62], [3.69], [3.190], [20.00], [1], -[22.8], [4], [140.8], [ 95], [3.92], [3.150], [22.90], [1], +[24.4], [4], [146.7], [62], [3.69], [3.190], [20.00], [1], +[22.8], [4], [140.8], [95], [3.92], [3.150], [22.90], [1], // tinytable footer after ) // end table diff --git a/inst/tinytest/_tinysnapshot/typst-issue-139_misaligned_rule_with_group_tt.txt b/inst/tinytest/_tinysnapshot/typst-issue-139_misaligned_rule_with_group_tt.txt index 9415a8ff..abe2b2c9 100644 --- a/inst/tinytest/_tinysnapshot/typst-issue-139_misaligned_rule_with_group_tt.txt +++ b/inst/tinytest/_tinysnapshot/typst-issue-139_misaligned_rule_with_group_tt.txt @@ -15,7 +15,7 @@ block[ // start block (pairs: ((0, 2), (0, 4), (0, 5), (0, 6),), indent: 1em, align: center, color: white, background: blue,), (pairs: ((0, 7), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13),), indent: 1em,), (pairs: ((0, 3), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6),), align: center, color: white, background: blue,), -(pairs: ((0, 0), (0, 1), (0, 8), (0, 14), (0, 15), (1, 0), (1, 1), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (2, 0), (2, 1), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (3, 0), (3, 1), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (3, 14), (3, 15), (4, 0), (4, 1), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15),), ), +(pairs: ((0, 0), (0, 1), (0, 8), (1, 0), (1, 1), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (2, 0), (2, 1), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (3, 0), (3, 1), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (4, 0), (4, 1), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (4, 13),), ), ) // tinytable align-default-array before @@ -48,31 +48,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 14, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 2, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 2, start: 0, end: 5, stroke: 0.05em + black), + table.hline(y: 14, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( @@ -85,14 +78,14 @@ block[ // start block [21.0], [6], [160.0], [110], [3.90], table.cell(colspan: 5)[Feta], [21.0], [6], [160.0], [110], [3.90], -[22.8], [4], [108.0], [ 93], [3.85], +[22.8], [4], [108.0], [93], [3.85], [21.4], [6], [258.0], [110], [3.08], [18.7], [8], [360.0], [175], [3.15], table.cell(colspan: 5)[Brie], [18.1], [6], [225.0], [105], [2.76], [14.3], [8], [360.0], [245], [3.21], -[24.4], [4], [146.7], [ 62], [3.69], -[22.8], [4], [140.8], [ 95], [3.92], +[24.4], [4], [146.7], [62], [3.69], +[22.8], [4], [140.8], [95], [3.92], [19.2], [6], [167.6], [123], [3.92], // tinytable footer after ) // end table diff --git a/inst/tinytest/_tinysnapshot/typst-issue323_group_tt_style_tt.txt b/inst/tinytest/_tinysnapshot/typst-issue323_group_tt_style_tt.txt index 423e8181..5f348e95 100644 --- a/inst/tinytest/_tinysnapshot/typst-issue323_group_tt_style_tt.txt +++ b/inst/tinytest/_tinysnapshot/typst-issue323_group_tt_style_tt.txt @@ -15,7 +15,7 @@ block[ // start block (pairs: ((0, 2), (0, 3), (0, 5), (0, 7), (0, 8), (0, 9), (0, 11), (0, 12), (0, 13),), indent: 1em,), (pairs: ((0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0),), color: orange,), (pairs: ((0, 4), (0, 6), (0, 10), (1, 4), (1, 6), (1, 10), (2, 4), (2, 6), (2, 10), (3, 4), (3, 6), (3, 10), (4, 4), (4, 6), (4, 10), (5, 4), (5, 6), (5, 10), (6, 4), (6, 6), (6, 10), (7, 4), (7, 6), (7, 10),), align: center, color: orange, background: black,), -(pairs: ((0, 1), (0, 14), (0, 15), (0, 16), (1, 1), (1, 2), (1, 3), (1, 5), (1, 7), (1, 8), (1, 9), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (1, 16), (2, 1), (2, 2), (2, 3), (2, 5), (2, 7), (2, 8), (2, 9), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (2, 16), (3, 1), (3, 2), (3, 3), (3, 5), (3, 7), (3, 8), (3, 9), (3, 11), (3, 12), (3, 13), (3, 14), (3, 15), (3, 16), (4, 1), (4, 2), (4, 3), (4, 5), (4, 7), (4, 8), (4, 9), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15), (4, 16), (5, 1), (5, 2), (5, 3), (5, 5), (5, 7), (5, 8), (5, 9), (5, 11), (5, 12), (5, 13), (5, 14), (5, 15), (5, 16), (6, 1), (6, 2), (6, 3), (6, 5), (6, 7), (6, 8), (6, 9), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (6, 16), (7, 1), (7, 2), (7, 3), (7, 5), (7, 7), (7, 8), (7, 9), (7, 11), (7, 12), (7, 13), (7, 14), (7, 15), (7, 16),), ), +(pairs: ((0, 1), (1, 1), (1, 2), (1, 3), (1, 5), (1, 7), (1, 8), (1, 9), (1, 11), (1, 12), (1, 13), (2, 1), (2, 2), (2, 3), (2, 5), (2, 7), (2, 8), (2, 9), (2, 11), (2, 12), (2, 13), (3, 1), (3, 2), (3, 3), (3, 5), (3, 7), (3, 8), (3, 9), (3, 11), (3, 12), (3, 13), (4, 1), (4, 2), (4, 3), (4, 5), (4, 7), (4, 8), (4, 9), (4, 11), (4, 12), (4, 13), (5, 1), (5, 2), (5, 3), (5, 5), (5, 7), (5, 8), (5, 9), (5, 11), (5, 12), (5, 13), (6, 1), (6, 2), (6, 3), (6, 5), (6, 7), (6, 8), (6, 9), (6, 11), (6, 12), (6, 13), (7, 1), (7, 2), (7, 3), (7, 5), (7, 7), (7, 8), (7, 9), (7, 11), (7, 12), (7, 13),), ), ) // tinytable align-default-array before @@ -48,31 +48,24 @@ block[ // start block columns: (auto, auto, auto, auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 14, start: 0, end: 8, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 1, start: 0, end: 8, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 2, start: 0, end: 8, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 2, start: 0, end: 8, stroke: 0.05em + black), + table.hline(y: 14, start: 0, end: 8, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 8, stroke: 0.1em + black), // tinytable lines before table.header( @@ -85,15 +78,15 @@ table.cell(stroke: (bottom: .05em + black), colspan: 3, align: center)[Hamburger [21.0], [6], [160.0], [110], [3.90], [2.620], [16.46], [0], [21.0], [6], [160.0], [110], [3.90], [2.875], [17.02], [0], table.cell(colspan: 8)[I like (fake) hamburgers], -[22.8], [4], [108.0], [ 93], [3.85], [2.320], [18.61], [1], +[22.8], [4], [108.0], [93], [3.85], [2.320], [18.61], [1], table.cell(colspan: 8)[She prefers halloumi], [21.4], [6], [258.0], [110], [3.08], [3.215], [19.44], [1], [18.7], [8], [360.0], [175], [3.15], [3.440], [17.02], [0], [18.1], [6], [225.0], [105], [2.76], [3.460], [20.22], [1], table.cell(colspan: 8)[They love tofu], [14.3], [8], [360.0], [245], [3.21], [3.570], [15.84], [0], -[24.4], [4], [146.7], [ 62], [3.69], [3.190], [20.00], [1], -[22.8], [4], [140.8], [ 95], [3.92], [3.150], [22.90], [1], +[24.4], [4], [146.7], [62], [3.69], [3.190], [20.00], [1], +[22.8], [4], [140.8], [95], [3.92], [3.150], [22.90], [1], // tinytable footer after ) // end table diff --git a/inst/tinytest/_tinysnapshot/typst-italic_markdown.txt b/inst/tinytest/_tinysnapshot/typst-italic_markdown.txt index 5b576a33..988e2194 100644 --- a/inst/tinytest/_tinysnapshot/typst-italic_markdown.txt +++ b/inst/tinytest/_tinysnapshot/typst-italic_markdown.txt @@ -45,31 +45,24 @@ block[ // start block columns: (auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 2, start: 0, end: 1, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 1, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 1, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 1, stroke: 0.05em + black), + table.hline(y: 2, start: 0, end: 1, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 1, stroke: 0.1em + black), // tinytable lines before table.header( diff --git a/inst/tinytest/_tinysnapshot/typst-missing_value_replacement.txt b/inst/tinytest/_tinysnapshot/typst-missing_value_replacement.txt index 4e98d53e..38207ab1 100644 --- a/inst/tinytest/_tinysnapshot/typst-missing_value_replacement.txt +++ b/inst/tinytest/_tinysnapshot/typst-missing_value_replacement.txt @@ -45,31 +45,24 @@ block[ // start block columns: (auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 4, start: 0, end: 2, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 2, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 2, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 2, stroke: 0.05em + black), + table.hline(y: 4, start: 0, end: 2, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 2, stroke: 0.1em + black), // tinytable lines before table.header( @@ -78,9 +71,9 @@ block[ // start block ), // tinytable cell content after -[-], [ 3], -[ 1], [-], -[ 2], [ 5], +[-], [3], +[1], [-], +[2], [5], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-more_formatting.txt b/inst/tinytest/_tinysnapshot/typst-more_formatting.txt index 0c1b9dbb..ab234ab2 100644 --- a/inst/tinytest/_tinysnapshot/typst-more_formatting.txt +++ b/inst/tinytest/_tinysnapshot/typst-more_formatting.txt @@ -45,31 +45,24 @@ block[ // start block columns: (auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 5, start: 0, end: 3, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 3, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 3, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 3, stroke: 0.05em + black), + table.hline(y: 5, start: 0, end: 3, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 3, stroke: 0.1em + black), // tinytable lines before table.header( diff --git a/inst/tinytest/_tinysnapshot/typst-no_headers.txt b/inst/tinytest/_tinysnapshot/typst-no_headers.txt index fbe89bc3..7a9e9ddb 100644 --- a/inst/tinytest/_tinysnapshot/typst-no_headers.txt +++ b/inst/tinytest/_tinysnapshot/typst-no_headers.txt @@ -45,31 +45,23 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 5, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 5, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + black), // tinytable lines before table.header( @@ -79,7 +71,7 @@ block[ // start block // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], [21.4], [6], [258], [110], [3.08], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-significant_cell.txt b/inst/tinytest/_tinysnapshot/typst-significant_cell.txt index 32c27589..6388be6b 100644 --- a/inst/tinytest/_tinysnapshot/typst-significant_cell.txt +++ b/inst/tinytest/_tinysnapshot/typst-significant_cell.txt @@ -45,31 +45,24 @@ block[ // start block columns: (auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, - table.hline(y: 3, start: 0, end: 1, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 1, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 1, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 1, start: 0, end: 1, stroke: 0.05em + black), + table.hline(y: 3, start: 0, end: 1, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 1, stroke: 0.1em + black), // tinytable lines before table.header( diff --git a/inst/tinytest/_tinysnapshot/typst-striped.txt b/inst/tinytest/_tinysnapshot/typst-striped.txt index 28233a5b..6c30f7e7 100644 --- a/inst/tinytest/_tinysnapshot/typst-striped.txt +++ b/inst/tinytest/_tinysnapshot/typst-striped.txt @@ -46,27 +46,19 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, table.hline(y: 5, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), @@ -81,7 +73,7 @@ block[ // start block // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], [21.4], [6], [258], [110], [3.08], // tinytable footer after diff --git a/inst/tinytest/_tinysnapshot/typst-tblr.txt b/inst/tinytest/_tinysnapshot/typst-tblr.txt index 3b753913..c9d1f16b 100644 --- a/inst/tinytest/_tinysnapshot/typst-tblr.txt +++ b/inst/tinytest/_tinysnapshot/typst-tblr.txt @@ -45,33 +45,26 @@ block[ // start block columns: (auto, auto, auto, auto, auto), stroke: none, align: (x, y) => { - let align-array = ( - // tinytable cell align after - ) - if align-array.len() == 0 { - left + let sarray = style-array.filter(a => "align" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().align } else { left - // for style in style-array { - // let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - // if m != none and ("align" in style) { - // let a = style.align - // } - // } } }, fill: (x, y) => { - for style in style-array { - let m = style.pairs.find(k => k.at(0) == x and k.at(1) == y) - if m != none and ("background" in style) { - style.background - } + let sarray = style-array.filter(a => "background" in a) + let sarray = sarray.filter(a => a.pairs.find(p => p.at(0) == x and p.at(1) == y) != none) + if sarray.len() > 0 { + sarray.last().background } }, + table.hline(y: 1, start: 0, end: 5, stroke: 0.05em + black), table.hline(y: 2, start: 1, end: 3, stroke: 0.05em + red), table.hline(y: 3, start: 1, end: 3, stroke: 0.05em + red), table.hline(y: 3, start: 1, end: 3, stroke: 0.05em + red), table.hline(y: 4, start: 1, end: 3, stroke: 0.05em + red), - table.hline(y: 6, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), - table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), table.hline(y: 1, start: 0, end: 5, stroke: 0.1em + rgb("#d3d8dc")), + table.hline(y: 6, start: 0, end: 5, stroke: 0.1em + black), + table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black), table.vline(x: 1, start: 2, end: 4, stroke: 0.05em + red), table.vline(x: 2, start: 2, end: 4, stroke: 0.05em + red), table.vline(x: 2, start: 2, end: 4, stroke: 0.05em + red), table.vline(x: 3, start: 2, end: 4, stroke: 0.05em + red), // tinytable lines before @@ -84,7 +77,7 @@ block[ // start block // tinytable cell content after [21.0], [6], [160], [110], [3.90], [21.0], [6], [160], [110], [3.90], -[22.8], [4], [108], [ 93], [3.85], +[22.8], [4], [108], [93], [3.85], [21.4], [6], [258], [110], [3.08], [18.7], [8], [360], [175], [3.15], diff --git a/inst/tinytest/helpers.R b/inst/tinytest/helpers.R index dbece642..685901a3 100644 --- a/inst/tinytest/helpers.R +++ b/inst/tinytest/helpers.R @@ -1,6 +1,10 @@ options("tinysnapshot_device" = "svglite") options("tinysnapshot_tol" = 200) +# common formatting options +options(tinytable_format_bool = function(x) tools::toTitleCase(tolower(x))) +options(tinytable_format_replace = "") + # libraries requiet <- function(package) { void <- capture.output( diff --git a/inst/tinytest/test-format_tt.R b/inst/tinytest/test-format_tt.R index 89ad88aa..f2195b35 100644 --- a/inst/tinytest/test-format_tt.R +++ b/inst/tinytest/test-format_tt.R @@ -193,3 +193,26 @@ x <- tt(x) |> format_tt(replace = "!", quarto = TRUE) |> save_tt("latex") expect_true(grepl("IQ==", x)) + + +# Website scaling example +thumbdrives <- data.frame( + date_lookup = as.Date(c("2024-01-15", "2024-01-18", "2024-01-14", "2024-01-16")), + price = c(18.49, 19.99, 24.99, 24.99), + price_rank = c(1, 2, 3, 3), + memory = c(16e9, 12e9, 10e9, 8e9), + speed_benchmark = c(0.6, 0.73, 0.82, 0.99) +) +tab <- tt(thumbdrives) |> + format_tt(j = 1, fn = scales::date_format("%B %y", locale = "fr")) |> + format_tt(j = 2, fn = scales::label_currency()) |> + format_tt(j = 3, fn = scales::label_ordinal()) |> + format_tt(j = 4, fn = scales::label_bytes()) |> + format_tt(j = 5, fn = scales::label_percent()) |> + format_tt(escape = TRUE) |> + print("dataframe") +expect_true("$18.49" %in% tab$price) +expect_true("16 GB" %in% tab$memory) +expect_true("99%" %in% tab$speed_benchmark) +expect_false("2024-01-15" %in% tab$date_lookup) + diff --git a/inst/tinytest/test-i_j.R b/inst/tinytest/test-i_j.R index 3014badb..09c8cd09 100644 --- a/inst/tinytest/test-i_j.R +++ b/inst/tinytest/test-i_j.R @@ -21,4 +21,11 @@ tab <- tt(x) |> format_tt(i = 3:4, j = c(5:6), num_fmt = "decimal", digits = 2) expect_snapshot_print(tab, "i_j-format_tt_i_01") + +cormat <- data.frame(cor(mtcars[1:5])) +tab <- tt(cormat, digits = 2) |> + style_tt(i = abs(cormat) > .8, background = "black", color = "white") +expect_equal(dim(tab), c(5, 5)) + + options(tinytable_print_output = NULL) diff --git a/inst/tinytest/test-latex.R b/inst/tinytest/test-latex.R index bfb20be1..3b875e60 100644 --- a/inst/tinytest/test-latex.R +++ b/inst/tinytest/test-latex.R @@ -47,25 +47,34 @@ expect_snapshot_print( # Lazy style: group after style is respected -a <- tt(mtcars[1:4, 1:4]) |> +a <- tt(mtcars[1:4, 1:4]) |> style_tt(color = "orange", background = "black") |> group_tt(j = list("blah" = 1:2, "bar" = 3:4)) -b <- tt(mtcars[1:4, 1:4]) |> +b <- tt(mtcars[1:4, 1:4]) |> group_tt(j = list("blah" = 1:2, "bar" = 3:4)) |> style_tt(color = "orange", background = "black") expect_snapshot_print(a, label = "latex-group_style_order") expect_equal(as.character(a@table_string), as.character(b@table_string)) - +# align d x <- data.frame(pi = c(pi * 100, pi * 1000, pi * 10000, pi * 100000)) tab <- tt(x) |> - format_tt(j = 1, digits = 8, num_fmt = "significant_cell") |> - style_tt(j = 1, align = "d") + format_tt(j = 1, digits = 8, num_fmt = "significant_cell") |> + style_tt(j = 1, align = "d") expect_snapshot_print(tab, label = "latex-align_d") +dat = data.frame(a = c("(03.1)", "(3.14)**", "(003.1416)+")) +tt(dat) |> style_tt(align = "d") +expect_snapshot_print(tab, label = "latex-align_d_02") + +dat = data.frame(a = c("(03.1)", "(3.14)**", "(003.1416)+")) +tt(dat) |> + group_tt(j = list("blah" = 1)) |> + style_tt(align = "d") +expect_snapshot_print(tab, label = "latex-align_d_03") # bug discovered with vignette -x <- tt(mtcars[1:9, 1:8]) |> +x <- tt(mtcars[1:9, 1:8]) |> group_tt( i = list( "I like (fake) hamburgers" = 3, @@ -76,8 +85,8 @@ x <- tt(mtcars[1:9, 1:8]) |> align = "c", color = "white", background = "gray", - bold = TRUE) |> - save_tt("latex") + bold = TRUE) |> + save_tt("latex") expect_inherits(x, "character") # Footnotes @@ -147,7 +156,7 @@ dat <- data.frame( ), check.names = FALSE ) -dat<-tt(dat) |> format_tt(j = 1, markdown = TRUE) +dat <- tt(dat) |> format_tt(j = 1, markdown = TRUE) expect_snapshot_print( dat, label = "latex-formatting_url") @@ -156,22 +165,22 @@ expect_snapshot_print( x <- mtcars[1:4, 1:5] expect_snapshot_print( (tt(x) |> - style_tt( - i = 2:3, - j = c(1, 3, 4), - italic = TRUE, - background = "green", - color = "orange")), + style_tt( + i = 2:3, + j = c(1, 3, 4), + italic = TRUE, + background = "green", + color = "orange")), label = "latex-style") -# Font size +# Font size expect_snapshot_print( (tt(x) |> style_tt(j = "mpg|hp|qsec", fontsize = 1.5)), label = "latex-font_size") # Merging cells expect_snapshot_print( - (tt(x)|> style_tt( + (tt(x) |> style_tt( i = 2, j = 2, colspan = 3, rowspan = 2, @@ -184,20 +193,20 @@ expect_snapshot_print( # Spanning cells tab <- aggregate(mpg ~ cyl + am, FUN = mean, data = mtcars) -tab <- tab[order(tab$cyl, tab$am),] +tab <- tab[order(tab$cyl, tab$am), ] expect_snapshot_print( (tt(tab, digits = 2) |> - style_tt(i = c(1, 3, 5), j = 1, rowspan = 2, alignv = "t")), + style_tt(i = c(1, 3, 5), j = 1, rowspan = 2, alignv = "t")), label = "latex-spanning_cells") # Conditional styling k <- mtcars[1:10, c("mpg", "am", "vs")] expect_snapshot_print( (tt(k) |> - style_tt( - i = which(k$am == k$vs), - background = "teal", - color = "white")), + style_tt( + i = which(k$am == k$vs), + background = "teal", + color = "white")), label = "latex-conditional_styling") # Heatmaps @@ -208,13 +217,13 @@ bg <- hcl.colors(20, "Inferno") fg <- ifelse(as.matrix(k) < 1.7, tail(bg, 1), head(bg, 1)) expect_snapshot_print( (tt(k, width = .7, theme = "void") |> - style_tt(j = 1:5, align = "ccccc") |> - style_tt( - i = 1:4, - j = 1:5, - color = fg, - background = bg, - fontsize = fs)), + style_tt(j = 1:5, align = "ccccc") |> + style_tt( + i = 1:4, + j = 1:5, + color = fg, + background = bg, + fontsize = fs)), label = "latex-heatmaps") # Borders @@ -239,12 +248,14 @@ expect_snapshot_print(tab, label = "latex-issue242") x <- data.frame(x = 1:5) x <- data.frame(x = 1:5) colnames(x) <- NULL -tab <- tt(x) |> format_tt() |> save_tt("latex") +tab <- tt(x) |> + format_tt() |> + save_tt("latex") expect_inherits(tab, "character") # Issue #307 -tab <- tt(head(iris)) |> +tab <- tt(head(iris)) |> group_tt(j = list("blah" = 1:2)) |> theme_tt("tabular") expect_snapshot_print(tab, label = "latex-issue307.tex") @@ -257,5 +268,3 @@ expect_snapshot_print(tab, label = "latex-format_tt_math.tex") options(tinytable_print_output = NULL) - - diff --git a/inst/tinytest/test-pdf.R b/inst/tinytest/test-pdf.R index 432dd384..18073675 100644 --- a/inst/tinytest/test-pdf.R +++ b/inst/tinytest/test-pdf.R @@ -30,5 +30,15 @@ expect_warning( expect_true("somelog.log" %in% list.files(dest_dir)) +# Issue #395 +x <- mtcars[1:4, 1:5] +fn <- tempfile(fileext = ".pdf") +cap <- "A simple \\texttt{tinytable} example." +not <- "Nullam odio est, ullamcorper scelerisque lectus a, eleifend luctus nisl. Etiam ullamcorper, nibh vel interdum auctor, odio nulla mollis tortor, vel fringilla ante quam quis est." +tt(x, caption = cap, notes = not, width = .5) |> + style_tt( i = 1:3, j = 1:2, background = "#1ecebf", bold = TRUE) |> + group_tt(j = list("Halloumi" = 1:2, "Tofu" = 4:5)) |> + save_tt(fn, overwrite = TRUE) + # Clean slate suppressWarnings(invisible(file.remove(list.files(dest_dir)))) diff --git a/man-roxygen/dependencies.R b/man-roxygen/dependencies.R new file mode 100644 index 00000000..7be4ecbb --- /dev/null +++ b/man-roxygen/dependencies.R @@ -0,0 +1,5 @@ +#' @section Dependencies: +#' +#' * `.pdf` output requires a full LaTeX installation on the local computer. +#' * `.png` output requires the `webshot2` package. +#' * `.html` self-contained files require the `base64enc` package. diff --git a/man-roxygen/global_options.R b/man-roxygen/global_options.R index 499abf8b..c2b845ae 100644 --- a/man-roxygen/global_options.R +++ b/man-roxygen/global_options.R @@ -1,48 +1,101 @@ #' #' @section Global options: #' -#' Many global options can be used to set the default argument values of `tinytable` functions. -#' For a full list, see: +#' Options can be set with `options()` and change the default behavior of tinytable. For example: #' -#' https://vincentarelbundock.github.io/tinytable/vignettes/options.html +#' ```r +#' options(tinytable_tt_digits = 4) +#' tt(head(iris)) +#' ``` #' -#' ## Quarto -#' -#' ### Figure environment -#' -#' * `options("tinytable_quarto_figure" = FALSE)`: Typst only. Normally, it is best to allow Quarto to define the figure environment, so the default behavior is to not include one. -#' -#' ### Data Processing +#' You can set options in a script or via `.Rprofile`. Note: be cautious with `.Rprofile` settings as they may affect reproducibility. #' -#' The `format_tt(quarto=TRUE)` argument activates Quarto data processing for specific cells. This funcationality comes with a few warnings: +#' ## Default values for function arguments #' -#' 1. Currently, Quarto provides a `\QuartoMarkdownBase64{}` LaTeX macro, but it does not appear to do anything with it. References and markdown codes may not be processed as expected in LaTeX. -#' 2. Quarto data processing can enter in conflict with `tinytable` styling or formatting options. See below for how to disable it. +#' ### tt() #' -#' `options(tinytable_quarto_disable_processing = TRUE)` +#' * `tinytable_tt_digits` +#' * `tinytable_tt_caption` +#' * `tinytable_tt_notes` +#' * `tinytable_tt_width` +#' * `tinytable_tt_theme` +#' * `tinytable_tt_rownames` #' -#' Disable Quarto processing of cell content. Setting this global option to `FALSE` may lead to conflicts with some `tinytable` features, but it also allows use of markdown and Quarto-specific code in table cells, such as cross-references. +#' ### format_tt() #' -#' ```r -#' x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") -#' fn <- function(z) sprintf("", z) -#' tt(x) |> format_tt(i = 1, fn = fn) -#' ``` +#' * `tinytable_format_digits` +#' * `tinytable_format_num_fmt` +#' * `tinytable_format_num_zero` +#' * `tinytable_format_num_suffix` +#' * `tinytable_format_num_mark_big` +#' * `tinytable_format_num_mark_dec` +#' * `tinytable_format_date` +#' * `tinytable_format_bool` +#' * `tinytable_format_other` +#' * `tinytable_format_replace` +#' * `tinytable_format_escape` +#' * `tinytable_format_markdown` +#' * `tinytable_format_quarto` +#' * `tinytable_format_fn` +#' * `tinytable_format_sprintf` +#' +#' ### save_tt() +#' +#' * `tinytable_save_overwrite` +#' +#' ### theme_tt() +#' +#' Placement: +#' * `tinytable_theme_placement_float` +#' * `tinytable_theme_placement_horizontal` +#' +#' Resize: +#' * `tinytable_theme_resize_width` +#' * `tinytable_theme_resize_direction` +#' +#' Multipage: +#' * `tinytable_theme_multipage_rowhead` +#' * `tinytable_theme_multipage_rowfoot` +#' +#' Tabular: +#' * `tinytable_theme_tabular_style` #' -#' See this link for more details: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing +#' ### print.tinytable() #' -#' ## HTML +#' * `tinytable_print_output` #' -#' * `options(tinytable_html_mathjax = TRUE)` -#' - insert MathJax scripts in the HTML document. Warning: This may conflict with other elements of the page if MathJax is otherwise loaded. -#' * `options(tinytable_html_portable = TRUE)` -#' - `plot_tt()` inserts base 64 encoded images directly in the HTML file rather than use external links. +#' ## Output-specific options #' -#' ## PDF +#' ### HTML #' -#' * `options(tinytable_pdf_clean = TRUE)` -#' - deletes temporary and log files. -#' * `options(tinytable_pdf_engine = "xelatex")` -#' - "xelatex", "pdflatex", "lualatex" +#' * `tinytable_html_mathjax`: Insert MathJax scripts (warning: may conflict if MathJax is loaded elsewhere) +#' * `tinytable_html_portable`: Insert base64 encoded images directly in HTML for `plot_tt()` +#' +#' ### PDF +#' +#' * `tinytable_pdf_clean`: Delete temporary and log files +#' * `tinytable_pdf_engine`: Choose between "xelatex", "pdflatex", "lualatex" +#' +#' ### Quarto +#' +#' The `format_tt(quarto=TRUE)` argument enables Quarto data processing with some limitations: +#' +#' 1. The `\QuartoMarkdownBase64{}` LaTeX macro may not process references and markdown as expected +#' 2. Quarto processing may conflict with `tinytable` styling/formatting +#' +#' Options: +#' +#' * `tinytable_quarto_disable_processing`: Disable Quarto cell processing +#' * `tinytable_print_rstudio_notebook`: Display tables "inline" or in "viewer" for RStudio notebooks +#' * `tinytable_quarto_figure`: Control Typst figure environment in Quarto +#' +#' Example of Quarto-specific code in cells: +#' +#' ```r +#' x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") +#' fn <- function(z) sprintf("", z) +#' tt(x) |> format_tt(i = 1, fn = fn) +#' ``` #' +#' For more details on Quarto table processing: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing #' diff --git a/man-roxygen/latex_preamble.R b/man-roxygen/latex_preamble.R index c662fc9b..0f668692 100644 --- a/man-roxygen/latex_preamble.R +++ b/man-roxygen/latex_preamble.R @@ -4,7 +4,9 @@ #' #' `tinytable` uses the `tabularray` package from your LaTeX distribution to draw tables. `tabularray`, in turn, uses the special `tblr`, `talltblr`, and `longtblr` environments. #' -#' When rendering a document from Quarto or Rmarkdown directly to PDF, `tinytable` will populate the LaTeX preamble automatically with all the required packages (except when code chunks are cached). For standalone LaTeX documents, these commands should be inserted in the preamble manually: +#' When rendering a document from Quarto or Rmarkdown directly to PDF, `tinytable` will populate the LaTeX preamble automatically with all the required packages. For standalone LaTeX documents, these commands should be inserted in the preamble manually: +#' +#' Note: Your document will fail to compile to PDF in Quarto if you enable caching and you use tinytable due to missing LaTeX headers. To avoid this problem, set the option `#| cache: false` for the chunk(s) where you use tinytable. #' #' ```latex #' \usepackage{tabularray} diff --git a/man-roxygen/limitations_word_markdown.R b/man-roxygen/limitations_word_markdown.R new file mode 100644 index 00000000..1851e7da --- /dev/null +++ b/man-roxygen/limitations_word_markdown.R @@ -0,0 +1,8 @@ +#' @section Word and Markdown limitations: +#' +#' Markdown and Word tables only support these styles: italic, bold, strikeout. The `width` argument is also unavailable +#' Moreover, the `style_tt()` function cannot be used to style headers inserted by the `group_tt()` function; +#' instead, you should style the headers directly in the header definition using markdown syntax: +#' `group_tt(i = list("*italic header*" = 2))`. These limitations are due to the fact that there is no markdown +#' syntax for the other options, and that we create Word documents by converting a markdown table to .docx +#' via the Pandoc software. diff --git a/man/format_tt.Rd b/man/format_tt.Rd index d294f19a..1a63747b 100644 --- a/man/format_tt.Rd +++ b/man/format_tt.Rd @@ -15,18 +15,16 @@ format_tt( num_mark_big = get_option("tinytable_format_num_mark_big", default = ""), num_mark_dec = get_option("tinytable_format_num_mark_dec", default = getOption("OutDec", default = ".")), - date = get_option("tinytable_format_date", default = "\%Y-\%m-\%d"), - bool = get_option("tinytable_format_bool", default = function(column) - tools::toTitleCase(tolower(column))), + date = get_option("tinytable_format_date", default = NULL), + bool = get_option("tinytable_format_bool", default = NULL), math = get_option("tinytable_format_math", default = FALSE), - other = get_option("tinytable_format_other", default = as.character), - replace = get_option("tinytable_format_replace", default = TRUE), + other = get_option("tinytable_format_other", default = NULL), + replace = get_option("tinytable_format_replace", default = FALSE), escape = get_option("tinytable_format_escape", default = FALSE), markdown = get_option("tinytable_format_markdown", default = FALSE), quarto = get_option("tinytable_format_quarto", default = FALSE), fn = get_option("tinytable_format_fn", default = NULL), - sprintf = get_option("tinytable_format_sprintf", default = NULL), - ... + sprintf = get_option("tinytable_format_sprintf", default = NULL) ) } \arguments{ @@ -84,8 +82,6 @@ format_tt( \item{fn}{Function for custom formatting. Accepts a vector and returns a character vector of the same length.} \item{sprintf}{String passed to the \code{?sprintf} function to format numbers or interpolate strings with a user-defined pattern (similar to the \code{glue} package, but using Base R).} - -\item{...}{Additional arguments are ignored.} } \value{ A data frame with formatted columns. @@ -99,101 +95,166 @@ If this function is applied several times to the same cell, the last transformat \section{Global options}{ -Many global options can be used to set the default argument values of \code{tinytable} functions. -For a full list, see: +Options can be set with \code{options()} and change the default behavior of tinytable. For example: -https://vincentarelbundock.github.io/tinytable/vignettes/options.html -\subsection{Quarto}{ -\subsection{Figure environment}{ +\if{html}{\out{
}}\preformatted{options(tinytable_tt_digits = 4) +tt(head(iris)) +}\if{html}{\out{
}} + +You can set options in a script or via \code{.Rprofile}. Note: be cautious with \code{.Rprofile} settings as they may affect reproducibility. +\subsection{Default values for function arguments}{ +\subsection{tt()}{ \itemize{ -\item \code{options("tinytable_quarto_figure" = FALSE)}: Typst only. Normally, it is best to allow Quarto to define the figure environment, so the default behavior is to not include one. +\item \code{tinytable_tt_digits} +\item \code{tinytable_tt_caption} +\item \code{tinytable_tt_notes} +\item \code{tinytable_tt_width} +\item \code{tinytable_tt_theme} +\item \code{tinytable_tt_rownames} } } -\subsection{Data Processing}{ - -The \code{format_tt(quarto=TRUE)} argument activates Quarto data processing for specific cells. This funcationality comes with a few warnings: -\enumerate{ -\item Currently, Quarto provides a \verb{\\QuartoMarkdownBase64\{\}} LaTeX macro, but it does not appear to do anything with it. References and markdown codes may not be processed as expected in LaTeX. -\item Quarto data processing can enter in conflict with \code{tinytable} styling or formatting options. See below for how to disable it. +\subsection{format_tt()}{ +\itemize{ +\item \code{tinytable_format_digits} +\item \code{tinytable_format_num_fmt} +\item \code{tinytable_format_num_zero} +\item \code{tinytable_format_num_suffix} +\item \code{tinytable_format_num_mark_big} +\item \code{tinytable_format_num_mark_dec} +\item \code{tinytable_format_date} +\item \code{tinytable_format_bool} +\item \code{tinytable_format_other} +\item \code{tinytable_format_replace} +\item \code{tinytable_format_escape} +\item \code{tinytable_format_markdown} +\item \code{tinytable_format_quarto} +\item \code{tinytable_format_fn} +\item \code{tinytable_format_sprintf} +} } -\code{options(tinytable_quarto_disable_processing = TRUE)} - -Disable Quarto processing of cell content. Setting this global option to \code{FALSE} may lead to conflicts with some \code{tinytable} features, but it also allows use of markdown and Quarto-specific code in table cells, such as cross-references. +\subsection{save_tt()}{ +\itemize{ +\item \code{tinytable_save_overwrite} +} +} -\if{html}{\out{
}}\preformatted{x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") -fn <- function(z) sprintf("", z) -tt(x) |> format_tt(i = 1, fn = fn) -}\if{html}{\out{
}} +\subsection{theme_tt()}{ -See this link for more details: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing +Placement: +\itemize{ +\item \code{tinytable_theme_placement_float} +\item \code{tinytable_theme_placement_horizontal} } +Resize: +\itemize{ +\item \code{tinytable_theme_resize_width} +\item \code{tinytable_theme_resize_direction} } -\subsection{HTML}{ +Multipage: \itemize{ -\item \code{options(tinytable_html_mathjax = TRUE)} +\item \code{tinytable_theme_multipage_rowhead} +\item \code{tinytable_theme_multipage_rowfoot} +} + +Tabular: \itemize{ -\item insert MathJax scripts in the HTML document. Warning: This may conflict with other elements of the page if MathJax is otherwise loaded. +\item \code{tinytable_theme_tabular_style} +} } -\item \code{options(tinytable_html_portable = TRUE)} + +\subsection{print.tinytable()}{ \itemize{ -\item \code{plot_tt()} inserts base 64 encoded images directly in the HTML file rather than use external links. +\item \code{tinytable_print_output} } } + } -\subsection{PDF}{ +\subsection{Output-specific options}{ +\subsection{HTML}{ \itemize{ -\item \code{options(tinytable_pdf_clean = TRUE)} +\item \code{tinytable_html_mathjax}: Insert MathJax scripts (warning: may conflict if MathJax is loaded elsewhere) +\item \code{tinytable_html_portable}: Insert base64 encoded images directly in HTML for \code{plot_tt()} +} +} + +\subsection{PDF}{ \itemize{ -\item deletes temporary and log files. +\item \code{tinytable_pdf_clean}: Delete temporary and log files +\item \code{tinytable_pdf_engine}: Choose between "xelatex", "pdflatex", "lualatex" } -\item \code{options(tinytable_pdf_engine = "xelatex")} +} + +\subsection{Quarto}{ + +The \code{format_tt(quarto=TRUE)} argument enables Quarto data processing with some limitations: +\enumerate{ +\item The \verb{\\QuartoMarkdownBase64\{\}} LaTeX macro may not process references and markdown as expected +\item Quarto processing may conflict with \code{tinytable} styling/formatting +} + +Options: \itemize{ -\item "xelatex", "pdflatex", "lualatex" +\item \code{tinytable_quarto_disable_processing}: Disable Quarto cell processing +\item \code{tinytable_print_rstudio_notebook}: Display tables "inline" or in "viewer" for RStudio notebooks +\item \code{tinytable_quarto_figure}: Control Typst figure environment in Quarto } + +Example of Quarto-specific code in cells: + +\if{html}{\out{
}}\preformatted{x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") +fn <- function(z) sprintf("", z) +tt(x) |> format_tt(i = 1, fn = fn) +}\if{html}{\out{
}} + +For more details on Quarto table processing: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing } + } } \examples{ dat <- data.frame( a = rnorm(3, mean = 10000), - b = rnorm(3, 10000)) + b = rnorm(3, 10000) +) tab <- tt(dat) format_tt(tab, - digits = 2, - num_mark_dec = ",", - num_mark_big = " ") - + digits = 2, + num_mark_dec = ",", + num_mark_big = " " +) + k <- tt(data.frame(x = c(0.000123456789, 12.4356789))) format_tt(k, digits = 2, num_fmt = "significant_cell") - + dat <- data.frame( - a = c("Burger", "Halloumi", "Tofu", "Beans"), - b = c(1.43202, 201.399, 0.146188, 0.0031), - c = c(98938272783457, 7288839482, 29111727, 93945)) + a = c("Burger", "Halloumi", "Tofu", "Beans"), + b = c(1.43202, 201.399, 0.146188, 0.0031), + c = c(98938272783457, 7288839482, 29111727, 93945) +) tt(dat) |> - format_tt(j = "a", sprintf = "Food: \%s") |> - format_tt(j = 2, digits = 1, num_fmt = "decimal", num_zero = TRUE) |> - format_tt(j = "c", digits = 2, num_suffix = TRUE) - + format_tt(j = "a", sprintf = "Food: \%s") |> + format_tt(j = 2, digits = 1, num_fmt = "decimal", num_zero = TRUE) |> + format_tt(j = "c", digits = 2, num_suffix = TRUE) + y <- tt(data.frame(x = c(123456789.678, 12435.6789))) -format_tt(y, digits=3, num_mark_big=" ") +format_tt(y, digits = 3, num_mark_big = " ") x <- tt(data.frame(Text = c("_italicized text_", "__bold text__"))) -format_tt(x, markdown=TRUE) +format_tt(x, markdown = TRUE) tab <- data.frame(a = c(NA, 1, 2), b = c(3, NA, 5)) tt(tab) |> format_tt(replace = "-") dat <- data.frame( - "LaTeX" = c("Dollars $", "Percent \%", "Underscore _"), - "HTML" = c("
", "4", "blah") + "LaTeX" = c("Dollars $", "Percent \%", "Underscore _"), + "HTML" = c("
", "4", "blah") ) -tt(dat) |> format_tt(escape = TRUE) +tt(dat) |> format_tt(escape = TRUE) } diff --git a/man/group_tt.Rd b/man/group_tt.Rd index e7fd6d23..3e1f1653 100644 --- a/man/group_tt.Rd +++ b/man/group_tt.Rd @@ -31,13 +31,24 @@ Spanning labels to identify groups of rows or columns \details{ Warning: The \code{style_tt()} can normally be used to style the group headers, as expected, but that feature is not available for Markdown and Word tables. } +\section{Word and Markdown limitations}{ + + +Markdown and Word tables only support these styles: italic, bold, strikeout. The \code{width} argument is also unavailable +Moreover, the \code{style_tt()} function cannot be used to style headers inserted by the \code{group_tt()} function; +instead, you should style the headers directly in the header definition using markdown syntax: +\code{group_tt(i = list("*italic header*" = 2))}. These limitations are due to the fact that there is no markdown +syntax for the other options, and that we create Word documents by converting a markdown table to .docx +via the Pandoc software. +} + \examples{ # vector of row labels dat <- data.frame( - label = c("a", "a", "a", "b", "b", "c", "a", "a"), - x1 = rnorm(8), - x2 = rnorm(8)) + label = c("a", "a", "a", "b", "b", "c", "a", "a"), + x1 = rnorm(8), + x2 = rnorm(8)) tt(dat[, 2:3]) |> group_tt(i = dat$label) # named lists of labels diff --git a/man/initialize-tinytable-method.Rd b/man/initialize-tinytable-method.Rd index 5707ffd2..8fe22d80 100644 --- a/man/initialize-tinytable-method.Rd +++ b/man/initialize-tinytable-method.Rd @@ -28,7 +28,7 @@ \item{theme}{Function or string. \itemize{ -\item String: grid, resize, multipage, placement, rotate, striped, void, bootstrap, tabular +\item String: bootstrap, grid, multipage, placement, revealjs, resize, rotate, spacing, striped, tabular, void \item Function: Applied to the \code{tinytable} object. }} diff --git a/man/rbind2-tinytable-tinytable-method.Rd b/man/rbind2-tinytable-tinytable-method.Rd index 8b6461d1..861f58f1 100644 --- a/man/rbind2-tinytable-tinytable-method.Rd +++ b/man/rbind2-tinytable-tinytable-method.Rd @@ -42,8 +42,8 @@ This function relies on the \code{rbindlist()} function from the \code{data.tabl } \examples{ library(tinytable) -x = tt(mtcars[1:3, 1:2], caption = "Combine two tiny tables.") -y = tt(mtcars[4:5, 8:10]) +x <- tt(mtcars[1:3, 1:2], caption = "Combine two tiny tables.") +y <- tt(mtcars[4:5, 8:10]) # rbind() does not support additional aarguments # rbind2() supports additional arguments diff --git a/man/save_tt.Rd b/man/save_tt.Rd index 25e9f939..4560a46f 100644 --- a/man/save_tt.Rd +++ b/man/save_tt.Rd @@ -29,6 +29,162 @@ A string with the table when \code{output} is a format, and the file path when \ \description{ This function saves an object of class tinytable to a specified file and format, with an option to overwrite existing files. } +\section{Dependencies}{ + +\itemize{ +\item \code{.pdf} output requires a full LaTeX installation on the local computer. +\item \code{.png} output requires the \code{webshot2} package. +\item \code{.html} self-contained files require the \code{base64enc} package. +} +} + +\section{LaTeX preamble}{ + + +\code{tinytable} uses the \code{tabularray} package from your LaTeX distribution to draw tables. \code{tabularray}, in turn, uses the special \code{tblr}, \code{talltblr}, and \code{longtblr} environments. + +When rendering a document from Quarto or Rmarkdown directly to PDF, \code{tinytable} will populate the LaTeX preamble automatically with all the required packages. For standalone LaTeX documents, these commands should be inserted in the preamble manually: + +Note: Your document will fail to compile to PDF in Quarto if you enable caching and you use tinytable due to missing LaTeX headers. To avoid this problem, set the option \verb{#| cache: false} for the chunk(s) where you use tinytable. + +\if{html}{\out{
}}\preformatted{\\usepackage\{tabularray\} +\\usepackage\{float\} +\\usepackage\{graphicx\} +\\usepackage\{rotating\} +\\usepackage[normalem]\{ulem\} +\\UseTblrLibrary\{booktabs\} +\\UseTblrLibrary\{siunitx\} +\newcommand{\tinytableTabularrayUnderline}[1]\{\\underline\{#1\}\} +\newcommand{\tinytableTabularrayStrikeout}[1]\{\\sout\{#1\}\} +\\NewTableCommand\{\\tinytableDefineColor\}[3]\{\\definecolor\{#1\}\{#2\}\{#3\}\} +}\if{html}{\out{
}} +} + +\section{Global options}{ + + +Options can be set with \code{options()} and change the default behavior of tinytable. For example: + +\if{html}{\out{
}}\preformatted{options(tinytable_tt_digits = 4) +tt(head(iris)) +}\if{html}{\out{
}} + +You can set options in a script or via \code{.Rprofile}. Note: be cautious with \code{.Rprofile} settings as they may affect reproducibility. +\subsection{Default values for function arguments}{ +\subsection{tt()}{ +\itemize{ +\item \code{tinytable_tt_digits} +\item \code{tinytable_tt_caption} +\item \code{tinytable_tt_notes} +\item \code{tinytable_tt_width} +\item \code{tinytable_tt_theme} +\item \code{tinytable_tt_rownames} +} +} + +\subsection{format_tt()}{ +\itemize{ +\item \code{tinytable_format_digits} +\item \code{tinytable_format_num_fmt} +\item \code{tinytable_format_num_zero} +\item \code{tinytable_format_num_suffix} +\item \code{tinytable_format_num_mark_big} +\item \code{tinytable_format_num_mark_dec} +\item \code{tinytable_format_date} +\item \code{tinytable_format_bool} +\item \code{tinytable_format_other} +\item \code{tinytable_format_replace} +\item \code{tinytable_format_escape} +\item \code{tinytable_format_markdown} +\item \code{tinytable_format_quarto} +\item \code{tinytable_format_fn} +\item \code{tinytable_format_sprintf} +} +} + +\subsection{save_tt()}{ +\itemize{ +\item \code{tinytable_save_overwrite} +} +} + +\subsection{theme_tt()}{ + +Placement: +\itemize{ +\item \code{tinytable_theme_placement_float} +\item \code{tinytable_theme_placement_horizontal} +} + +Resize: +\itemize{ +\item \code{tinytable_theme_resize_width} +\item \code{tinytable_theme_resize_direction} +} + +Multipage: +\itemize{ +\item \code{tinytable_theme_multipage_rowhead} +\item \code{tinytable_theme_multipage_rowfoot} +} + +Tabular: +\itemize{ +\item \code{tinytable_theme_tabular_style} +} +} + +\subsection{print.tinytable()}{ +\itemize{ +\item \code{tinytable_print_output} +} +} + +} + +\subsection{Output-specific options}{ +\subsection{HTML}{ +\itemize{ +\item \code{tinytable_html_mathjax}: Insert MathJax scripts (warning: may conflict if MathJax is loaded elsewhere) +\item \code{tinytable_html_portable}: Insert base64 encoded images directly in HTML for \code{plot_tt()} +} +} + +\subsection{PDF}{ +\itemize{ +\item \code{tinytable_pdf_clean}: Delete temporary and log files +\item \code{tinytable_pdf_engine}: Choose between "xelatex", "pdflatex", "lualatex" +} +} + +\subsection{Quarto}{ + +The \code{format_tt(quarto=TRUE)} argument enables Quarto data processing with some limitations: +\enumerate{ +\item The \verb{\\QuartoMarkdownBase64\{\}} LaTeX macro may not process references and markdown as expected +\item Quarto processing may conflict with \code{tinytable} styling/formatting +} + +Options: +\itemize{ +\item \code{tinytable_quarto_disable_processing}: Disable Quarto cell processing +\item \code{tinytable_print_rstudio_notebook}: Display tables "inline" or in "viewer" for RStudio notebooks +\item \code{tinytable_quarto_figure}: Control Typst figure environment in Quarto +} + +Example of Quarto-specific code in cells: + +\if{html}{\out{
}}\preformatted{x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") +fn <- function(z) sprintf("", z) +tt(x) |> format_tt(i = 1, fn = fn) +}\if{html}{\out{
}} + +For more details on Quarto table processing: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing +} + +} +} + \examples{ library(tinytable) x <- mtcars[1:4, 1:5] diff --git a/man/style_tt.Rd b/man/style_tt.Rd index 14e18a31..5c54a1da 100644 --- a/man/style_tt.Rd +++ b/man/style_tt.Rd @@ -37,7 +37,12 @@ style_tt( \arguments{ \item{x}{A table object created by \code{tt()}.} -\item{i}{Row indices where the styling should be applied. Can be a single value, a vector, or a logical matrix with the same number of rows and columns as \code{x}. \code{i=0} is the header, and negative values are higher level headers. Row indices refer to rows \emph{after} the insertion of row labels by \code{group_tt()}, when applicable.} +\item{i}{Numeric vector, logical matrix, or string.. +\itemize{ +\item Numeric vector: Row indices where the styling should be applied. Can be a single value or a vector. +\item Logical matrix: A matrix with the same number of rows and columns as \code{x}. \code{i=0} is the header, and negative values are higher level headers. Row indices refer to rows \emph{after} the insertion of row labels by \code{group_tt()}, when applicable. +\item String: "notes" or "caption". +}} \item{j}{Column indices where the styling should be applied. Can be: \itemize{ @@ -123,27 +128,16 @@ Style a Tiny Table } \details{ This function applies styling to a table created by \code{tt()}. It allows customization of text style (bold, italic, monospace), text and background colors, font size, cell width, text alignment, column span, and indentation. The function also supports passing native instructions to LaTeX (tabularray) and HTML (bootstrap) formats. - -Note: Markdown and Word tables only support these styles: italic, bold, strikeout. Moreover, the \code{style_tt()} function cannot be used to style headers inserted by the \code{group_tt()} function; instead, you should style the headers directly in the header definition using markdown syntax: \code{group_tt(i = list("*italic header*" = 2))}. These limitations are due to the fact that there is no markdown syntax for the other options, and that we create Word documents by converting a markdown table to .docx via the Pandoc software. } -\section{LaTeX preamble}{ +\section{Word and Markdown limitations}{ -\code{tinytable} uses the \code{tabularray} package from your LaTeX distribution to draw tables. \code{tabularray}, in turn, uses the special \code{tblr}, \code{talltblr}, and \code{longtblr} environments. - -When rendering a document from Quarto or Rmarkdown directly to PDF, \code{tinytable} will populate the LaTeX preamble automatically with all the required packages (except when code chunks are cached). For standalone LaTeX documents, these commands should be inserted in the preamble manually: - -\if{html}{\out{
}}\preformatted{\\usepackage\{tabularray\} -\\usepackage\{float\} -\\usepackage\{graphicx\} -\\usepackage\{rotating\} -\\usepackage[normalem]\{ulem\} -\\UseTblrLibrary\{booktabs\} -\\UseTblrLibrary\{siunitx\} -\newcommand{\tinytableTabularrayUnderline}[1]\{\\underline\{#1\}\} -\newcommand{\tinytableTabularrayStrikeout}[1]\{\\sout\{#1\}\} -\\NewTableCommand\{\\tinytableDefineColor\}[3]\{\\definecolor\{#1\}\{#2\}\{#3\}\} -}\if{html}{\out{
}} +Markdown and Word tables only support these styles: italic, bold, strikeout. The \code{width} argument is also unavailable +Moreover, the \code{style_tt()} function cannot be used to style headers inserted by the \code{group_tt()} function; +instead, you should style the headers directly in the header definition using markdown syntax: +\code{group_tt(i = list("*italic header*" = 2))}. These limitations are due to the fact that there is no markdown +syntax for the other options, and that we create Word documents by converting a markdown table to .docx +via the Pandoc software. } \examples{ @@ -156,15 +150,15 @@ library(tinytable) tt(mtcars[1:5, 1:6]) # Alignment -tt(mtcars[1:5, 1:6]) |> +tt(mtcars[1:5, 1:6]) |> style_tt(j = 1:5, align = "lcccr") # Colors and styles -tt(mtcars[1:5, 1:6]) |> +tt(mtcars[1:5, 1:6]) |> style_tt(i = 2:3, background = "black", color = "orange", bold = TRUE) # column selection with `j`` -tt(mtcars[1:5, 1:6]) |> +tt(mtcars[1:5, 1:6]) |> style_tt(j = 5:6, background = "pink") tt(mtcars[1:5, 1:6]) |> @@ -178,27 +172,27 @@ tt(mtcars[1:5, 1:6], theme = "void") |> i = 2, j = 2, colspan = 3, rowspan = 2, - align="c", + align = "c", alignv = "m", color = "white", background = "black", bold = TRUE) - + tt(mtcars[1:5, 1:6], theme = "void") |> style_tt( - i=0:3, - j=1:3, - line="tblr", - line_width=0.4, - line_color="teal") - + i = 0:3, + j = 1:3, + line = "tblr", + line_width = 0.4, + line_color = "teal") + tt(mtcars[1:5, 1:6], theme = "bootstrap") |> - style_tt( - i = c(2,5), - j = 3, - strikeout = TRUE, - fontsize = 0.7) - + style_tt( + i = c(2, 5), + j = 3, + strikeout = TRUE, + fontsize = 0.7) + tt(mtcars[1:5, 1:6]) |> style_tt(bootstrap_class = "table table-dark table-hover") diff --git a/man/theme_tt.Rd b/man/theme_tt.Rd index 9ac81d50..dc21420f 100644 --- a/man/theme_tt.Rd +++ b/man/theme_tt.Rd @@ -17,6 +17,7 @@ theme_tt(x, theme, ...) \item "placement": Position of the table environment (LaTeX) \item "rotate": Rotate a LaTeX or Typst table. \item "resize": Scale a LaTeX \code{tinytable} to fit the \code{width} argument. +\item "spacing": Draw more compact or airy tables. \item "striped": Grey stripes on alternating rows \item "tabular": Remove table environment (LaTeX) or Javascript/CSS (HTML) \item "void": No rules @@ -91,6 +92,12 @@ rotate \item LaTeX: In Quarto documents, captions must be specified using the \code{caption} argument in \code{tt()} rather than via Quarto chunk options. } } + +spacing +\itemize{ +\item \code{rowsep}: Row spacing +\item \code{colsep}: Column spacing +} } \examples{ @@ -104,7 +111,7 @@ tt(x, theme = "striped") tt(x) |> theme_tt("striped") # resize w/ argument -x <- cbind(mtcars[1:10,], mtcars[1:10,]) +x <- cbind(mtcars[1:10, ], mtcars[1:10, ]) tt(x) |> theme_tt("resize", width = .9) |> print("latex") diff --git a/man/tt.Rd b/man/tt.Rd index 273afaf8..52e100a6 100644 --- a/man/tt.Rd +++ b/man/tt.Rd @@ -39,7 +39,7 @@ tt( \item{theme}{Function or string. \itemize{ -\item String: grid, resize, multipage, placement, rotate, striped, void, bootstrap, tabular +\item String: bootstrap, grid, multipage, placement, revealjs, resize, rotate, spacing, striped, tabular, void \item Function: Applied to the \code{tinytable} object. }} @@ -67,12 +67,23 @@ The \code{tt} function renders a table in different formats with various styling \code{tinytable} attempts to determine the appropriate way to print the table based on interactive use, RStudio availability, and output format in RMarkdown or Quarto documents. Users can call \code{print(x, output="markdown")} to print the table in a specific format. Alternatively, they can set a global option: \code{options("tinytable_print_output"="markdown")} } +\section{Dependencies}{ + +\itemize{ +\item \code{.pdf} output requires a full LaTeX installation on the local computer. +\item \code{.png} output requires the \code{webshot2} package. +\item \code{.html} self-contained files require the \code{base64enc} package. +} +} + \section{LaTeX preamble}{ \code{tinytable} uses the \code{tabularray} package from your LaTeX distribution to draw tables. \code{tabularray}, in turn, uses the special \code{tblr}, \code{talltblr}, and \code{longtblr} environments. -When rendering a document from Quarto or Rmarkdown directly to PDF, \code{tinytable} will populate the LaTeX preamble automatically with all the required packages (except when code chunks are cached). For standalone LaTeX documents, these commands should be inserted in the preamble manually: +When rendering a document from Quarto or Rmarkdown directly to PDF, \code{tinytable} will populate the LaTeX preamble automatically with all the required packages. For standalone LaTeX documents, these commands should be inserted in the preamble manually: + +Note: Your document will fail to compile to PDF in Quarto if you enable caching and you use tinytable due to missing LaTeX headers. To avoid this problem, set the option \verb{#| cache: false} for the chunk(s) where you use tinytable. \if{html}{\out{
}}\preformatted{\\usepackage\{tabularray\} \\usepackage\{float\} @@ -87,66 +98,139 @@ When rendering a document from Quarto or Rmarkdown directly to PDF, \code{tinyta }\if{html}{\out{
}} } +\section{Word and Markdown limitations}{ + + +Markdown and Word tables only support these styles: italic, bold, strikeout. The \code{width} argument is also unavailable +Moreover, the \code{style_tt()} function cannot be used to style headers inserted by the \code{group_tt()} function; +instead, you should style the headers directly in the header definition using markdown syntax: +\code{group_tt(i = list("*italic header*" = 2))}. These limitations are due to the fact that there is no markdown +syntax for the other options, and that we create Word documents by converting a markdown table to .docx +via the Pandoc software. +} + \section{Global options}{ -Many global options can be used to set the default argument values of \code{tinytable} functions. -For a full list, see: +Options can be set with \code{options()} and change the default behavior of tinytable. For example: -https://vincentarelbundock.github.io/tinytable/vignettes/options.html -\subsection{Quarto}{ -\subsection{Figure environment}{ +\if{html}{\out{
}}\preformatted{options(tinytable_tt_digits = 4) +tt(head(iris)) +}\if{html}{\out{
}} + +You can set options in a script or via \code{.Rprofile}. Note: be cautious with \code{.Rprofile} settings as they may affect reproducibility. +\subsection{Default values for function arguments}{ +\subsection{tt()}{ \itemize{ -\item \code{options("tinytable_quarto_figure" = FALSE)}: Typst only. Normally, it is best to allow Quarto to define the figure environment, so the default behavior is to not include one. +\item \code{tinytable_tt_digits} +\item \code{tinytable_tt_caption} +\item \code{tinytable_tt_notes} +\item \code{tinytable_tt_width} +\item \code{tinytable_tt_theme} +\item \code{tinytable_tt_rownames} } } -\subsection{Data Processing}{ - -The \code{format_tt(quarto=TRUE)} argument activates Quarto data processing for specific cells. This funcationality comes with a few warnings: -\enumerate{ -\item Currently, Quarto provides a \verb{\\QuartoMarkdownBase64\{\}} LaTeX macro, but it does not appear to do anything with it. References and markdown codes may not be processed as expected in LaTeX. -\item Quarto data processing can enter in conflict with \code{tinytable} styling or formatting options. See below for how to disable it. +\subsection{format_tt()}{ +\itemize{ +\item \code{tinytable_format_digits} +\item \code{tinytable_format_num_fmt} +\item \code{tinytable_format_num_zero} +\item \code{tinytable_format_num_suffix} +\item \code{tinytable_format_num_mark_big} +\item \code{tinytable_format_num_mark_dec} +\item \code{tinytable_format_date} +\item \code{tinytable_format_bool} +\item \code{tinytable_format_other} +\item \code{tinytable_format_replace} +\item \code{tinytable_format_escape} +\item \code{tinytable_format_markdown} +\item \code{tinytable_format_quarto} +\item \code{tinytable_format_fn} +\item \code{tinytable_format_sprintf} +} } -\code{options(tinytable_quarto_disable_processing = TRUE)} +\subsection{save_tt()}{ +\itemize{ +\item \code{tinytable_save_overwrite} +} +} -Disable Quarto processing of cell content. Setting this global option to \code{FALSE} may lead to conflicts with some \code{tinytable} features, but it also allows use of markdown and Quarto-specific code in table cells, such as cross-references. +\subsection{theme_tt()}{ -\if{html}{\out{
}}\preformatted{x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") -fn <- function(z) sprintf("", z) -tt(x) |> format_tt(i = 1, fn = fn) -}\if{html}{\out{
}} - -See this link for more details: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing +Placement: +\itemize{ +\item \code{tinytable_theme_placement_float} +\item \code{tinytable_theme_placement_horizontal} } +Resize: +\itemize{ +\item \code{tinytable_theme_resize_width} +\item \code{tinytable_theme_resize_direction} } -\subsection{HTML}{ +Multipage: \itemize{ -\item \code{options(tinytable_html_mathjax = TRUE)} +\item \code{tinytable_theme_multipage_rowhead} +\item \code{tinytable_theme_multipage_rowfoot} +} + +Tabular: \itemize{ -\item insert MathJax scripts in the HTML document. Warning: This may conflict with other elements of the page if MathJax is otherwise loaded. +\item \code{tinytable_theme_tabular_style} +} } -\item \code{options(tinytable_html_portable = TRUE)} + +\subsection{print.tinytable()}{ \itemize{ -\item \code{plot_tt()} inserts base 64 encoded images directly in the HTML file rather than use external links. +\item \code{tinytable_print_output} } } + } -\subsection{PDF}{ +\subsection{Output-specific options}{ +\subsection{HTML}{ \itemize{ -\item \code{options(tinytable_pdf_clean = TRUE)} +\item \code{tinytable_html_mathjax}: Insert MathJax scripts (warning: may conflict if MathJax is loaded elsewhere) +\item \code{tinytable_html_portable}: Insert base64 encoded images directly in HTML for \code{plot_tt()} +} +} + +\subsection{PDF}{ \itemize{ -\item deletes temporary and log files. +\item \code{tinytable_pdf_clean}: Delete temporary and log files +\item \code{tinytable_pdf_engine}: Choose between "xelatex", "pdflatex", "lualatex" +} } -\item \code{options(tinytable_pdf_engine = "xelatex")} + +\subsection{Quarto}{ + +The \code{format_tt(quarto=TRUE)} argument enables Quarto data processing with some limitations: +\enumerate{ +\item The \verb{\\QuartoMarkdownBase64\{\}} LaTeX macro may not process references and markdown as expected +\item Quarto processing may conflict with \code{tinytable} styling/formatting +} + +Options: \itemize{ -\item "xelatex", "pdflatex", "lualatex" +\item \code{tinytable_quarto_disable_processing}: Disable Quarto cell processing +\item \code{tinytable_print_rstudio_notebook}: Display tables "inline" or in "viewer" for RStudio notebooks +\item \code{tinytable_quarto_figure}: Control Typst figure environment in Quarto } + +Example of Quarto-specific code in cells: + +\if{html}{\out{
}}\preformatted{x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") +fn <- function(z) sprintf("", z) +tt(x) |> format_tt(i = 1, fn = fn) +}\if{html}{\out{
}} + +For more details on Quarto table processing: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing } + } } @@ -157,9 +241,9 @@ x <- mtcars[1:4, 1:5] tt(x) tt(x, - theme = "striped", - width = 0.5, - caption = "Data about cars.") + theme = "striped", + width = 0.5, + caption = "Data about cars.") tt(x, notes = "Hello World!") @@ -168,6 +252,6 @@ tab <- tt(x, notes = list("*" = fn)) print(tab, "latex") k <- data.frame(x = c(0.000123456789, 12.4356789)) -tt(k, digits=2) +tt(k, digits = 2) } diff --git a/sandbox/latex.qmd b/sandbox/latex.qmd new file mode 100644 index 00000000..3256603c --- /dev/null +++ b/sandbox/latex.qmd @@ -0,0 +1,16 @@ +--- +format: pdf +--- + +```{r} +pkgload::load_all() +dat <- data.frame(a = c("(03.1)", "(3.14)**", "(003.1416)+")) +tt(dat) |> style_tt(align = "d") +``` + +```{r} +dat <- data.frame(a = c("(03.1)", "(3.14)**", "(003.1416)+")) +tt(dat) |> + group_tt(j = list("blah" = 1)) |> + style_tt(align = "d") +``` diff --git a/sandbox/quarto_processing.qmd b/sandbox/quarto_processing.qmd index 6b24b2fb..fb16e054 100644 --- a/sandbox/quarto_processing.qmd +++ b/sandbox/quarto_processing.qmd @@ -36,4 +36,4 @@ tt(x) |> format_tt(replace = " ", quarto = TRUE) ```{r} #| eval: false tt(x) |> format_tt(replace = "+", quarto = TRUE) -``` \ No newline at end of file +``` diff --git a/sandbox/typst.qmd b/sandbox/typst.qmd index bd94b29d..0e02396e 100644 --- a/sandbox/typst.qmd +++ b/sandbox/typst.qmd @@ -12,13 +12,12 @@ options(tinytable_print_output = "typst") ``` ```{r} -dat <- data.frame( - a = c("a", "aa", "aaa"), - b = c("b", "bb", "bbb"), - c = c("c", "cc", "ccc")) -tt(dat) |> style_tt(j = 1:3, align = "lcr") +tt(head(iris), caption = "Hello World", notes = "This is a note") |> + style_tt("notes", color = "orange", italic = TRUE) |> + style_tt("caption", color = "green", bold = TRUE, strikeout = TRUE) ``` + ```{r} # Semi-complicated tab <- tt(mtcars[1:4, 1:5], caption = "Hello World") |> @@ -41,7 +40,7 @@ tab ```{r} # Issue #139 tab <- tt(mtcars[1:5, 1:5]) |> - style_tt(2:3, 2:3, line_color = "red", line = "tblr", line_width = .05) + style_tt(2:3, 2:3, line_color = "red", line = "tblr", line_width = .05) tab ``` @@ -58,7 +57,8 @@ dat <- data.frame( w = c(143002.2092, 201399.181, 100188.3883), x = c(1.43402, 201.399, 0.134588), y = as.Date(c(897, 232, 198), origin = "1970-01-01"), - z = c(TRUE, TRUE, FALSE)) + z = c(TRUE, TRUE, FALSE) +) dat <- tt(dat, digits = 2) dat ``` @@ -68,7 +68,8 @@ dat dat <- data.frame( a = c("Burger", "Halloumi", "Tofu", "Beans"), b = c(1.43202, 201.399, 0.146188, 0.0031), - c = c(98938272783457, 7288839482, 29111727, 93945)) + c = c(98938272783457, 7288839482, 29111727, 93945) +) tab <- tt(dat) |> format_tt(j = "a", sprintf = "Food: %s") |> format_tt(j = 2, digits = 1) |> @@ -124,7 +125,8 @@ dat <- tt(dat) |> group_tt(i = list( "I like (fake) hamburgers" = 3, "She prefers halloumi" = 4, - "They love tofu" = 7)) + "They love tofu" = 7 + )) dat ``` @@ -137,7 +139,9 @@ tab <- tt(dat) |> j = list( "Hamburgers" = 1:3, "Halloumi" = 4:5, - "Tofu" = 7)) + "Tofu" = 7 + ) + ) tab ``` @@ -154,19 +158,25 @@ tab #| warnings: false # issue #323 dat <- mtcars[1:9, 1:8] -tab <- tt(dat) |> +tab <- tt(dat) |> group_tt( - i = list("I like (fake) hamburgers" = 3, - "She prefers halloumi" = 4, - "They love tofu" = 7), - j = list("Hamburgers" = 1:3, - "Halloumi" = 4:5, - "Tofu" = 7)) |> + i = list( + "I like (fake) hamburgers" = 3, + "She prefers halloumi" = 4, + "They love tofu" = 7 + ), + j = list( + "Hamburgers" = 1:3, + "Halloumi" = 4:5, + "Tofu" = 7 + ) + ) |> style_tt( i = c(3, 5, 9), align = "c", background = "black", - color = "orange") |> + color = "orange" + ) |> style_tt(i = -1, color = "orange") tab ``` @@ -187,3 +197,20 @@ tt(head(iris)) |> group_tt(i = list("hello" = 2, "world" = 2)) tt(head(iris), notes = "blah") ``` + +# align + +```{r} +dat <- data.frame( + a = c("a", "aa", "aaa"), + b = c("b", "bb", "bbb"), + c = c("c", "cc", "ccc") +) +tt(dat) +``` +```{r} +tt(dat) |> style_tt(align = "c") +``` +```{r} +tt(dat) |> style_tt(align = "lcr") +``` diff --git a/tests/tinytest.R b/tests/tinytest.R index 09bf3bf6..c4b167e7 100644 --- a/tests/tinytest.R +++ b/tests/tinytest.R @@ -1,5 +1,3 @@ - -if ( requireNamespace("tinytest", quietly=TRUE) ){ +if (requireNamespace("tinytest", quietly = TRUE)) { tinytest::test_package("tinytable") } - diff --git a/vignettes/alternatives.qmd b/vignettes/alternatives.qmd index 94e62c43..f02441f0 100644 --- a/vignettes/alternatives.qmd +++ b/vignettes/alternatives.qmd @@ -29,12 +29,12 @@ How does `tinytable` compare to alternative table-drawing packages in `R`? There ```{r, include=FALSE} db <- tools::CRAN_package_db() -dep_kableExtra <- length(tools::package_dependencies("kableExtra", recursive=TRUE, db=db)[[1]]) -dep_gt <- length(tools::package_dependencies("gt", recursive=TRUE, db=db)[[1]]) -dep_flextable <- length(tools::package_dependencies("flextable", recursive=TRUE, db=db)[[1]]) -dep_huxtable <- length(tools::package_dependencies("huxtable", recursive=TRUE, db=db)[[1]]) -dep_DT <- length(tools::package_dependencies("DT", recursive=TRUE, db=db)[[1]]) -dep_reactable <- length(tools::package_dependencies("reactable", recursive=TRUE, db=db)[[1]]) +dep_kableExtra <- length(tools::package_dependencies("kableExtra", recursive = TRUE, db = db)[[1]]) +dep_gt <- length(tools::package_dependencies("gt", recursive = TRUE, db = db)[[1]]) +dep_flextable <- length(tools::package_dependencies("flextable", recursive = TRUE, db = db)[[1]]) +dep_huxtable <- length(tools::package_dependencies("huxtable", recursive = TRUE, db = db)[[1]]) +dep_DT <- length(tools::package_dependencies("DT", recursive = TRUE, db = db)[[1]]) +dep_reactable <- length(tools::package_dependencies("reactable", recursive = TRUE, db = db)[[1]]) ``` Here are a few totally biased (and possibly unfair) comments about each of them. diff --git a/vignettes/custom.qmd b/vignettes/custom.qmd index 96254aa1..1a3a68d4 100644 --- a/vignettes/custom.qmd +++ b/vignettes/custom.qmd @@ -49,7 +49,16 @@ We can also combine several Bootstrap classes. Here, we get a table with the "ho ```{r, eval = knitr::is_html_output()} tt(x) |> style_tt( - bootstrap_class = "table table-hover") + bootstrap_class = "table table-hover" +) +``` + + +By default, Bootstrap 5 places captions at the bottom of the table. This can be changed by using a different class: + +```{r} +tt(head(iris), caption = "A caption on top") |> + style_tt(bootstrap_class = "table caption-top") ``` ::: @@ -104,12 +113,13 @@ css_rule <- " } " -tt(x, width = 2/3) |> +tt(x, width = 2 / 3) |> style_tt( j = 1:5, align = "ccccc", bootstrap_class = "table mytable", - bootstrap_css_rule = css_rule) + bootstrap_css_rule = css_rule + ) ``` @@ -128,8 +138,9 @@ css <- " tt(mtcars[1:10, 1:8]) |> style_tt( - bootstrap_class = "table table-borderless squirreltable", - bootstrap_css_rule = css) + bootstrap_class = "table table-borderless squirreltable", + bootstrap_css_rule = css + ) ``` ::: @@ -200,7 +211,7 @@ The Inner block, enclosed in `{}`, defines specific styles like column formats ( We can create this code easily by passing a string to the `tabularray_inner` argument of the `style_tt()` function: ```{r, eval = knitr::is_latex_output()} -##| tbl-cap: "\\LaTeX{} table with colors and a spanning cell." +## | tbl-cap: "\\LaTeX{} table with colors and a spanning cell." inner <- " column{1-4}={halign=c}, hlines = {fg=white}, @@ -346,15 +357,18 @@ library("shiny") library("tinytable") fn <- paste(tempfile(), ".html") -tab <- tt(mtcars[1:5, 1:4]) |> - style_tt(i = 0:5, color = "orange", background = "black") |> - save_tt(fn) +tab <- tt(mtcars[1:5, 1:4]) |> + style_tt(i = 0:5, color = "orange", background = "black") |> + save_tt(fn) shinyApp( ui = fluidPage( - fluidRow(column(12, h1("This is test of tinytable"), - shiny::includeHTML(fn)))), - server = function(input, output) { + fluidRow(column( + 12, h1("This is test of tinytable"), + shiny::includeHTML(fn) + )) + ), + server = function(input, output) { } ) ``` diff --git a/vignettes/faq.qmd b/vignettes/faq.qmd index f6bd46ca..f4a17abc 100644 --- a/vignettes/faq.qmd +++ b/vignettes/faq.qmd @@ -165,17 +165,24 @@ With these changes, the table should appear with colors as expected. ## Typst -### Captions and labels +### Quarto -Due to a quirk in Quarto [reported here,](https://github.com/quarto-dev/quarto-cli/issues/9369) captions in Typst and Quarto documents need to be specified using *both* the `tbl-cap` and the `label` chunk option: +By default `tinytable` uses Quarto's own figure handling to set captions and figure blocks. This allows cross-references to work. For this to work well, users should specify _both_ the table label and the table caption explicitly using chunk options. Note that the label must imperatively start with `tbl-`: -````{verbatim} -```{r} -#| tbl-cap: "blah blah blah" -#| label: tbl-blah -tinytable::tt(head(iris, 5)) +```r +#| label: tbl-example +#| tbl-cap: This is an example table +library(tinytable) +tt(head(iris)) ``` -```` + +Alternatively, users can disable Quarto table handling and rely on internal `tinytable` options instead. + +```r +options(tinytable_quarto_figure = FALSE) +``` + +Doing this will prevent styles to bleed over from one table to the next. ### Multi-page long tables @@ -213,103 +220,38 @@ These arguments are already implemented in the form of "pseudo-spans", meaning t One alternative would be to remove line segments in finalize_grid(). I tried this but it is tricky and the results were brittle, so I rolled it back. I'm open to considering a PR if someone wants to contribute code, but please discuss the feature design in an issue with me before working on this. -## Quarto - -### Custom crossref styles -In `Quarto`, it is possible to create a custom crossref type for things like appendix tables. One challenge, is that LaTeX will not allow users to nest a `tblr` environment, inside a `table` environment, inside the new environment that `Quarto` creates for the crossref. Therefore, when rendering a table to LaTeX/PDF, it is important to drop the `\begin{table}` environment. This can be done using the `theme_tt()` function. -In the example below, we call `theme_tt()` explicitly for a single table, but the [themes vignette](https://vincentarelbundock.github.io/tinytable/vignettes/theme.html) shows how to set a global theme using the `tinytable_tt_theme` option. +## Word (`.docx`) -````{verbatim} ---- -title: "Crossref Example" -format: - pdf: default - html: default -crossref: - custom: - - kind: float - key: apptbl - latex-env: apptbl - reference-prefix: Table A - space-before-numbering: false - latex-list-of-description: Appendix Table -apptbl-cap-location: top ---- - -See @apptbl-testing - -::: {#apptbl-testing} +Word document documents are created in two steps: -```{r} -library(tinytable) - -tt(mtcars[1:5,]) |> theme_tt("tabular", style = "tabularray") -``` - -Caption goes here. +1. Generates a markdown table. +2. Call the external [Pandoc software](https://pandoc.org/) to convert the markdown table to a Word document. -::: -```` +This workflow limits the range of styling options available in Word. Indeed, many arguments in the `style_tt()` function do not have formal markdown notation to represent them, and are thus not available. For example, while `italic`, `bold`, and `strikeout`, are supported, `color` and `background` are not. -### Sub-captions +Note that other `tinytable` functions such as `group_tt()` and `format_tt()` and `plot_tt()` should work as expected in Word. -With version 0.4.0 of `tinytable` and versions above 1.6 of Quarto---only available [as a pre-release build at the time of writing](https://quarto.org/docs/download/prerelease.html)--- users can specify sub-captions for tables. This is done by adding a `tbl-subcap` chunk option to the table chunk. We also need to use a `tinytable` theme to remove built-in table structure and let Quarto handle the table construction. Here is a simple example document: +Users who want full styling capabilities in Word can save tables as image files and insert them in their documents. Here is an example Quarto notebook illustrating this workflow. ````{verbatim} --- -format: pdf +format: docx --- -See @tbl-example, @tbl-example-1, or @tbl-example-2. - ```{r} -#| label: tbl-example -#| tbl-cap: "Example" -#| tbl-subcap: -#| - "Cars" -#| - "Pressure" -#| layout-ncol: 2 - +#| out-width: "50%" library(tinytable) -tt(head(cars)) |> theme_tt("tabular", style = "tabularray") -tt(head(pressure)) |> theme_tt("tabular", style = "tabularray") -``` -```` - -### Same table, different styles -In some cases, the user wants to print a single table multiple times with different styles in a single HTML document. This will sometimes cause issues, because the `style_tt()` function inserts several javascript functions to modify the same table, thus creating conflicts. A simple solution is to change the unique ID of the table object manually. +options(tinytable_save_overwrite = TRUE) -Consider this RevalJS slideshow in which we sequentially highlight different rows of the data frame: +tt(mtcars[1:10, 1:5]) |> + style_tt(j = 2:3, background = "black", color = "white") |> + save_tt("table_01.png") -````{verbatim} ---- -format: revealjs ---- - -## Page 1 - -```{r} -library(tinytable) - -tab <- tt(head(iris)) -tab -``` - -## Page 2 - -```{r} -tab@id <- "table_01" -tab |> style_tt(i = 3, background = "skyblue") -``` - -## Page 3 - -```{r} -tab@id <- "table_02" -tab |> style_tt(i = 5, background = "orange") +knitr::include_graphics("table_01.png") ``` ```` + diff --git a/vignettes/figures/gallery/gallery.sh b/vignettes/figures/gallery/gallery.sh new file mode 100755 index 00000000..b8d32d70 --- /dev/null +++ b/vignettes/figures/gallery/gallery.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +# Define the output GIF filename +output_gif="tinytable_gallery.gif" + +# Use ImageMagick to create an animated GIF from images starting with 'tinytable_gallery_' +# -delay is increased for a slower animation (e.g., 100 equals 1 second per frame) +# -resize option is used to fit images within a 1280x720 frame (16:9 aspect ratio) +# convert -delay 250 -loop 0 tinytable_gallery_*.png -resize 1250x690 -gravity center -extent 1280x720 "$output_gif" +# convert -delay 250 -loop 0 tinytable_gallery_*.png -resize 1000x500 -gravity center -extent 1025x576 "$output_gif" +convert -delay 200 -loop 0 tinytable_gallery_*.png -resize 1000x500 -gravity center -extent 1025x576 -layers Optimize -colors 128 "$output_gif" + +# Display a message when done +echo "Animated GIF created: $output_gif" diff --git a/vignettes/figures/gallery/tinytable_gallery_00.png b/vignettes/figures/gallery/tinytable_gallery_00.png new file mode 100755 index 00000000..9e6ce448 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_00.png differ diff --git a/vignettes/figures/gallery/tinytable_gallery_01.png b/vignettes/figures/gallery/tinytable_gallery_01.png new file mode 100755 index 00000000..04973678 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_01.png differ diff --git a/vignettes/figures/gallery/tinytable_gallery_02.png b/vignettes/figures/gallery/tinytable_gallery_02.png new file mode 100755 index 00000000..07de0df4 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_02.png differ diff --git a/vignettes/figures/gallery/tinytable_gallery_03.png b/vignettes/figures/gallery/tinytable_gallery_03.png new file mode 100755 index 00000000..39791189 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_03.png differ diff --git a/vignettes/figures/gallery/tinytable_gallery_04.png b/vignettes/figures/gallery/tinytable_gallery_04.png new file mode 100755 index 00000000..889cef25 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_04.png differ diff --git a/vignettes/figures/gallery/tinytable_gallery_06.png b/vignettes/figures/gallery/tinytable_gallery_06.png new file mode 100755 index 00000000..a1a60321 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_06.png differ diff --git a/vignettes/figures/gallery/tinytable_gallery_07.png b/vignettes/figures/gallery/tinytable_gallery_07.png new file mode 100755 index 00000000..48b981d0 Binary files /dev/null and b/vignettes/figures/gallery/tinytable_gallery_07.png differ diff --git a/vignettes/figures/spider.png b/vignettes/figures/spider.png new file mode 100755 index 00000000..a017a78f Binary files /dev/null and b/vignettes/figures/spider.png differ diff --git a/vignettes/figures/spider_long.png b/vignettes/figures/spider_long.png new file mode 100755 index 00000000..559e6af5 Binary files /dev/null and b/vignettes/figures/spider_long.png differ diff --git a/vignettes/figures/squirrel.png b/vignettes/figures/squirrel.png new file mode 100755 index 00000000..5b11d688 Binary files /dev/null and b/vignettes/figures/squirrel.png differ diff --git a/vignettes/figures/tinytable_logo.png b/vignettes/figures/tinytable_logo.png new file mode 100755 index 00000000..9e6ce448 Binary files /dev/null and b/vignettes/figures/tinytable_logo.png differ diff --git a/vignettes/figures/tinytable_logo.svg b/vignettes/figures/tinytable_logo.svg new file mode 100755 index 00000000..c7f16e0b --- /dev/null +++ b/vignettes/figures/tinytable_logo.svg @@ -0,0 +1,59 @@ + + + + + + + + + tinytable + + diff --git a/vignettes/figures/tinytable_logo_notext.png b/vignettes/figures/tinytable_logo_notext.png new file mode 100755 index 00000000..1ee18de8 Binary files /dev/null and b/vignettes/figures/tinytable_logo_notext.png differ diff --git a/vignettes/figures/tinytable_logo_notext.svg b/vignettes/figures/tinytable_logo_notext.svg new file mode 100644 index 00000000..694d8edc --- /dev/null +++ b/vignettes/figures/tinytable_logo_notext.svg @@ -0,0 +1,52 @@ + + + + + + + + + + diff --git a/vignettes/figures/tinytable_logo_notext_white.png b/vignettes/figures/tinytable_logo_notext_white.png new file mode 100644 index 00000000..0747f762 Binary files /dev/null and b/vignettes/figures/tinytable_logo_notext_white.png differ diff --git a/vignettes/format.qmd b/vignettes/format.qmd index a8721edf..75a5ff06 100644 --- a/vignettes/format.qmd +++ b/vignettes/format.qmd @@ -33,10 +33,11 @@ In a very simple case---such as printing 2 significant digits of all numeric var ```{r} dat <- data.frame( - w = c(143002.2092, 201399.181, 100188.3883), - x = c(1.43402, 201.399, 0.134588), - y = as.Date(sample(1:1000, 3), origin = "1970-01-01"), - z = c(TRUE, TRUE, FALSE)) + w = c(143002.2092, 201399.181, 100188.3883), + x = c(1.43402, 201.399, 0.134588), + y = as.Date(sample(1:1000, 3), origin = "1970-01-01"), + z = c(TRUE, TRUE, FALSE) +) tt(dat, digits = 2) ``` @@ -44,27 +45,31 @@ tt(dat, digits = 2) We can get more fine-grained control over formatting by calling `format_tt()` after `tt()`, optionally by specifying the columns to format with `j`: ```{r} -tt(dat) |> +tt(dat) |> format_tt( j = 2:4, digits = 1, - date = "%B %d %Y") |> + date = "%B %d %Y", + bool = tolower + ) |> format_tt( j = 1, digits = 2, num_mark_big = " ", num_mark_dec = ",", num_zero = TRUE, - num_fmt = "decimal") + num_fmt = "decimal" + ) ``` We can use a regular expression in `j` to select columns, and the `?sprintf` function to format strings, numbers, and to do [string interpolation](https://en.wikipedia.org/wiki/String_interpolation) (similar to the `glue` package, but using Base `R`): ```{r} dat <- data.frame( - a = c("Burger", "Halloumi", "Tofu", "Beans"), - b = c(1.43202, 201.399, 0.146188, 0.0031), - c = c(98938272783457, 7288839482, 29111727, 93945)) + a = c("Burger", "Halloumi", "Tofu", "Beans"), + b = c(1.43202, 201.399, 0.146188, 0.0031), + c = c(98938272783457, 7288839482, 29111727, 93945) +) tt(dat) |> format_tt(j = "a", sprintf = "Food: %s") |> format_tt(j = 2, digits = 1) |> @@ -172,15 +177,13 @@ tt(dat) |> ## Replacement -Missing values can be replaced by a custom string using the `replace` argument (default `""`): +Missing values can be replaced by a custom string using the `replace` argument: ```{r} tab <- data.frame(a = c(NA, 1, 2), b = c(3, NA, 5)) tt(tab) -tt(tab) |> format_tt() - tt(tab) |> format_tt(replace = "-") ``` @@ -199,8 +202,8 @@ LaTeX and HTML use special characters to indicate strings which should be interp ```{r} dat <- data.frame( - "LaTeX" = c("Dollars $", "Percent %", "Underscore _"), - "HTML" = c("
", "4", "blah") + "LaTeX" = c("Dollars $", "Percent %", "Underscore _"), + "HTML" = c("
", "4", "blah") ) tt(dat) |> format_tt(escape = TRUE) @@ -217,10 +220,10 @@ format_tt("_ Dollars $", escape = "latex") Markdown can be rendered in cells by using the `markdown` argument of the `format_tt()` function (note: this requires installing the `markdown` as an optional dependency). ```{r} -dat <- data.frame( markdown = c( +dat <- data.frame(markdown = c( "This is _italic_ text.", - "This sentence ends with a superscript.^2^") -) + "This sentence ends with a superscript.^2^" +)) tt(dat) |> format_tt(j = 1, markdown = TRUE) |> @@ -269,7 +272,7 @@ tt(dat) |> format_tt(j = 1, markdown = TRUE) On top of the built-in features of `format_tt`, a custom formatting function can be specified via the `fn` argument. The `fn` argument takes a function that accepts a single vector and returns a string (or something that coerces to a string like a number). ```{r} -tt(x) |> +tt(x) |> format_tt(j = "mpg", fn = function(x) paste(x, "mi/gal")) |> format_tt(j = "drat", fn = \(x) signif(x, 2)) ``` @@ -290,9 +293,9 @@ thumbdrives <- data.frame( tt(thumbdrives) |> format_tt(j = 1, fn = scales::label_date("%e %b", locale = "fr")) |> format_tt(j = 2, fn = scales::label_currency()) |> - format_tt(j = 3, fn = scales::label_ordinal()) |> - format_tt(j = 4, fn = scales::label_bytes()) |> - format_tt(j = 5, fn = scales::label_percent()) |> + format_tt(j = 3, fn = scales::label_ordinal()) |> + format_tt(j = 4, fn = scales::label_bytes()) |> + format_tt(j = 5, fn = scales::label_percent()) |> format_tt(escape = TRUE) ``` diff --git a/vignettes/group.qmd b/vignettes/group.qmd index b52ba90e..d61adea5 100644 --- a/vignettes/group.qmd +++ b/vignettes/group.qmd @@ -53,18 +53,21 @@ tt(head(iris)) |> We can style group rows in the same way as regular rows: ```{r} -tt(dat) |> +tt(dat) |> group_tt( i = list( "I like (fake) hamburgers" = 3, "She prefers halloumi" = 4, - "They love tofu" = 7)) |> + "They love tofu" = 7 + ) + ) |> style_tt( i = c(3, 5, 9), align = "c", color = "white", background = "gray", - bold = TRUE) + bold = TRUE + ) ``` ### Automatic row groups @@ -73,7 +76,9 @@ We can use the `group_tt()` function to group rows and label them using spanners ```{r} # subset and sort data -df <- mtcars |> head(10) |> sort_by(~ am) +df <- mtcars |> + head(10) |> + sort_by(~am) # draw table tt(df) |> group_tt(i = df$am) @@ -85,7 +90,7 @@ tt(df) |> group_tt(i = df$am) The syntax for column groups is very similar, but we use the `j` argument instead. The named list specifies the labels to appear in column-spanning labels, and the values must be a vector of consecutive and non-overlapping integers that indicate which columns are associated to which labels: ```{r} -tt(dat) |> +tt(dat) |> group_tt( j = list( "Hamburgers" = 1:3, @@ -97,19 +102,25 @@ Here is a table with both row and column headers, as well as some styling: ```{r} dat <- mtcars[1:9, 1:8] -tt(dat) |> +tt(dat) |> group_tt( - i = list("I like (fake) hamburgers" = 3, - "She prefers halloumi" = 4, - "They love tofu" = 7), - j = list("Hamburgers" = 1:3, - "Halloumi" = 4:5, - "Tofu" = 7)) |> + i = list( + "I like (fake) hamburgers" = 3, + "She prefers halloumi" = 4, + "They love tofu" = 7 + ), + j = list( + "Hamburgers" = 1:3, + "Halloumi" = 4:5, + "Tofu" = 7 + ) + ) |> style_tt( i = c(3, 5, 9), align = "c", background = "teal", - color = "white") |> + color = "white" + ) |> style_tt(i = -1, color = "teal") ``` diff --git a/vignettes/notebooks.qmd b/vignettes/notebooks.qmd new file mode 100644 index 00000000..4e8cd233 --- /dev/null +++ b/vignettes/notebooks.qmd @@ -0,0 +1,208 @@ +# Notebooks + + +## Quarto + +### Slides: RevealjS + +Quarto can create slides using [the RevealJS framework](https://revealjs.com/). Unfortunately, RevealJS does not include Bootstrap, so `tinytable` will not be as pretty as in other HTML documents, and the font size will often be too big. + +A good workaround is to use the `theme_revealjs()` function. For a one time use: + +````{verbatim} +```{r} +library(tinytable) +tt(head(iris)) |> theme_revealjs() +``` +```` + +To style all tables in a slide show, use a global option: + +````{verbatim} +```{r} +options(tinytable_tt_theme = "revealjs") +tt(head(iris)) +``` +```` + +To select a specific font size, use the `fontsize` argument: + +````{verbatim} +# Slide title + +This is a nice table: + +```{r} +library(tinytable) +options(tinytable_tt_theme = \(x) theme_tt(x, "revealjs", fontsize = .5)) +tt(head(iris)) +``` +```` + +### Custom crossref styles + +In `Quarto`, it is possible to create a custom crossref type for things like appendix tables. One challenge, is that LaTeX will not allow users to nest a `tblr` environment, inside a `table` environment, inside the new environment that `Quarto` creates for the crossref. Therefore, when rendering a table to LaTeX/PDF, it is important to drop the `\begin{table}` environment. This can be done using the `theme_tt()` function. + +In the example below, we call `theme_tt()` explicitly for a single table, but the [themes vignette](https://vincentarelbundock.github.io/tinytable/vignettes/theme.html) shows how to set a global theme using the `tinytable_tt_theme` option. + +````{verbatim} +--- +title: "Crossref Example" +format: + pdf: default + html: default +crossref: + custom: + - kind: float + key: apptbl + latex-env: apptbl + reference-prefix: Table A + space-before-numbering: false + latex-list-of-description: Appendix Table +apptbl-cap-location: top +--- + +See @apptbl-testing + +::: {#apptbl-testing} + +```{r} +library(tinytable) + +tt(mtcars[1:5, ]) |> theme_tt("tabular", style = "tabularray") +``` + +Caption goes here. + +::: +```` + +### Sub-captions + +With version 0.4.0 of `tinytable` and versions above 1.6 of Quarto---only available [as a pre-release build at the time of writing](https://quarto.org/docs/download/prerelease.html)--- users can specify sub-captions for tables. This is done by adding a `tbl-subcap` chunk option to the table chunk. We also need to use a `tinytable` theme to remove built-in table structure and let Quarto handle the table construction. Here is a simple example document: + +````{verbatim} +--- +format: pdf +--- + +See @tbl-example, @tbl-example-1, or @tbl-example-2. + +```{r} +#| label: tbl-example +#| tbl-cap: "Example" +#| tbl-subcap: +#| - "Cars" +#| - "Pressure" +#| layout-ncol: 2 + +library(tinytable) +tt(head(cars)) |> theme_tt("tabular", style = "tabularray") +tt(head(pressure)) |> theme_tt("tabular", style = "tabularray") +``` +```` + +### Same table, different styles + +In some cases, the user wants to print a single table multiple times with different styles in a single HTML document. This will sometimes cause issues, because the `style_tt()` function inserts several javascript functions to modify the same table, thus creating conflicts. A simple solution is to change the unique ID of the table object manually. + +Consider this RevalJS slideshow in which we sequentially highlight different rows of the data frame: + +````{verbatim} +--- +format: revealjs +--- + +## Page 1 + +```{r} +library(tinytable) + +tab <- tt(head(iris)) +tab +``` + +## Page 2 + +```{r} +tab@id <- "table_01" +tab |> style_tt(i = 3, background = "skyblue") +``` + +## Page 3 + +```{r} +tab@id <- "table_02" +tab |> style_tt(i = 5, background = "orange") +``` +```` + +### Typst + +See [the FAQ on Typst](https://vincentarelbundock.github.io/tinytable/vignettes/faq.html#typst) for important notes on using Typst in Quarto documents. + + + +## Rmarkdown + + +### `papaja` + + +`papaja` is a package to assist in the preparation of APA manuscripts. Cross-references can be a bit challenging to implement when using this package with `tinytable`. When the target format is PDF, one workaround is to use raw LaTeX code to make renferences and labels. + +For example: + +````{verbatim} +--- +output : + papaja::apa6_pdf: + latex_engine: xelatex + fig_caption: yes + keep_tex: false +header-includes : + - \usepackage{tabularray} + - \usepackage{graphicx} + - \UseTblrLibrary{booktabs} + - \UseTblrLibrary{siunitx} + - \newcommand{\tinytableTabularrayUnderline}[1]{\underline{#1}} + - \newcommand{\tinytableTabularrayStrikeout}[1]{\sout{#1}} + - \NewTableCommand{\tinytableDefineColor}[3]{\definecolor{#1}{#2}{#3}} + - \usepackage{caption,fixltx2e} + - \usepackage[table]{xcolor} +--- + +# tidytable + +Table \ref{tab:tinytableref} + +```{r} +library(tinytable) +tt(head(iris), caption = "\\label{tab:tinytableref} Hello world!") |> + style_tt(color = "blue") +``` +```{r} +```` + + + + + +## Bookdown + +### Cross-references + +The `bookdown` package uses a special syntax to handle cross-references, and it does not recognize `tinytable` objects as tables automatically. To include cross-references to tables, it is thus necessary to use the `caption` argument of `tinytable::tt()`, and to insert a `bookdown` label in that caption. Here is an example: + + +````{verbatim} +Table \@ref(tab:tinytableref) + +```{r} +library(tinytable) +tt(head(iris), caption = "(#tab:tinytableref) Hello world!") |> + style_tt(color = "blue") +``` +```` + + diff --git a/vignettes/options.qmd b/vignettes/options.qmd deleted file mode 100644 index d15f7897..00000000 --- a/vignettes/options.qmd +++ /dev/null @@ -1,118 +0,0 @@ -# Available Options - -Options can be set with `options()` and change the default behavior of tinytable. For example, to format all tables to 4 digits when calling `tt()`, we can do: - -```r -options(tinytable_tt_digits = 4) -tt(head(iris)) -``` - -You can either set options in a script (usually at the top) or via `.Rprofile`. Note that you want to [be cautious](https://rstats.wtf/r-startup.html) with putting things in `.Rprofile` since they might make results not reproducible (e.g. if you change `tinytable_format_digits` in `.Rprofile`, the table will be formatted differently). - -## Default values for function arguments - -Most options are function specific and allow you to set default values. These all start with `tinytable_X_` where X is `tt`/`format`/`theme`/`print`. See the corresponding help documentation for the what the argument looks like. - -### `tt()` - -Sets default values for `tt()` arguments. - -- `tinytable_tt_digits` -- `tinytable_tt_caption` -- `tinytable_tt_notes` -- `tinytable_tt_width` -- `tinytable_tt_theme` -- `tinytable_tt_rownames` - -### `format_tt()` - -Sets default formats for different kinds of variables. see `format_tt()` - -- `tinytable_format_digits` -- `tinytable_format_num_fmt` -- `tinytable_format_num_zero` -- `tinytable_format_num_suffix` -- `tinytable_format_num_mark_big` -- `tinytable_format_num_mark_dec` -- `tinytable_format_date` -- `tinytable_format_bool` -- `tinytable_format_other` -- `tinytable_format_replace` -- `tinytable_format_escape` -- `tinytable_format_markdown` -- `tinytable_format_quarto` -- `tinytable_format_fn` -- `tinytable_format_sprintf` - -### `save_tt()` - -- `tinytable_save_overwrite` - -### `theme_tt()` - -When using `theme_tt(theme = "theme_name")`, this allows you to set default arguments to the corresponding theme. See `theme_tt()` for details. - -placement: - -- `tinytable_theme_placement_float` -- `tinytable_theme_placement_horizontal` - -resize: - -- `tinytable_theme_resize_width` -- `tinytable_theme_resize_direction` - -multipage: - -- `tinytable_theme_multipage_rowhead` -- `tinytable_theme_multipage_rowfoot` - -tabular: - -- `tinytable_theme_tabular_style` - -### `print.tinytable()` - -`tinytable_print_output` - - -## Global options - -The rest of the options are a set of global options that apply when the tables are being built. - -### HTML - -* `options(tinytable_html_mathjax = TRUE)` - - insert MathJax scripts in the HTML document. Warning: This may conflict with other elements of the page if MathJax is otherwise loaded. -* `options(tinytable_html_portable = TRUE)` - - `plot_tt()` inserts base 64-encoded images directly in the HTML file rather than use external links. - -### PDF - -* `options(tinytable_pdf_clean = TRUE)` - - deletes temporary and log files. -* `options(tinytable_pdf_engine = "xelatex")` - - `"xelatex"`, `"pdflatex"`, `"lualatex"` - -### Quarto - -The `format_tt(quarto=TRUE)` argument activates Quarto data processing for specific cells. This funcationality comes with a few warnings: - -1. Currently, Quarto provides a `\QuartoMarkdownBase64{}` LaTeX macro, but it does not appear to do anything with it. References and markdown codes may not be processed as expected in LaTeX. -2. Quarto data processing can enter in conflict with `tinytable` styling or formatting options. See below for how to disable it. - -* `options(tinytable_quarto_disable_processing = TRUE)` - - disables Quarto processing of cell content. -* `options(tinytable_quarto_figure = FALSE)` - - by default, do not include Typst tables in a figure environment in Quarto. - - Setting this global option to `FALSE` may lead to conflicts with some `tinytable` features, but it also allows use of markdown and Quarto-specific code in table cells, such as cross-references. - - ```r - x <- data.frame(Math = "x^2^", Citation = "@Lovelace1842") - fn <- function(z) sprintf("", z) - tt(x) |> format_tt(i = 1, fn = fn) - ``` - - See this link for more details: https://quarto.org/docs/authoring/tables.html#disabling-quarto-table-processing - diff --git a/vignettes/plot.qmd b/vignettes/plot.qmd index eb289b92..2c45b7bb 100644 --- a/vignettes/plot.qmd +++ b/vignettes/plot.qmd @@ -35,8 +35,8 @@ dat <- data.frame( ) img <- c( - "../figures/spider.png", - "../figures/squirrel.png" + "figures/spider.png", + "figures/squirrel.png" ) tt(dat) |> @@ -73,7 +73,7 @@ There are several types of inline plots available by default. For example, plot_data <- list(mtcars$mpg, mtcars$hp, mtcars$qsec) dat <- data.frame( - Variables = c("mpg", "hp", "qsec"), + Variables = c("mpg", "hp", "qsec"), Histogram = "", Density = "", Bar = "", @@ -124,10 +124,10 @@ library(ggplot2) f <- function(d, color = "black", ...) { d <- data.frame(x = d) - ggplot(d, aes(x = x)) + + ggplot(d, aes(x = x)) + geom_histogram(bins = 30, color = color, fill = color) + - scale_x_continuous(expand=c(0,0)) + - scale_y_continuous(expand=c(0,0)) + + scale_x_continuous(expand = c(0, 0)) + + scale_y_continuous(expand = c(0, 0)) + theme_void() } @@ -144,7 +144,8 @@ We can insert arbitrarily complex plots by customizing the `ggplot2` call: #| warning: false penguins <- read.csv( "https://vincentarelbundock.github.io/Rdatasets/csv/palmerpenguins/penguins.csv", - na.strings = "") |> na.omit() + na.strings = "" +) |> na.omit() # split data by species dat <- split(penguins, penguins$species) @@ -164,8 +165,8 @@ tab <- data.frame( f <- function(d, ...) { ggplot(d, aes(x = flipper_length_mm, y = body_mass_g, color = sex)) + geom_point(size = .2) + - scale_x_continuous(expand=c(0,0)) + - scale_y_continuous(expand=c(0,0)) + + scale_x_continuous(expand = c(0, 0)) + + scale_y_continuous(expand = c(0, 0)) + scale_color_manual(values = c("#E69F00", "#56B4E9")) + theme_void() + theme(legend.position = "none") @@ -176,7 +177,7 @@ tt(tab) |> plot_tt(j = 2, fun = "histogram", data = body, height = 2) |> plot_tt(j = 3, fun = "density", data = flip, height = 2) |> plot_tt(j = 4, fun = f, data = dat, height = 2) |> - style_tt(j = 2:4, align = "c") + style_tt(j = 2:4, align = "c") ``` diff --git a/vignettes/style.qmd b/vignettes/style.qmd index 470b23f1..47e2a957 100644 --- a/vignettes/style.qmd +++ b/vignettes/style.qmd @@ -54,7 +54,8 @@ tt(x) |> i = 2, j = 3, background = "black", - color = "white") + color = "white" + ) ``` The `i` and `j` accept vectors of integers to modify several cells at once: @@ -65,7 +66,8 @@ tt(x) |> i = 2:3, j = c(1, 3, 4), italic = TRUE, - color = "orange") + color = "orange" + ) ``` We can style all cells in a table by omitting both the `i` and `j` arguments: @@ -104,7 +106,7 @@ tt(x) |> style_tt(j = "^(?!drat|mpg)", color = "orange") Of course, we can also call the `style_tt()` function several times to apply different styles to different parts of the table: ```{r} -tt(x) |> +tt(x) |> style_tt(i = 1, j = 1:2, color = "orange") |> style_tt(i = 1, j = 3:4, color = "green") ``` @@ -143,7 +145,8 @@ To align columns, we use a single character, or a string where each letter repre dat <- data.frame( a = c("a", "aa", "aaa"), b = c("b", "bb", "bbb"), - c = c("c", "cc", "ccc")) + c = c("c", "cc", "ccc") +) tt(dat) |> style_tt(j = 1:3, align = "c") @@ -155,8 +158,8 @@ In LaTeX documents (only), we can use decimal-alignment: ```{r} z <- data.frame(pi = c(pi * 100, pi * 1000, pi * 10000, pi * 100000)) tt(z) |> - format_tt(j = 1, digits = 8, num_fmt = "significant_cell") |> - style_tt(j = 1, align = "d") + format_tt(j = 1, digits = 8, num_fmt = "significant_cell") |> + style_tt(j = 1, align = "d") ``` @@ -173,7 +176,7 @@ tt(x) |> style_tt(j = "mpg|hp|qsec", fontsize = 1.5) Sometimes, it can be useful to make a cell stretch across multiple colums or rows, for example when we want to insert a label. To achieve this, we can use the `colspan` argument. Here, we make the 2nd cell of the 2nd row stretch across three columns and two rows: ```{r} -tt(x)|> style_tt( +tt(x) |> style_tt( i = 2, j = 2, colspan = 3, rowspan = 2, @@ -181,7 +184,8 @@ tt(x)|> style_tt( alignv = "m", color = "white", background = "black", - bold = TRUE) + bold = TRUE +) ``` Here is the original table for comparison: @@ -194,7 +198,7 @@ Spanning cells can be particularly useful when we want to suppress redundant lab ```{r} tab <- aggregate(mpg ~ cyl + am, FUN = mean, data = mtcars) -tab <- tab[order(tab$cyl, tab$am),] +tab <- tab[order(tab$cyl, tab$am), ] tab tt(tab, digits = 2) |> @@ -207,15 +211,15 @@ The `rowspan` feature is also useful to create multi-row labels. For example, in tab <- data.frame(Letters = c("A
B", ""), Numbers = c("First", "Second")) tt(tab) |> - style_tt(bootstrap_class = "table-bordered") + style_tt(bootstrap_class = "table-bordered") ``` Now, we use `colspan` to ensure that that cells in the first column take up less space and are combined into one: ```{r} tt(tab) |> - style_tt(bootstrap_class = "table-bordered") |> - style_tt(1, 1, rowspan = 2) + style_tt(bootstrap_class = "table-bordered") |> + style_tt(1, 1, rowspan = 2) ``` ## Headers @@ -248,11 +252,12 @@ We can use the standard `which` function from Base `R` to create indices and app ```{r} k <- mtcars[1:10, c("mpg", "am", "vs")] -tt(k) |> +tt(k) |> style_tt( i = which(k$am == k$vs), background = "teal", - color = "white") + color = "white" + ) ``` In versions *above* 0.4.0 of `tinytable`, users can also supply a logical matrix of the same size as `x` to indicate which cell should be styled. For example, we can change the colors of certain entries in a correlation matrix as follows: @@ -272,7 +277,8 @@ The `color`, `background`, and `fontsize` arguments are vectorized. This allows tt(x) |> style_tt( i = 1:4, - color = c("red", "blue", "green", "orange")) + color = c("red", "blue", "green", "orange") + ) ``` When using a single value for a vectorized argument, it gets applied to all values: @@ -282,7 +288,8 @@ tt(x) |> style_tt( j = 2:3, color = c("orange", "green"), - background = "black") + background = "black" + ) ``` We can also produce more complex heatmap-like tables to illustrate different font sizes in em units: @@ -307,7 +314,8 @@ tt(k, width = .7, theme = "void") |> j = 1:5, color = fg, background = bg, - fontsize = fs) + fontsize = fs + ) ``` @@ -328,21 +336,22 @@ Here is an example where we draw lines around every border ("t", "b", "l", and " ```{r} tt(x, theme = "void") |> - style_tt( - i = 0:3, - j = 1:3, - line = "tblr", - line_width = 0.4, - line_color = "orange") + style_tt( + i = 0:3, + j = 1:3, + line = "tblr", + line_width = 0.4, + line_color = "orange" + ) ``` And here is an example with horizontal rules: ```{r} tt(x, theme = "void") |> - style_tt(i = 0, line = "t", line_color = "orange", line_width = 0.4) |> - style_tt(i = 1, line = "t", line_color = "purple", line_width = 0.2) |> - style_tt(i = 4, line = "b", line_color = "orange", line_width = 0.4) + style_tt(i = 0, line = "t", line_color = "orange", line_width = 0.4) |> + style_tt(i = 1, line = "t", line_color = "purple", line_width = 0.2) |> + style_tt(i = 4, line = "b", line_color = "orange", line_width = 0.4) ``` @@ -350,25 +359,13 @@ tt(x, theme = "void") |> dat <- data.frame(1:2, 3:4, 5:6, 7:8) colnames(dat) <- NULL -tt(dat, theme = "void") |> +tt(dat, theme = "void") |> style_tt( line = "tblr", line_color = "white", line_width = 0.5, - background = "blue", color = "white") -``` - -## Cell padding (height and width) - -There is no argument in `style_tt()` to control the padding of cells. Thankfully, this is easy to control using CSS and `tabularray` options: - - -```{r} -tt(x) |> style_tt( - bootstrap_css = "padding-right: .2em; padding-top: 2em;", - tabularray_inner = "rowsep={2em}, colsep = {.2em}" -) + background = "blue", color = "white" + ) ``` - ## Markdown and Word Styling for Markdown and Word tables is more limited than for the other formats. In particular: diff --git a/vignettes/theme.qmd b/vignettes/theme.qmd index 402ba799..216a07b3 100644 --- a/vignettes/theme.qmd +++ b/vignettes/theme.qmd @@ -43,6 +43,10 @@ tt(x, theme = "grid") tt(x, theme = "bootstrap") ``` +```{r} +tt(x, theme = "spacing") +``` + ::: {.content-visible when-format="pdf"} ```{r} tt(x, theme = "void") @@ -56,7 +60,7 @@ Users can also define their own themes to apply consistent visual tweaks to tabl ```{r} theme_vincent <- function(x, ...) { - out <- x |> + out <- x |> style_tt(color = "teal") out@caption <- "Always use the same caption." out@width <- .5 @@ -78,14 +82,14 @@ Here is a slightly more complex example. The benefit of this approach is that we ```{r} #| eval: false theme_slides <- function(x, ...) { - fn <- function(table) { - if (isTRUE(table@output == "typst")) { - table@table_string <- paste0("#figure([\n", table@table_string, "\n])") - } - return(table) + fn <- function(table) { + if (isTRUE(table@output == "typst")) { + table@table_string <- paste0("#figure([\n", table@table_string, "\n])") } - x <- style_tt(x, finalize = fn) - return(x) + return(table) + } + x <- style_tt(x, finalize = fn) + return(x) } tt(head(iris), theme = theme_slides) @@ -97,7 +101,9 @@ tt(head(iris), theme = theme_slides) The `tabular` theme is designed to provide a more "raw" table, without a floating table environment in LaTeX, and without CSS or Javascript in HTML. ```{r tabular-theme} -tt(x) |> theme_tt("tabular") |> print("latex") +tt(x) |> + theme_tt("tabular") |> + print("latex") ``` @@ -111,7 +117,7 @@ LaTeX only. The `resize` theme allows you to adjust the size of the table in LaTeX outputs, making it fit within a specified width of the page. This is useful for large tables that need to be scaled down to fit the document layout. This table will be scaled to 90% of the available line width, ensuring it fits nicely within the document. ```{r} -tmp <- cbind(mtcars, mtcars)[1:10,] +tmp <- cbind(mtcars, mtcars)[1:10, ] tt(tmp) |> theme_tt("resize", width = .9) ``` @@ -141,7 +147,7 @@ tt(x) |> ## Rotate ```{r} -tt(head(iris), caption = "Rotated table.") |> +tt(head(iris), caption = "Rotated table.") |> theme_tt("rotate", angle = 45) ``` ::: @@ -161,8 +167,8 @@ tmp <- rbind(mtcars, mtcars)[, 1:6] cap <- "A long 80\\% width table with repeating headers." -tt(tmp, width = .8, caption = cap) |> - theme_tt("multipage", rowhead = 1) +tt(tmp, width = .8, caption = cap) |> + theme_tt("multipage", rowhead = 1) ``` ::: diff --git a/vignettes/tinytable.qmd b/vignettes/tinytable.qmd index 00aedc0f..cd0039ed 100644 --- a/vignettes/tinytable.qmd +++ b/vignettes/tinytable.qmd @@ -21,7 +21,8 @@ Install the latest version from R-Universe or CRAN: ```{r, eval = FALSE} install.packages("tinytable", - repos = c("https://vincentarelbundock.r-universe.dev", "https://cran.r-project.org")) + repos = c("https://vincentarelbundock.r-universe.dev", "https://cran.r-project.org") +) ``` This tutorial introduces the main functions of the package. It is also [available as a single PDF document.](tinytable_tutorial.pdf) @@ -74,7 +75,7 @@ lorem <- data.frame( Ipsum = " Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos." ) -tt(lorem, width = 3/4) +tt(lorem, width = 3 / 4) ``` @@ -99,10 +100,9 @@ We can also add markers in individual cells by providing coordinates: ```{r} tt(x, notes = list( - a = list(i = 0:1, j = 1, text = "Blah."), - b = "Blah blah." - ) -) + a = list(i = 0:1, j = 1, text = "Blah."), + b = "Blah blah." +)) ``` @@ -201,10 +201,13 @@ tt(mtcars[1:10, 1:5]) |> group_tt( i = list( "Hello" = 3, - "World" = 8), + "World" = 8 + ), j = list( "Foo" = 2:3, - "Bar" = 4:5)) |> + "Bar" = 4:5 + ) + ) |> print("markdown") ``` @@ -213,10 +216,13 @@ tt(mtcars[1:10, 1:5]) |> group_tt( i = list( "Hello" = 3, - "World" = 8), + "World" = 8 + ), j = list( "Foo" = 2:3, - "Bar" = 4:5)) |> + "Bar" = 4:5 + ) + ) |> save_tt("markdown") ``` @@ -238,7 +244,7 @@ Tables can be combined with the usual `rbind()` function: ```{r} a <- tt(mtcars[1:3, 1:2], caption = "Combine two tiny tables.") -b <- tt(mtcars[4:5, 8:10]) +b <- tt(mtcars[4:5, 8:10]) rbind(a, b) @@ -274,7 +280,7 @@ In a pipe-based workflow, we can use the `setNames()` function from base `R`: ```{r} mtcars[1:2, 1:2] |> - tt() |> - setNames(c("a", "b")) + tt() |> + setNames(c("a", "b")) ``` diff --git a/vignettes/tinytable_tutorial.qmd b/vignettes/tinytable_tutorial.qmd index ffbd6d2d..cf8472c7 100644 --- a/vignettes/tinytable_tutorial.qmd +++ b/vignettes/tinytable_tutorial.qmd @@ -7,6 +7,10 @@ format: number-sections: true colorlinks: true keep-tex: true + pdf-engine: xelatex + include-in-header: + text: | + \usepackage{fontspec} --- \clearpage
22.8 4 108 9393 3.85