Skip to contents

This article is for authors who already have weft turned on in a document (see vignette("weft", package = "weft")) and want to print numbers, counts, lists and dates the same way everywhere. After it you will know every formatter class, the keys that adjust them, how weft rounds, what it does with a missing value, and how to change the defaults for a project.

Bare values and formatted values

A bare value is inline R with no attribute block: `r x`. weft leaves it alone, and it prints exactly as knitr prints it. weft still records it, and the static lints still count it as a computed number.

A formatted value has an attribute block after the closing backtick, with nothing in between: `r x`{.num}. The block holds one or more formatter classes, and sometimes keys that adjust them. Under Quarto, `{r} x`{.num} behaves the same.

Where weft reads inline R

weft reads inline R wherever knitr evaluates it:

  • in prose, headings, lists, tables and captions;
  • inside a code span;
  • inside a fenced block that is not a chunk;
  • inside an HTML comment, closed or not;
  • inside math and raw LaTeX.

It does not read a chunk’s code, which is R and not text. Read there, inline R counts as a value, the lints see it, and an attribute block after it formats it. In the source below, x is 12.4567, and the reader sees lm(y ~ 12.46) in a code span:

# Fit `lm(y ~ `r x`{.num})` to the data.

Two consequences follow, and both are because knitr does the same. Wrapping a paragraph in an HTML comment does not switch its values or claims off, since knitr still runs them, so the gate still counts them. And a fenced block cannot show weft syntax literally: the inline R in it is evaluated. A bracketed span ([...]{.if ...}) in a code span, a fence or a comment is left as text.

Inline R in math is read and counted, and a class block after it writes TeX: see “Values in math and raw LaTeX” below.

The examples below come from one document. Its data chunk is:

mean_ntu <- 8.2333
share <- 0.1234
p_val <- 0.0462
n_dry <- 0
n_wet <- 12
survey_no <- 3
record_years <- 11
sites <- c("Upper", "Middle", "Lower", "Estuary", "Mouth")
means <- c(Upper = 4.2, Middle = 7.9, Lower = 12.6)
depth_range <- c(0.4, 1.3)
visit <- as.Date("2024-09-02")
volume <- 1234567
flagged <- character(0)

Numbers

Mean turbidity was `r mean_ntu`{.num}, or `r mean_ntu`{.num digits="2"} to
two places, or `r mean_ntu`{.num sigfig="1"} to one significant figure.

`r share`{.pct} of samples exceeded the guideline (`r p_val`{.p}).

The pond holds `r volume`{.num} L, `r volume`{.sci} L in scientific notation.
Mean turbidity was 8.2, or 8.23 to two places, or 8 to one significant figure.

12.3% of samples exceeded the guideline (p = 0.046).

The pond holds 1,234,567 L, 1.2 × 10⁶ L in scientific notation.
Class Prints
.num a number: a whole number with no decimals, any other to the default digits (one place unless set)
.pct a proportion as a percentage: 0.1234 prints “12.3%”
.sci scientific notation
.p a p-value: “p = 0.046”, “p < 0.001”, “p > 0.99”, never “p = 0.000”
.date a date, in the default format “2 September 2024”

.num, .pct and .ord put a thousands mark in numbers from 1,000 up. A year held as a plain number gets one too, so print a year as a bare value, or keep it in the dictionary as a year entry, which never gets a mark (see vignette("units", package = "weft")):

fmt_num(2024)
#> <weft_text>
#> [1] "2,024"

weft rounds half away from zero, on the number as written: 0.15 prints “0.2”. It prints the minus sign as the true minus (U+2212).

A sign on a difference: .plus

A difference reads better with its sign. .plus prints + before a number above zero:

The mean rose by `r d_mean`{.num .plus} mg/L (`r d_pct`{.pct .plus}).
The change ranged `r d_rng`{.range .plus} across sites.
The mean rose by +1.2 mg/L (+12%).
The change ranged −0.5 to +1.2 across sites.

with d_mean <- 1.2, d_pct <- 0.12 and d_rng <- c(-0.5, 1.2). A negative number keeps its minus. A number that prints as zero has no sign, as it has no minus. Under .range the ends are joined by ” to ” when either end has a sign, so no dash stands next to a sign:

fmt_num(c(1.25, 0, -1.25), plus = TRUE)
#> <weft_text>
#> [1] "+1.3" "0"    "−1.3"
fmt_range(c(1.2, 3.4), plus = TRUE)
#> <weft_text>
#> [1] "+1.2 to +3.4"
fmt_range(c(0, 1.2), plus = TRUE)
#> <weft_text>
#> [1] "0.0 to +1.2"

.plus goes with .num or .pct (alone, it implies .num), with a list class, and with .a: `r 8`{.num .plus .a} prints “a +8”. With .sci, .p, .date, .no, a wording class or .val, or on an n, if, sign, list or cite span, it is a construct error. No setting signs every number: a sign belongs to a difference, and a project-wide sign would print “+12 sites”.

p-values: digits and label

By default .p prints three decimals below 0.1 and two from 0.1 up, with “p < 0.001” and “p > 0.99” at the ends. digits fixes the number of decimals, and the ends move with it, so “p = 0.000” never prints:

fmt_p(c(0.0004, 0.046, 0.12, 0.995))
#> <weft_text>
#> [1] "p < 0.001" "p = 0.046" "p = 0.12"  "p > 0.99"
fmt_p(c(0.0004, 0.046, 0.12, 0.9996), digits = 3)
#> <weft_text>
#> [1] "p < 0.001" "p = 0.046" "p = 0.120" "p > 0.999"
fmt_p(c(0.004, 0.046, 0.995), digits = 2)
#> <weft_text>
#> [1] "p < 0.01" "p = 0.05" "p > 0.99"

With digits = 3, a value below 0.001 prints “p < 0.001”, a value that would round to 1 prints “p > 0.999”, and any other value prints with exactly three decimals, trailing zeros kept: “p = 0.120”. digits on .p is a whole number from 1 to 6. sigfig on .p is a construct error.

label sets the text before the relation. Use it for an adjusted value, or leave it empty to print the number alone:

The trend was weak (`r fit_p`{.p digits="3"}).
After correction it held (`r fit_q`{.p label="q"}).
Effects were small (`r fit_p`{.p label=""}).
The trend was weak (p = 0.046).
After correction it held (q = 0.003).
Effects were small (0.046).

The label is printed as written, so label="*p*" prints an italic p. label on anything but .p is a construct error. The settings p_digits and p_label set both for a project, and a key on the value wins over them.

Counts and wording

`r n_dry`{.no .word .cap} sites were dry and `r n_wet`{.count} were wet.
This is the `r survey_no`{.ord} survey.

`r n_wet`{.word .cap} sites were wet. The logger gave
`r record_years`{.num .a}-year record.
No sites were dry and 12 were wet. This is the 3rd survey.

Twelve sites were wet. The logger gave an 11-year record.
Class Prints
.no a zero as “no”
.word a whole number spelled out (“three”), in digits from 100 up
.count a word below ten, digits from ten up (“three”, “12”)
.ord an ordinal (“3rd”)
.a “a” or “an” before a number, by its sound (“an 11”, “an 8”)
.cap a capital first letter
.strong, .em bold or italic

.word, .count and .ord need a whole number that is not negative. A decimal or a negative number is a value error: the render fails at the end and names the line.

Lists

We sampled `r sites`{.and trunc="3"}, or `r sites`{.or sep="; "}.

Means were `r means`{.num .pairs}.

Depths ranged over `r depth_range`{.range} m. The first visit was on
`r visit`{.date}.

Flagged sites: `r flagged`{.and none="none"}.
We sampled Upper, Middle, Lower and 2 others, or Upper; Middle; Lower;
Estuary or Mouth.

Means were Upper (4.2), Middle (7.9) and Lower (12.6).

Depths ranged over 0.4–1.3 m. The first visit was on 2 September 2024.

Flagged sites: none.
Class Prints
.and, .or the items joined with “and” or “or”
.pairs a named vector as “A (1.2), B (3.4) and C (5.6)”
.range two numbers as a range (“3–5”), or “−5 to −3” when an end is negative or, with .plus, signed
.ul, .ol, .dl a bullet list, a numbered list or a definition list

A vector with no list class prints its items joined by “,”, as knitr prints a vector.

.ul, .ol and .dl make a block, so the value must be alone in its paragraph, and not inside a list item, a block quote or a table cell:

The sites were:

`r sites[1:3]`{.ul}
The sites were:

- Upper
- Middle
- Lower

Keys

Keys adjust a class. Write them inside the same attribute block, with the value in double or single quotes, or none when it is one word (digits=2).

Key Sets
digits decimal places (on .p, a whole number from 1 to 6)
sigfig significant figures (not with digits, not on .p)
label the text before a p-value’s relation, .p only
unit the unit a quantity prints in (see the units article)
sep the text between list items
last the text before the last item
trunc how many items to show before “and N others”
none the text to print for an empty vector, with a list class

digits, sigfig or unit on a value with no number class imply .num.

Combining classes

Classes act in four fixed stages, whatever order you write them in:

  1. Number: at most one of .num, .pct, .sci, .p, .date; and .plus, which is in no group.
  2. Wording: .no, then at most one of .word, .count, .ord.
  3. List: at most one of .and, .or, .pairs, .range, .ul, .ol, .dl.
  4. Text: .a, then .cap, then .strong or .em.

So {.num .pairs} formats each number and then pairs them, and {.no .word .cap} turns 0 into “no”, then capitalises it. Two classes from one “at most one” group are a construct error, which stops the render at once and which the lints report without running anything.

A class or key that weft does not own passes through to a Pandoc span around the output. weft(), described below, resolves markup in a string; its markdown form shows what weft writes:

mean_ntu <- 8.2333
format(weft("Turbidity was `r mean_ntu`{.num .strong} and `r mean_ntu`{.num .smallcaps}."), target = "markdown")
#> [1] "Turbidity was **8.2** and [8.2]{.smallcaps}."

A misspelt class, such as .nmu, is therefore not an error. The tier-2 lint name lists it (see vignette("lints", package = "weft")).

Numbers that print as zero

A number that is not zero but rounds to “0.0” under the default digits is easy to miss. weft prints it, and records a warned check: the render does not fail, and the warning is printed at the end of the knit. Outside a knit it is an R warning:

fmt_num(0.04)
#> Warning: weft: 0.04 printed as 0.0: add sigfig to show it, or digits to confirm
#> it
#> <weft_text>
#> [1] "0.0"
fmt_num(0.04, sigfig = 1)
#> <weft_text>
#> [1] "0.04"
fmt_num(0.04, digits = 1)
#> <weft_text>
#> [1] "0.0"

Give sigfig to show the number, or digits to say that the zero is what you meant. Either one silences the warning.

Missing values

NA, NaN, Inf, -Inf and a vector of length zero are missing values. Given to a formatter, a span or a phrase function, a missing value is a “no value” failure: the render fails at the end, and in draft mode the value prints as <<weft: no value, line N>>. A bare value with no attribute block prints NA as knitr does, but a bare value whose printed text is exactly NA, NaN, Inf or -Inf is a warned check: the render does not fail, last_knit()$warnings holds a row for it, and the condition log records a warning of class weft_bare_missing_warning. A vector such as c(1, NA) records nothing. Set bare_missing: false in _weft.yml to turn the check off.

A list class with none is the exception: an empty vector prints the none text, as in the “Flagged sites” example above.

Formatters in R code

Every class .x has a function fmt_x(), for chunks, plot labels and table cells:

fmt_num(8.2333, digits = 2)
#> <weft_text>
#> [1] "8.23"
fmt_pct(0.1234)
#> <weft_text>
#> [1] "12.3%"
fmt_p(0.00002)
#> <weft_text>
#> [1] "p < 0.001"
fmt_word(3)
#> <weft_text>
#> [1] "three"
fmt_count(c(3, 12))
#> <weft_text>
#> [1] "three" "12"
fmt_ord(3)
#> <weft_text>
#> [1] "3rd"
fmt_and(c("Upper", "Middle", "Lower", "Estuary"), trunc = 2)
#> <weft_text>
#> [1] "Upper, Middle and 2 others"
fmt_range(c(-5, -3))
#> <weft_text>
#> [1] "−5 to −3"
fmt_date(as.Date("2024-09-02"))
#> <weft_text>
#> [1] "2 September 2024"
fmt_cap(fmt_word(12))
#> <weft_text>
#> [1] "Twelve"
fmt_a(fmt_num(11))
#> <weft_text>
#> [1] "an 11"

A formatter returns a weft_text: a character vector that carries its printed record, the number as printed, whether decimals show, and whether it is a bound such as “< 0.01”. Pass one formatter’s result to another and the record goes with it:

fmt_pairs(fmt_num(c(Upper = 4.2, Middle = 7.9, Lower = 12.6)))
#> <weft_text>
#> [1] "Upper (4.2), Middle (7.9) and Lower (12.6)"

glue_vec() is the joining engine behind .and and .or:

glue_vec(c("Upper", "Middle", "Lower"), last = " or ")
#> <weft_text>
#> [1] "Upper, Middle or Lower"

weft() resolves weft markup in a string, for text that no chunk option reaches: a kable() caption, a plot title, text written by a chunk with results: asis.

n_sites <- 3
weft("Turbidity at `r n_sites`{.word} sites, mean `r mean_ntu`{.num} NTU.")

Turbidity at three sites, mean 8.2 NTU.

Captions and front matter

A construct works in a chunk’s caption. Write the caption as a YAML block scalar (|), because a construct in any other form of scalar is a construct error:

```{r}
#| label: fig-depth
#| fig-cap: |
#|   Depth at [a site | # sites]{n="n_sites"}, mean `r mean(d)`{.num} m.
d <- c(0.4, 0.7, 1.3)
n_sites <- length(d)
barplot(d)
```

The caption is resolved after the chunk runs, so it sees objects the chunk made. The same works in fig-alt, fig-subcap and tbl-cap under Quarto, and in fig.cap and fig.alt under R Markdown. A construct in the caption of a chunk with cache: true or eval: false is a construct error: write that caption in a figure div instead.

The front-matter fields title, subtitle, abstract and description take constructs too, when written as a block scalar. Front matter is read before any chunk runs, so a field that needs a chunk’s values goes in a second metadata block at the end of the document:

---
abstract: |
  We sampled [a site | # sites]{n="n_sites"}, to a mean depth of
  `r mean(d)`{.num} m.
---

Values in math and raw LaTeX

A formatter’s markdown is wrong inside a formula. .sci would write a markdown superscript, .pct a bare % that TeX reads as a comment, and the comma in 1,234 would be spaced as punctuation. So in math and raw LaTeX a class block writes TeX. Write the value as inline R with a class block, as in prose:

The fit gave $a = `r mean_ntu`{.num digits=2}$ and $b = `r share`{.pct}$.

$$ V = `r volume`{.sci} $$

weft puts this into the document before the renderer sees it:

The fit gave $a = 8.23$ and $b = 12.3\%$.

$$ V = 1.2 \times 10^{6} $$

and the renderer sets it as math, so the page shows a = 8.23, b = 12.3% and V = 1.2 × 10⁶.

These places count as math: $...$, $$...$$, the math environments of LaTeX (equation, align, gather, multline, cases, the matrices and the others, starred or not) and, in an .Rmd knitted with R Markdown, \(...\) and \[...\]. Under Quarto those two forms are not math, and weft does not treat them as math. Raw LaTeX is any other \begin{...} environment, a fence written ```{=latex} or ```{=tex}, and a code span followed by {=latex} or {=tex}. A {=typst} or {=html} fence is neither, and keeps the markdown of prose. A raw command such as \textbf{...} in the middle of a paragraph is not found.

What each class prints

With the values of the document above (depth_range is c(0.4, 1.3)), in math:

Written Prints, as TeX
`r mean_ntu`{.num} 8.2
`r volume`{.num} 1{,}234{,}567
`r share`{.pct} 12.3\%
`r share`{.pct .plus} +12.3\%
`r p_val`{.p} p = 0.046
`r volume`{.sci} 1.2 \times 10^{6}
`r depth_range`{.range} 0.4\ \text{to}\ 1.3

.p writes its label, so a formula holds `r p_val`{.p} alone, and not p = before it. The minus sign is always -, whatever the minus setting says. The thousands mark is {,}, which keeps the comma from taking punctuation spacing. A range always says “to”, even between two positive numbers: no dash survives every renderer, and a dash between numbers in a formula reads as a subtraction. The other marks follow your settings, in TeX: big_mark: " " prints 1\,234\,567, and p_label: "adj. p" prints \text{adj. p}. A label key on .p is TeX already and goes in as you write it: label="\tilde{p}" prints \tilde{p} = 0.046.

A value with a unit prints the unit inside \text{}: 5\,\text{mg/L}, 5\,\text{m}^{2}, 20\,\text{°C}. The characters of a unit, such as the degree and micro signs, go through unchanged. .uname prints the name, 5\ \text{milligrams per litre}.

What is refused, and why

A formula holds numbers. The classes that print words, emphasis or a list have no TeX form, and in math and raw LaTeX they are a construct error:

  • .word, .count, .ord, .no, .date, .a and .cap print words.
  • .em and .strong are markdown emphasis. Put \mathbf{} or \mathit{} round the value in the formula.
  • .and, .or, .pairs, .ul, .ol and .dl, and the keys sep, last, trunc and none, join items. Use .range for two ends.

So is a class or key that is not weft’s, because weft would put the value in a Pandoc span, and a formula has none. lints() finds these without running R, and a render stops at one. The message names the class and says why.

In raw LaTeX

In raw LaTeX the output of a construct is wrapped in \ensuremath{...}, so it is safe in running text as well as in a math mode:

```{=latex}
\begin{tabular}{ll}
Share & `r share`{.pct} \\
\end{tabular}
```

writes \ensuremath{12.3\%} into the cell. A failure marker is written inside \text{}, and in raw LaTeX inside the wrapper too.

A named value works in these places too: the Lua filter finds it inside the formula and writes the same TeX. See vignette("named-values"), “A named value in math and raw LaTeX”.

A bare value, inline R with no class block, is left as it is everywhere. In math it prints as knitr prints it. In raw LaTeX it is not wrapped, so a string in a tabular cell stays text. Writing fmt_num(x) in a bare value in math therefore writes markdown, which is the fault the class block removes: the value-format lint says so, and suggests the class block.

From code

Every fmt_*() takes target as its last argument. "markdown" is the default and the output you know. target = "tex" writes the TeX of this section, for text you build in code and put into a formula:

fmt_num(1234567, target = "tex")
#> <weft_text>
#> [1] "1{,}234{,}567"
fmt_pct(0.1234, target = "tex")
#> <weft_text>
#> [1] "12.3\\%"
fmt_range(c(0.4, 1.3), target = "tex")
#> <weft_text>
#> [1] "0.4\\ \\text{to}\\ 1.3"
fmt_num(u(5, mg/L), target = "tex")
#> <weft_text>
#> [1] "5\\,\\text{mg/L}"

A text made for TeX carries the attribute target = "tex". Passing it to a markdown formatter is an error, because it would print TeX source in a paragraph: format the number again, without target. The functions that print words, emphasis or a list refuse target = "tex", as the classes are refused in math, and any other value of target is an error too.

Project formatters in math

A project formatter writes markdown. To use it in math it must say that it can write TeX, with targets: in its registration:

formatters:
  .millions:
    function: in_millions
    stage: number
    targets: [markdown, tex]
in_millions <- function(x, target = "markdown") {
  txt <- paste(weft::fmt_num(x / 1e6, target = target), "million")
  if (target == "tex") paste0("\\text{", txt, "}") else txt
}

targets: is [markdown] unless set, and must include markdown. It lists markdown and, optionally, tex: plain, html and marquee are refused with a configuration error (E104), because under those targets a formatter is called as for markdown and weft reads its text from that. A function that lists tex is called with target = "markdown" or target = "tex" as its last argument, after any options, and must take target or .... A class that does not list tex is a construct error in math.

Changing the defaults

Project settings live in _weft.yml at the project root. A document overrides them with a weft: key in its own front matter. The settings for values are:

Setting Default Governs
digits 1 decimal places for a number that is not whole
decimal_mark "." the decimal mark
big_mark "," the thousands mark
thousands_from 1000 the smallest number that gets a thousands mark
serial_comma false a comma before the final “and” or “or” of three or more items
minus "−" the minus sign
pct_proportion true whether .pct reads 0.12 as 12%
p_digits null the decimals of .p, 1 to 6; null keeps the default rule
p_label "p" the text before a p-value’s relation; may be ""
count_threshold 10 where .count switches from words to digits
word_limit 100 where .word switches to digits
date_format "%-d %B %Y" the format of .date
governor_class .num the class that formats the number of an n or sign span
bare_missing true whether a bare value that prints a missing value is a warned check

With this _weft.yml:

digits: 2
serial_comma: true
count_threshold: 20
formatters:
  .millions:
    function: in_millions
    stage: number

and this document:

---
title: "Settings"
output: html_document
knitr:
  opts_knit:
    weft: !expr weft::weft_setup()
weft:
  date_format: "%d/%m/%Y"
---

```{r data}
in_millions <- function(x) paste(format(round(x / 1e6, 1), nsmall = 1), "million")
mean_ntu <- 8.2333
n_wet <- 12
sites <- c("Upper", "Middle", "Lower")
visit <- as.Date("2024-09-02")
volume <- 1234567
```

Mean turbidity was `r mean_ntu`{.num}. `r n_wet`{.count .cap} sites were wet:
`r sites`{.and}. The first visit was on `r visit`{.date}. The pond holds
`r volume`{.millions} litres.

the paragraph renders as:

Mean turbidity was 8.23. Twelve sites were wet: Upper, Middle, and Lower.
The first visit was on 02/09/2024. The pond holds 1.2 million litres.

The formatters: setting registers a project formatter: a class name, the function behind it (pkg::fun, or a name the document can see), and the stage it acts in (number unless given). It counts towards that stage’s “at most one” rule, and it may not reuse the name of a weft class. A formatter that is to be used in math lists targets: [markdown, tex] as well (see “Project formatters in math” above).

Options for a project formatter

A project formatter can take options: keys written on the construct that reach the function as named arguments. Declare them under options:, each with a type:

formatters:
  .millions:
    function: in_millions
    stage: number
    options:
      digits: integer
      word: string
in_millions <- function(x, digits = NULL, word = "million") {
  paste(weft::fmt_num(x / 1e6, digits = digits), word)
}

`r volume`{.millions digits=2} then prints “1.23 million” and `r volume`{.millions word="M"} prints “1.2 M”. The function gets only the options the construct writes, in the order options: lists them, so its own defaults apply to the rest. Give a forwarded option a NULL default, as digits has here, and the project’s digits setting still applies when the construct writes none. A formatter with no options: is called with the value alone, as before.

The types are number, integer, string and logical. A value is read by its type and arrives as a number, a whole number, a string exactly as written, or TRUE or FALSE (written true or false, in any case). A value outside its type is a construct error, found when the document is scanned. A list of names (options: [digits, word]) declares each as a string, except that a weft key of the formatter’s stage (digits and sigfig for a number formatter, sep, last and trunc for a collapse formatter) keeps its own type. The function must have an argument for every declared option, or ..., and no option may share the name of its first argument, which receives the value; weft says so when the formatter runs.

What happens to a key that is not declared:

  • A weft key of the formatter’s stage is an error. {.millions digits=2} with no digits declared stops the render, where digits was once dropped without a word. Declare it, or remove it.
  • Any other key passes through to the output as an attribute, as it does on a weft class. lints() points out a name that is one edit from an option, and an option of another formatter.
  • A declared option is yours: it is not passed through, and its letter case does not matter.

A later formatters: entry for the same class, in a document’s front matter, replaces options: as a whole. The names n, if, sign, list, cite, unit, none, label, why, decision, claim, level and target are weft’s and cannot be options. Options are for R documents; a named value on the Lua filter route cannot take a project formatter.