Skip to main content

R API

Installation

# From a source package (needs Rust 1.85 or later):
install.packages("gridwell_0.1.0.tar.gz", repos = NULL, type = "source")

The source package carries the Rust crates it needs, so it builds offline. In a checkout of the repository, make it with cargo xtask r-source and then R CMD build target/r-source/gridwell.

Parsing

library(gridwell)

json <- paste(readLines("table.json", warn = FALSE), collapse = "\n")
tbl <- gw_parse_ir(json)

gw_parse_ir() gives a gw_table. Every function takes a gw_table, a gt table (converted on the way in) or IR as a JSON string; as_gw_table() turns any of them into a gw_table, and anything else is an error. A gw_table can be saved with saveRDS() and read back, and knitr’s cache keeps it too.

Showing a Table

For the getting-started table:

tbl
#> <gw_table: 2 columns, 2 rows>
#>
#> ┌────────────┬────────────┐
#> │ Name       │      Score │
#> ├────────────┼────────────┤
#> │ Alice      │         95 │
#> │ Bob        │         87 │
#> └────────────┴────────────┘
format(tbl, width = 60)   # the same as lines, the drawing at most 60 wide

A table prints as a description (its size, row groups, summary rows and title) and the table drawn as text, as gw_render_ansi() draws it, fitted to the console. The console gets colors unless it can’t show them or NO_COLOR is set; options(gridwell.color = TRUE) or FALSE decides. An invalid table prints its validation errors.

In R Markdown and Quarto, a table a chunk returns is shown in the document’s format:

Output Shown as
HTML HTML, with an id of its own so its styles apply to it alone, marked so Quarto doesn’t add Bootstrap’s table styling
PDF (LaTeX, Beamer) LaTeX, adding the packages it uses (booktabs, multirow, longtable, tabularx, xcolor, ulem) to the document, with rmarkdown installed
Typst Typst
Word, PowerPoint, RTF, others the table drawn as text; gw_save() writes a real one

.Rnw and .Rhtml files get LaTeX and HTML, unfenced.

Validation

errors <- gw_validate(tbl)
if (length(errors) > 0) {
  message("Errors: ", paste(errors, collapse = "; "))
}

A valid table can still use a feature a format can’t express. gw_warnings(tbl, format) lists those warnings for one format, or every format with format = NULL (the default); invalid IR and an unknown format are errors. A table of a newer minor IR version is warned for first, then what this gridwell leaves out of the table (IGNORED_VALUE, IGNORED_SELECTOR), and gw_parse_ir() gives a warning() for a newer minor version too.

warnings <- gw_warnings(tbl, "latex")

Text Rendering

html   <- gw_render_html(tbl)
latex  <- gw_render_latex(tbl)
typst  <- gw_render_typst(tbl)
rtf    <- gw_render_rtf(tbl)
svg    <- gw_render_svg(tbl)
ansi   <- gw_render_ansi(tbl)
pandoc <- gw_render_pandoc(tbl)
quarto <- gw_render_quarto(tbl)

# Generic by name
html <- gw_render(tbl, "html")

# Writer options: a named list, a JSON string, or named arguments
html <- gw_render(tbl, "html", list(inline_styles = TRUE))
html <- gw_render(tbl, "html", '{"inline_styles": true}')
html <- gw_render_html(tbl, inline_styles = TRUE)

# Every format, with its options and defaults, and whether it is experimental
# (a data frame)
gw_formats()

Passing options as a list needs the jsonlite package. See Writer Options for each format’s options.

Binary Rendering

docx_raw <- gw_render_docx(tbl)    # raw vector
xlsx_raw <- gw_render_xlsx(tbl)
pptx_raw <- gw_render_pptx(tbl)

# Generic by name
docx_raw <- gw_render_binary(tbl, "docx")

Saving to a File

gw_save() renders and writes in one call, for every format: the format comes from the file extension and the bytes are written unchanged (UTF-8 text, no re-encoding, no added newline), so there is no writeLines() versus writeBin() to choose. It takes any table the other functions take, and returns path invisibly.

gt::gt(gt::exibble) |> gw_save("table.rtf")

gw_save(tbl, "output.docx")
gw_save(tbl, "table.tex", booktabs = FALSE)              # writer options as arguments
gw_save(tbl, "table.json", format = "quarto")            # .json is pandoc or quarto
gw_save(tbl, "table.txt")                                # plain text, no ANSI escapes
gw_save(tbl, "table.txt", color = TRUE)                  # keep the escapes
gw_save(tbl, "table.html", standalone = TRUE)            # a full document, not a fragment

# Many tables at once
purrr::walk2(tables, paths, gw_save)
Extension Format
.html html
.tex latex
.typ typst
.rtf rtf
.svg svg
.txt ansi (plain text unless color = TRUE)
.docx, .xlsx, .pptx docx, xlsx, pptx
.json pandoc or quarto: pass format

Extensions are case-insensitive, and format overrides the extension. A missing, unknown or ambiguous extension is an error, and nothing is written if the table, format or options are invalid.

Serialization

json_out <- gw_to_json(tbl)

gt Integration

library(gt)
library(gridwell)

gt_tbl <- gt(exibble, rowname_col = "row", groupname_col = "group")
html <- gw_render_html(gt_tbl)
tbl <- as_gw_table(gt_tbl)

ir_json <- gt_to_ir(gt_tbl)  # the IR itself

gt_to_ir() and gt_to_ir_list() use gt’s own converter, gt::as_gridwell(), once the installed gt has one, and gridwell’s copy until then; pass emitter = "upstream" or emitter = "gridwell" to choose. See gt Integration.

Conformance

gw_conformance_check() checks a table’s IR against an expected table, for an emitter’s tests. Tables are compared as normalized grids, so style ids, key order and how styles are written don’t matter; the check goes by tiers (L0 valid, L1 structure, L2 content, L3 styling), each including the ones before. The expected grids for the conformance cases are in the repository’s conformance/ directory (see its README).

gt_tbl <- gt(exibble)                                   # the exibble_basic case
grid <- gw_conformance_normalize(gt_tbl, tier = "L1")  # a table's grid, as JSON
report <- gw_conformance_check(gt_tbl, grid)           # or the path of a grid file
report$passed       # TRUE
report$tiers        # c(L0 = "pass", L1 = "pass", L2 = "not checked", L3 = "not checked")
report$differences  # a data frame: tier, path, expected, actual
report

testthat::expect_true(
    gw_conformance_check(gt_tbl, "conformance/expected/gt/exibble_basic.json")$passed
)

IR that doesn’t parse or validate fails L0. In differences, expected and actual are JSON, and NA where that grid has nothing at all.

Error Handling

Every gw_render*() function validates the table first and signals an R error listing the validation errors if the IR is invalid. Use gw_validate() to get them as a character vector instead. Unknown format names, a binary format passed to gw_render() (or a text one to gw_render_binary()), and invalid options are errors too. gw_save() adds errors for an extension it can’t infer a format from and for a file it can’t write (naming the path).

tryCatch(
  gw_parse_ir("invalid json"),
  error = function(e) message("Parse error: ", conditionMessage(e))
)