Nometabelline
MateriaSpecs
Classekept up to date

Specs · rebuilt on every push

How tabelline behaves

Every behaviour agreed so far, written down with OpenSpec: 9 specs, 121 requirements, 107 examples. Each example ran against the code while this page was built: 107 of 107 pass.

A spec in openspec/specs/ says how one part of tabelline behaves today: requirements, each with an example (Nim code and what it prints) and scenarios (WHEN this, THEN that). A change in openspec/changes/ proposes new behaviour, with its spec deltas and tasks; when it ships, it is archived and its deltas join the specs. The examples are checked by nim r tools/specexamples.nim, here and in CI. Tap a spec to open it.

Links to a part of this page, for people and agents

Add spec= or change= to this page's link to show only some of it, opened: ?spec=formatting, ?spec=table-* (a prefix), ?spec=formatting,styling, ?change=all. The same works after # (#spec=formatting). The filter runs in the browser; a tool that does not run JavaScript gets the whole page, so to read one spec, read its markdown: openspec/specs/<name>/spec.md in the repository.

Specs

formatting 38 requirements · 0 scenarios · 38 examplesHow values become text: formatting functions usable on their own, and fmt* verbs that attach them to columns and rows, applied when the table is rendered.

Formats are applied at render time

A fmt* verb SHALL resolve its columns and rows when it is called and store a format; the formats SHALL run when the table is rendered, and for each cell the last format that covers it SHALL win. Missing values SHALL render blank unless a substitution says otherwise.

✓ the output matches openspec/specs/formatting/spec.md:14
let d = tableData:
  x: [1.5, 2.25, nil]
let t = tabella(d):
  fmtNumber "x", decimals = 1
  fmtNumber "x", decimals = 3, rows = [0]
echo t
x
1.500
2.2
what it prints
┌───────┐
│     x │
╞═══════╡
│ 1.500 │
│   2.2 │
│       │
└───────┘

Number formats

fmtNumber SHALL format numbers with decimals, digit grouping (useSeps), dropTrailingZeros, scaleBy, compact suffixes (K, M, B, T), forceSign and a pattern around the value ("{x} kg"). fmtInteger, fmtPercent, fmtCurrency, fmtScientific and fmtRoman SHALL be the usual special cases. Negative numbers SHALL use the minus sign (−).

✓ the output matches openspec/specs/formatting/spec.md:39
let d = tableData:
  n: [1234567.891, -0.5, 0.0123]
let number = tabella(d):
  fmtNumber "n", decimals = 2
echo number
let compact = tabella(d):
  fmtNumber "n", compact = true
echo compact
let percent = tabella(d):
  fmtPercent "n", decimals = 1
echo percent
let currency = tabella(d):
  fmtCurrency "n", currency = "EUR"
echo currency
let scientific = tabella(d):
  fmtScientific "n", decimals = 1
echo scientific
n
1,234,567.89
−0.50
0.01
n
1.23M
−0.5
0.01
n
123,456,789.1%
−50.0%
1.2%
n
€1,234,567.89
−€0.50
€0.01
n
1.2 × 106
−5.0 × 10−1
1.2 × 10−2
what it prints
┌──────────────┐
│            n │
╞══════════════╡
│ 1,234,567.89 │
│        −0.50 │
│         0.01 │
└──────────────┘
┌───────┐
│     n │
╞═══════╡
│ 1.23M │
│  −0.5 │
│  0.01 │
└───────┘
┌────────────────┐
│              n │
╞════════════════╡
│ 123,456,789.1% │
│         −50.0% │
│           1.2% │
└────────────────┘
┌───────────────┐
│             n │
╞═══════════════╡
│ €1,234,567.89 │
│        −€0.50 │
│         €0.01 │
└───────────────┘
┌─────────────┐
│           n │
╞═════════════╡
│   1.2 × 10⁶ │
│ −5.0 × 10⁻¹ │
│  1.2 × 10⁻² │
└─────────────┘

Locales

A table SHALL take a locale (as tabella(data, locale = "it")) that sets the digit group and decimal marks of its number formats, the pattern of its percentages and currencies, and the names and order of its dates and times, from Unicode CLDR; a format's own locale, sepMark or decMark SHALL win. A tag SHALL be read in any case, with - or _; an unknown region SHALL fall back to its language, and an unknown language to English.

✓ the output matches openspec/specs/formatting/spec.md:104
let d = tableData:
  n: [1234.5, 0.25]
let p = tableData:
  share: [0.123, 0.5]
let italian = tabella(d, locale = "it"):
  fmtNumber "n", decimals = 2
echo italian
let swiss = tabella(d, locale = "de_CH"):
  fmtNumber "n", decimals = 2
echo swiss
let french = tabella(p, locale = "fr"):
  fmtPercent "share"
echo french
echo getLocale("pt-XX").tag, " ", getLocale("it").months[10], " ", getLocale("ja").daysAbbr[0]
n
1.234,50
0,25
n
1'234.50
0.25
share
12,3 %
50,0 %
what it prints
┌──────────┐
│        n │
╞══════════╡
│ 1.234,50 │
│     0,25 │
└──────────┘
┌──────────┐
│        n │
╞══════════╡
│ 1'234.50 │
│     0.25 │
└──────────┘
┌────────┐
│  share │
╞════════╡
│ 12,3 % │
│ 50,0 % │
└────────┘
pt novembre 日

Other formats

fmtDate SHALL format ISO dates in a named style or a std/times pattern; fmtTf SHALL show booleans as two texts; fmtMarkdown SHALL read cells as inline Markdown; fmt(columns, proc) SHALL take any proc from a Value to a string.

✓ the output matches openspec/specs/formatting/spec.md:148
let d = tableData:
  day: ["2026-11-07", "2015-01-15"]
  ok: [true, false]
  stars: [3, 1]
let t = tabella(d):
  fmtDate "day", dateStyle = "day_month_year"
  fmtTf "ok", trueText = "yes", falseText = "no"
  fmt "stars", proc (v: Value): string = "*".repeat(v.i)
echo t
dayokstars
7 November 2026yes***
15 January 2015no*
what it prints
┌─────────────────┬─────┬───────┐
│ day             │ ok  │ stars │
╞═════════════════╪═════╪═══════╡
│ 7 November 2026 │ yes │   *** │
│ 15 January 2015 │ no  │     * │
└─────────────────┴─────┴───────┘

Substitutions

subMissing SHALL show missing values as a text (by default an em dash), subZero SHALL show zeros as a text. Substitutions SHALL apply after the formats.

✓ the output matches openspec/specs/formatting/spec.md:173
let d = tableData:
  n: [0, nil, 3]
let t = tabella(d):
  subMissing()
  subZero zeroText = "none"
echo t
n
none
—
3
what it prints
┌──────┐
│    n │
╞══════╡
│ none │
│    — │
│    3 │
└──────┘

Value functions

The functions behind the verbs (formatNumber, formatInteger, formatCompact, formatScientific, formatEngineering, formatNumberSi, formatPercent, formatPartsper, formatCurrency, formatBytes, formatRoman, formatIndex, formatSpelledNum, formatDate, formatTime, formatDatetime, formatDuration, formatTf, formatFlag) SHALL be public, for use outside tables.

✓ the output matches openspec/specs/formatting/spec.md:199
echo formatNumber(1234567.891), " ", formatCompact(1234567.891), " ", formatScientific(5.97e24)
echo formatPercent(0.1234), " ", formatCurrency(-49.95, "EUR"), " ", formatRoman(2026)
echo formatInteger(1234.6), " ", formatEngineering(12345), " ", formatNumberSi(1500, "W"), " ", formatPartsper(0.0042)
echo formatBytes(2048, "binary"), " ", formatIndex(3), " ", formatSpelledNum(7), " ", formatDuration(3725)
echo formatTime("09:05", "h_m_p"), " ", formatDatetime("2026-11-07T09:05", "m_day_year"), " ", formatTf(true, "yes-no"), " ", formatFlag("IT")
what it prints
1,234,567.89 1.2M 5.97 × 10²⁴
12.3% −€49.95 MMXXVI
1,235 12.35 × 10³ 1.50 kW 4.20‰
2 KiB C seven 1h 2m 5s
9:05 AM Nov 7, 2026 09:05:00 yes 🇮🇹

Engineering notation and SI prefixes

fmtEngineering(columns, rows, decimals) SHALL show numbers in scientific notation with exponents in steps of three; fmtNumberSi(columns, rows, unit, decimals, inclSpace) SHALL show them with an SI prefix (from quecto to quetta) before an optional unit.

✓ the output matches openspec/specs/formatting/spec.md:220
let d = tableData:
  x: [12345.0, 0.000123, 1.5]
let engineering = tabella(d):
  fmtEngineering "x"
echo engineering
let si = tabella(d):
  fmtNumberSi "x", unit = "g"
echo si
x
12.35 × 103
123.00 × 10−6
1.50
x
12.35 kg
123.00 µg
1.50 g
what it prints
┌───────────────┐
│             x │
╞═══════════════╡
│   12.35 × 10³ │
│ 123.00 × 10⁻⁶ │
│          1.50 │
└───────────────┘
┌───────────┐
│         x │
╞═══════════╡
│  12.35 kg │
│ 123.00 µg │
│    1.50 g │
└───────────┘

Parts per

fmtPartsper(columns, rows, toUnits, decimals, scaleValues, inclSpace) SHALL show fractions as parts per thousand ("per-mille", ‰), ten thousand ("per-myriad", ‱), hundred thousand ("pcm"), million ("ppm"), billion ("ppb"), trillion ("ppt") or quadrillion ("ppq"). With inclSpace = "auto" there SHALL be a space before letters and none before ‰ and ‱.

✓ the output matches openspec/specs/formatting/spec.md:254
let d = tableData:
  co2: [0.000421, 0.000280]
let ppm = tabella(d):
  fmtPartsper "co2", toUnits = "ppm", decimals = 0
echo ppm
let perMille = tabella(d):
  fmtPartsper "co2", decimals = 3
echo perMille
co2
421 ppm
280 ppm
co2
0.421‰
0.280‰
what it prints
┌─────────┐
│     co2 │
╞═════════╡
│ 421 ppm │
│ 280 ppm │
└─────────┘
┌────────┐
│    co2 │
╞════════╡
│ 0.421‰ │
│ 0.280‰ │
└────────┘

Bytes

fmtBytes(columns, rows, standard, decimals, inclSpace) SHALL show sizes in bytes with decimal (kB, MB, GB, powers of 1000) or binary (KiB, MiB, GiB, powers of 1024) units, dropping trailing zeros; sizes below one unit SHALL show whole bytes.

✓ the output matches openspec/specs/formatting/spec.md:285
let d = tableData:
  size: [512, 1500, 1536, 3_200_000_000]
let t = tabella(d):
  fmtBytes "size"
  fmtBytes "size", rows = [2], standard = "binary"
echo t
size
512 B
1.5 kB
1.5 KiB
3.2 GB
what it prints
┌─────────┐
│    size │
╞═════════╡
│   512 B │
│  1.5 kB │
│ 1.5 KiB │
│  3.2 GB │
└─────────┘

Letters and spelled numbers

fmtIndex(columns, rows, upper, indexAlgo) SHALL show whole numbers as letters (1 is A, 26 is Z, 27 is AA, then BB with "repeat" or AB with "excel"); fmtSpelledNum(columns, rows) SHALL spell numbers from zero to one hundred in English, and leave others as digits.

✓ the output matches openspec/specs/formatting/spec.md:310
let d = tableData:
  n: [1, 3, 27, 42]
let index = tabella(d):
  fmtIndex "n", upper = false
echo index
let spelled = tabella(d):
  fmtSpelledNum "n"
echo spelled
n
a
c
aa
pp
n
one
three
twenty-seven
forty-two
what it prints
┌────┐
│  n │
╞════╡
│  a │
│  c │
│ aa │
│ pp │
└────┘
┌──────────────┐
│            n │
╞══════════════╡
│          one │
│        three │
│ twenty-seven │
│    forty-two │
└──────────────┘

Times and datetimes

fmtTime(columns, rows, timeStyle) SHALL show times ("14:35", "14:35:07", or the time part of an ISO datetime) in a named style (timeStyles: "iso", "iso-short", "h_m_s_p", "h_m_p", "h_p", ...); fmtDatetime(columns, rows, dateStyle, timeStyle, sep) SHALL show ISO datetimes as a date and a time, each in its style. Text that is not a time SHALL be left as it is.

✓ the output matches openspec/specs/formatting/spec.md:346
let d = tableData:
  launch: ["1969-07-16T13:32:00", "2026-11-07 09:05", "soon"]
let t = tabella(d):
  fmtDatetime "launch", dateStyle = "day_m_year", timeStyle = "h_m_p"
echo t
echo formatTime("14:35:07", "iso-short"), " ", formatTime("14:35", "h_p")
launch
16 Jul 1969 1:32 PM
7 Nov 2026 9:05 AM
soon
what it prints
┌─────────────────────┐
│ launch              │
╞═════════════════════╡
│ 16 Jul 1969 1:32 PM │
│ 7 Nov 2026 9:05 AM  │
│ soon                │
└─────────────────────┘
14:35 2 PM

Durations

fmtDuration(columns, rows, inputUnits, outputUnits, durationStyle, trimZeroUnits, maxOutputUnits) SHALL show numbers as lengths of time in weeks, days, hours, minutes and seconds, in the styles "narrow" (2h 5m), "wide" (2 hours 5 minutes), "colon-sep" (02:05:03) and "iso" (PT2H5M). The smallest output unit SHALL be rounded.

✓ the output matches openspec/specs/formatting/spec.md:372
let d = tableData:
  secs: [7503.0, 90061.0, 45.0]
let narrow = tabella(d):
  fmtDuration "secs"
echo narrow
let colons = tabella(d):
  fmtDuration "secs", durationStyle = "colon-sep"
echo colons
echo formatDuration(1.5, inputUnits = "days", durationStyle = "wide")
secs
2h 5m 3s
1d 1h 1m 1s
45s
secs
02:05:03
25:01:01
00:00:45
what it prints
┌─────────────┐
│        secs │
╞═════════════╡
│    2h 5m 3s │
│ 1d 1h 1m 1s │
│         45s │
└─────────────┘
┌──────────┐
│     secs │
╞══════════╡
│ 02:05:03 │
│ 25:01:01 │
│ 00:00:45 │
└──────────┘
1 day 12 hours

Booleans

fmtTf(columns, rows, tfStyle, trueText, falseText, naText, colors, html) SHALL show booleans in a named style (tfStyles: "true-false", "yes-no", "up-down", "check-mark", "circles", "squares", "diamonds", "arrows", "triangles", "triangles-lr") or as two texts of your own, with naText for missing values and colors for true and false in HTML. With html = true the texts SHALL be HTML (an SVG symbol, say), not escaped.

✓ the output matches openspec/specs/formatting/spec.md:409
let d = tableData:
  rings: [false, true, nil]
let circles = tabella(d):
  fmtTf "rings", tfStyle = "circles", naText = "?"
echo circles
let t = tabella(d):
  fmtTf "rings", trueText = "<b>yes</b>", falseText = "no", html = true, colors = ["green", "gray"]
echo "<span style=\"color: green\"><b>yes</b></span>" in t.toHtml
rings
○
●
?
what it prints
┌───────┐
│ rings │
╞═══════╡
│ ○     │
│ ●     │
│ ?     │
└───────┘
true

Links

fmtUrl(columns, rows, label, asButton, color, target, showUnderline) SHALL make links of addresses, with the address as text unless label is given or the cell is a Markdown link [label](address); fmtEmail SHALL do the same with mailto: links. In text, the label SHALL be shown.

✓ the output matches openspec/specs/formatting/spec.md:437
let d = tableData:
  site: ["https://nim-lang.org", "[nimib](https://github.com/pietroppeter/nimib)"]
let t = tabella(d):
  fmtUrl "site"
echo t
echo "<a href=\"https://github.com/pietroppeter/nimib\">nimib</a>" in t.toHtml
what it prints
┌──────────────────────┐
│ site                 │
╞══════════════════════╡
│ https://nim-lang.org │
│ nimib                │
└──────────────────────┘
true

Flags

fmtFlag(columns, rows, sep, useTitle) SHALL show country codes (ISO 3166-1, two or three letters, several separated by commas) as flag emoji, built from regional indicator letters, so nothing is loaded and every renderer shows them; with useTitle the code SHALL be the HTML title.

✓ the output matches openspec/specs/formatting/spec.md:461
let d = tableData:
  country: ["IT", "JPN", "FR,DE"]
let t = tabella(d):
  fmtFlag "country"
echo t
country
🇮🇹
🇯🇵
🇫🇷 🇩🇪
what it prints
┌─────────┐
│ country │
╞═════════╡
│ 🇮🇹      │
│ 🇯🇵      │
│ 🇫🇷 🇩🇪   │
└─────────┘

Small, large and given values

subSmallVals(columns, rows, threshold = 0.01, smallPattern = "<{x}", sign) SHALL show numbers closer to zero than the threshold (but not zero) as the pattern, with the threshold for {x}; subLargeVals(columns, rows, threshold = 1e12, largePattern = ">={x}", sign) SHALL do the same for numbers at or beyond the threshold; sign = "-" SHALL apply them to negative numbers. subValues(columns, rows, values, replacement) SHALL show the given values, or the values for which a proc fn holds, as a text.

✓ the output matches openspec/specs/formatting/spec.md:487
let d = tableData:
  x: [0.004, 2.5, 3e13, -99.0]
let t = tabella(d):
  fmtNumber "x"
  subSmallVals()
  subLargeVals()
  subValues values = [-99], replacement = "n/a"
echo t
x
<0.01
2.50
>=1T
n/a
what it prints
┌───────┐
│     x │
╞═══════╡
│ <0.01 │
│  2.50 │
│  >=1T │
│   n/a │
└───────┘

Text transforms

textTransform(fn, locations) SHALL change the shown text at locations (by default the body) with a proc: for body and stub cells the proc SHALL get the formatted text when the table is rendered, for labels and notes their text when the verb is called; the labels of summary rows (loc.summaryStub(), loc.grandSummaryStub()) SHALL change as shown text only, so a location that names a summary row by its label still finds it. textReplace(pattern, replacement, locations) SHALL replace a plain text, and textCaseMatch(cases, default, replace, locations) SHALL change texts that match a case (or, with replace = "partial", the matching parts).

✓ the output matches openspec/specs/formatting/spec.md:518
let t = tabella(planets(), rownameCol = "planet"):
  tabStubhead "planet"
  colsHide ["type", "mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "moons"]
  textTransform toUpperAscii, loc.stub()
  fmtTf "rings", tfStyle = "yes-no"
  textCaseMatch:
    yes: "rings!"
    default = ""
    locations = loc.body("rings")
  textReplace "planet", "Planet", loc.stubhead()
echo t
Planetrings
MERCURYno
VENUSno
EARTHno
MARSno
JUPITERrings!
SATURNrings!
URANUSrings!
NEPTUNErings!
what it prints
┌─────────┬────────┐
│ Planet  │ rings  │
╞═════════╪════════╡
│ MERCURY │ no     │
│ VENUS   │ no     │
│ EARTH   │ no     │
│ MARS    │ no     │
│ JUPITER │ rings! │
│ SATURN  │ rings! │
│ URANUS  │ rings! │
│ NEPTUNE │ rings! │
└─────────┴────────┘

Units

formatUnits(s, ctx) SHALL read units in gt's notation: tokens separated by spaces, ^ before a power, _ before a subscript, [_a^b] for both stacked, a token after a lone / as a power −1 ("m /s" is "m s⁻¹"), :name: for a symbol (:mu:, :ohm:, :degree:, the Greek letters), degC, degF, um, ug, uL, ohm, x10 as "×10", *...* for emphasis and %...% for a chemical formula. HTML SHALL use <sup> and <sub>; text SHALL use Unicode superscripts and subscripts, or ^x and _x when a character has none. fmtUnits(columns, rows) SHALL show cells as units, colsUnits(units, unitsPattern = "{1}, {2}") SHALL add units to column labels, and units between {{ and }} in a column label, a spanner or the stubhead SHALL be shown as units.

✓ the output matches openspec/specs/formatting/spec.md:557
let d = tableData:
  quantity: ["speed of sound", "gravity", "air density"]
  value: [343.0, 9.81, 1.204]
  units: ["m /s", "m s^-2", "kg m^-3"]
let quantities = tabella(d, rownameCol = "quantity"):
  fmtUnits "units"
  colsLabel:
    value: "at {{20 degC}}"
echo quantities
let gravity = tabella(planets(), rownameCol = "planet"):
  colsHide everything()
  colsUnhide ["density", "gravity"]
  colsUnits:
    density: "kg m^-3"
    gravity: "m s^-2"
    unitsPattern = "{1} ({2})"
echo gravity
at 20 °Cunits
speed of sound343.0m s−1
gravity9.81m s−2
air density1.204kg m−3
density (kg m−3)gravity (m s−2)
Mercury54293.7
Venus52438.9
Earth55149.8
Mars39343.7
Jupiter132623.1
Saturn6879.0
Uranus12708.7
Neptune163811.0
what it prints
┌────────────────┬──────────┬────────┐
│                │ at 20 °C │ units  │
╞════════════════╪══════════╪════════╡
│ speed of sound │    343.0 │ m s⁻¹  │
│ gravity        │     9.81 │ m s⁻²  │
│ air density    │    1.204 │ kg m⁻³ │
└────────────────┴──────────┴────────┘
┌─────────┬──────────────────┬─────────────────┐
│         │ density (kg m⁻³) │ gravity (m s⁻²) │
╞═════════╪══════════════════╪═════════════════╡
│ Mercury │             5429 │             3.7 │
│ Venus   │             5243 │             8.9 │
│ Earth   │             5514 │             9.8 │
│ Mars    │             3934 │             3.7 │
│ Jupiter │             1326 │            23.1 │
│ Saturn  │              687 │             9.0 │
│ Uranus  │             1270 │             8.7 │
│ Neptune │             1638 │            11.0 │
└─────────┴──────────────────┴─────────────────┘

Chemical formulas

formatChem(s, ctx) SHALL read formulas and reactions in gt's notation: digits after an element or a bracket as subscripts, a count before a formula (2H2O), a charge after ^ or after a count (SO4^2-, NH4+), an isotope before an element (^14C, ^{235}_{92}U), ->, <-, <->, <-->, <=> as arrows, ^ and v alone as a gas and a precipitate, * and . alone as a dot. fmtChem(columns, rows) SHALL show cells as formulas.

✓ the output matches openspec/specs/formatting/spec.md:606
let d = tableData:
  name: ["water", "copper sulfate", "sulfate", "carbon-14"]
  formula: ["H2O", "CuSO4 * 5H2O", "SO4^2-", "^14C"]
let t = tabella(d, rownameCol = "name"):
  fmtChem "formula"
echo t
echo formatChem("2H2 + O2 -> 2H2O")
formula
waterH2O
copper sulfateCuSO4⋅5 H2O
sulfateSO42−
carbon-1414C
what it prints
┌────────────────┬─────────────┐
│                │ formula     │
╞════════════════╪═════════════╡
│ water          │ H₂O         │
│ copper sulfate │ CuSO₄⋅5 H₂O │
│ sulfate        │ SO₄²⁻       │
│ carbon-14      │ ¹⁴C         │
└────────────────┴─────────────┘
2 H₂ + O₂ → 2 H₂O

Fractions

formatFraction(x, accuracy, denominator, simplify, layout, useSeps, sepMark, ctx) SHALL show a number as a mixed fraction: the whole part, then the closest fraction with a denominator up to 9 (accuracy = "low"), 99 ("med") or 999 ("high"), or with the given denominator (reduced when simplify). A fraction that rounds to a whole number SHALL show just the number. layout = "diagonal" SHALL show the fraction as a superscript, a fraction slash and a subscript. fmtFraction(columns, rows, ...) SHALL format cells so.

✓ the output matches openspec/specs/formatting/spec.md:636
let d = tableData:
  x: [0.25, 1.5, 2.333, 0.999, -0.125]
let t = tabella(d):
  colsAdd "diagonal", d["x"].values
  colsAdd "sixteenths", d["x"].values
  fmtFraction "x"
  fmtFraction "diagonal", layout = "diagonal"
  fmtFraction "sixteenths", denominator = 16
echo t
xdiagonalsixteenths
1/41⁄41/4
1 1/211⁄21 1/2
2 1/321⁄32 5/16
111
−1/8−1⁄8−1/8
what it prints
┌───────┬──────────┬────────────┐
│     x │ diagonal │ sixteenths │
╞═══════╪══════════╪════════════╡
│   1/4 │      ¹⁄₄ │        1/4 │
│ 1 1/2 │     1¹⁄₂ │      1 1/2 │
│ 2 1/3 │     2¹⁄₃ │     2 5/16 │
│     1 │        1 │          1 │
│  −1/8 │     −¹⁄₈ │       −1/8 │
└───────┴──────────┴────────────┘

Bins

formatBins(s, sep = "--", fmt) SHALL show an interval written as [a,b), (a,b], [a,b] or (a,b) as a, sep (where -- is an en dash), b; fmt, a proc of a float, SHALL format each end. Other text SHALL be shown as it is. fmtBins(columns, rows, sep, fmt) SHALL format cells so.

✓ the output matches openspec/specs/formatting/spec.md:665
let d = tableData:
  population: ["[0,1e+06)", "[1e+06,1e+07)", "[1e+07,1e+08)"]
  countries: [52, 61, 83]
let t = tabella(d):
  fmtBins "population", fmt = proc (x: float): string = formatCompact(x, 0)
echo t
populationcountries
0–1M52
1M–10M61
10M–100M83
what it prints
┌────────────┬───────────┐
│ population │ countries │
╞════════════╪═══════════╡
│ 0–1M       │        52 │
│ 1M–10M     │        61 │
│ 10M–100M   │        83 │
└────────────┴───────────┘

Passthrough and automatic formats

fmtPassthrough(columns, rows, escape = true, pattern = "{x}") SHALL show values as they are, in the pattern; with escape = false a value SHALL be HTML. fmtAuto(columns, rows, scope = ["numbers", "currency"], lgNumPref = "sci") SHALL give each numeric column a format: a currency when the column's name ends with _ or . and a currency code, else numbers with no decimals in a column of whole numbers and up to three otherwise (trailing zeros dropped), and scientific notation, with up to three decimals, for values below 0.001 or from a million (lgNumPref = "suf": a suffix, "12.3M", up to 10¹⁵).

✓ the output matches openspec/specs/formatting/spec.md:693
let d = tableData:
  item: ["a", "b", "c"]
  count: [3, 2500000, 12]
  ratio: [0.5, 0.0000123, 1.25]
  price_eur: [3.5, 10.0, 99.99]
let t = tabella(d):
  fmtAuto()
  fmtPassthrough "item", pattern = "item {x}"
echo t
itemcountratioprice_eur
item a30.5€3.50
item b2.5 × 1061.23 × 10−5€10.00
item c121.25€99.99
what it prints
┌────────┬───────────┬─────────────┬───────────┐
│ item   │     count │       ratio │ price_eur │
╞════════╪═══════════╪═════════════╪═══════════╡
│ item a │         3 │         0.5 │     €3.50 │
│ item b │ 2.5 × 10⁶ │ 1.23 × 10⁻⁵ │    €10.00 │
│ item c │        12 │        1.25 │    €99.99 │
└────────┴───────────┴─────────────┴───────────┘

Country names

countryName(code) SHALL give the English name of a country or territory by its two- or three-letter code (ISO 3166-1, any case), from Unicode CLDR, and the code itself when it is not one. formatCountry(codes, sep = ", ") SHALL do so for several codes separated by commas or spaces, and fmtCountry(columns, rows, pattern, sep) SHALL format cells so.

✓ the output matches openspec/specs/formatting/spec.md:721
let d = tableData:
  codes: ["IT", "jpn", "FR, DE", "XX"]
let t = tabella(d):
  colsAdd "names", d["codes"].values
  fmtCountry "names"
echo t
codesnames
ITItaly
jpnJapan
FR, DEFrance, Germany
XXXX
what it prints
┌────────┬─────────────────┐
│ codes  │ names           │
╞════════╪═════════════════╡
│ IT     │ Italy           │
│ jpn    │ Japan           │
│ FR, DE │ France, Germany │
│ XX     │ XX              │
└────────┴─────────────────┘

Currencies

fmtCurrency(columns, rows, currency, decimals, placement, accounting, useSubunits, locale) SHALL take any ISO 4217 code that CLDR knows, with its symbol and its number of decimals; the symbol SHALL go where the locale's pattern puts it, or on the placement given ("left", "right"), with a no-break space when the symbol ends or starts with a letter. accounting SHALL write negative amounts in parentheses; useSubunits = false SHALL drop the decimals.

✓ the output matches openspec/specs/formatting/spec.md:748
let d = tableData:
  amount: [1234.5, -3.25]
let accounting = tabella(d):
  fmtCurrency "amount", currency = "CAD", accounting = true
echo accounting
let euro = tabella(d, locale = "it"):
  fmtCurrency "amount", currency = "EUR"
echo euro
let dinar = tabella(d):
  fmtCurrency "amount", currency = "BHD", placement = "right"
echo dinar
echo formatCurrency(1500, "JPY"), " ", currencyInfo("CHF")
amount
CA$1,234.50
(CA$3.25)
amount
1.234,50 €
−3,25 €
amount
1,234.500 BHD
−3.250 BHD
what it prints
┌─────────────┐
│      amount │
╞═════════════╡
│ CA$1,234.50 │
│   (CA$3.25) │
└─────────────┘
┌────────────┐
│     amount │
╞════════════╡
│ 1.234,50 € │
│    −3,25 € │
└────────────┘
┌───────────────┐
│        amount │
╞═══════════════╡
│ 1,234.500 BHD │
│    −3.250 BHD │
└───────────────┘
¥1,500 (name: "Swiss Franc", symbol: "CHF", digits: 2)

Dates and times in every locale

fmtDate, fmtTime and fmtDatetime SHALL take a locale (or the table's) for the names of months, days, quarters, eras, AM and PM. A date style SHALL be one of gt's fixed styles (dateStyles: "iso", "wday_month_day_year", "day_month_year", "year_week", ...) or one of gt's flexible styles (dateSkeletons: "yMMMd", "yMMMEd", "yQQQQ", ...), written in the locale's order; a time style SHALL be one of timeStyles or of timeSkeletons ("Hm", "hm", "hms", ...).

✓ the output matches openspec/specs/formatting/spec.md:792
let d = tableData:
  day: ["2026-11-07", "2015-01-15"]
let german = tabella(d, locale = "de"):
  fmtDate "day", dateStyle = "yMMMEd"
echo german
for loc in ["en", "it", "ja", "ru"]:
  echo loc, ": ", formatDate("2026-11-07", "wday_day_month_year", loc), " · ",
    formatDate("2026-11-07", "yMMMd", loc), " · ", formatTime("14:35", "hm", loc)
day
Sa., 7. Nov. 2026
Do., 15. Jan. 2015
what it prints
┌────────────────────┐
│ day                │
╞════════════════════╡
│ Sa., 7. Nov. 2026  │
│ Do., 15. Jan. 2015 │
└────────────────────┘
en: Saturday 7 November 2026 · Nov 7, 2026 · 2:35 PM
it: sabato 7 novembre 2026 · 7 nov 2026 · 2:35 PM
ja: 土曜日 7 11月 2026 · 2026年11月7日 · 午後2:35
ru: суббота 7 ноября 2026 · 7 нояб. 2026 г. · 2:35 PM

Icons

fmtIcon(columns, rows, height = "1em", sep, ...) SHALL show each cell's names of Font Awesome Free icons (several separated by commas) as inline SVG, height high and as wide as their shape, in the text's colour unless fillColor or, by name, fillColors is given. A name SHALL be a short name (the regular style when there are two), a full name ("fas fa-star") or an older name ("user-large"); an unknown name SHALL raise ValueError when the verb is called. In text output the names SHALL stay.

✓ the output matches openspec/specs/formatting/spec.md:824
let d = tableData:
  planet: ["Earth", "Jupiter"]
  kind: ["mountain", "cloud, star"]
let t = tabella(d):
  fmtIcon "kind", fillColors = {"star": "gold"}
echo t
echo t.toHtml.count("class=\"tb_icon\""), " ", icon("star").style, " ", icon("fas fa-star").style, " ", hasIcon("user-large")
planetkind
Earth
Jupiter
what it prints
┌─────────┬─────────────┐
│ planet  │ kind        │
╞═════════╪═════════════╡
│ Earth   │ mountain    │
│ Jupiter │ cloud, star │
└─────────┴─────────────┘
3 regular solid true

Images

fmtImage(columns, rows, height, width, sep, path, filePattern = "{x}", encode = true, alt) SHALL show each cell's file names (several separated by commas) as images, found in path and written with filePattern. With encode, a local file SHALL be read when the verb is called and inlined as a data URL, its type from its extension; an address (https://...) SHALL be left as it is. Without height or width an image SHALL be 2em high. In text output the names SHALL stay.

✓ the output matches openspec/specs/formatting/spec.md:852
let dir = getTempDir()
writeFile(dir / "dot.svg", "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 2'><circle cx='1' cy='1' r='1'/></svg>")
let d = tableData:
  pic: ["dot"]
let t = tabella(d):
  fmtImage "pic", path = dir, filePattern = "{x}.svg"
echo t
echo t.toHtml.contains("<img src=\"data:image/svg+xml;base64,")
pic
dot
what it prints
┌─────┐
│ pic │
╞═════╡
│ dot │
└─────┘
true

Nanoplots

fmtNanoplot(columns, rows, plotType = "line", plotHeight = "2em", missingVals = "gap", autoscale, referenceLine, referenceArea, expandY, options, alt) SHALL draw a plot in each cell, as inline SVG: a line plot ("line"), a bar plot ("bar") or a box plot ("boxplot") of the cell's values (numbers separated by spaces, commas or semicolons, NA for a missing one), or, in a column of numbers, a horizontal bar or line from a zero line shared by the rows. The values SHALL show when the pointer is over the plot, without JavaScript. A missing value SHALL break the line ("gap"), be marked ("marker"), count as 0 ("zero") or be left out ("remove"). referenceLine SHALL be a number or a statistic of the values ("mean", "median", "min", "max", "q1", "q3", "first", "last"), and referenceArea two of them. With autoscale every plot of the column SHALL share its y axis. nanoplotOptions(...) SHALL hold the look, with Great Tables' defaults. In text output a nanoplot SHALL be a sparkline, a bar of blocks beside a zero line, or the five numbers of a box plot.

✓ the output matches openspec/specs/formatting/spec.md:886
let d = tableData:
  city: ["Oslo", "Rome"]
  trend: ["1 4 2 8 5", "3, NA, 6, 2"]
  change: [4.2, -1.5]
let t = tabella(d, rownameCol = "city"):
  fmtNanoplot "trend", referenceLine = "mean"
  fmtNanoplot "change", plotType = "bar"
echo t
echo t.toHtml.count("class=\"tb_nanoplot\""), " ", nanoplotLabel(1234), " ", nanoplotLabel(0.25)
trendchange
Oslo481142854.20
Rome3.67623NA62−1.50
what it prints
┌──────┬───────────┬───────────────────┐
│      │ trend     │            change │
╞══════╪═══════════╪═══════════════════╡
│ Oslo │ ▁▄▂█▅ 1–8 │    │███████ 4.20  │
│ Rome │ ▃ █▁ 2–6  │ ███│        −1.50 │
└──────┴───────────┴───────────────────┘
4 1.23K 0.25

Formats on lists and records

A format SHALL apply to a list item by item and to a record field by field, keeping the separators of $ ("1.2, 1.6", "lo: 0.8, hi: 1.6"); an item that the format does not take SHALL be shown as it is. fmtIcon, fmtImage and fmtFlag SHALL take a list of names as they take names separated by commas.

✓ the output matches openspec/specs/formatting/spec.md:914
let d = tableData:
  sensor: ["north", "south"]
  readings: [@[1.24, 1.56], @[12.71]]
  span: [(lo: 0.82, hi: 1.56), (lo: 9.13, hi: 12.71)]
let t = tabella(d, rownameCol = "sensor"):
  fmtNumber ["readings", "span"], decimals = 1
echo t
readingsspan
north1.2, 1.6lo: 0.8, hi: 1.6
south12.7lo: 9.1, hi: 12.7
what it prints
┌───────┬──────────┬───────────────────┐
│       │ readings │ span              │
╞═══════╪══════════╪═══════════════════╡
│ north │ 1.2, 1.6 │ lo: 0.8, hi: 1.6  │
│ south │ 12.7     │ lo: 9.1, hi: 12.7 │
└───────┴──────────┴───────────────────┘

Nanoplots of lists and of x and y

fmtNanoplot SHALL read a list of numbers as the values of a cell, and a record as its field y, with its field x (as many) the places of the values on the x axis of a line plot, in the order of x; a bar or box plot SHALL leave x out. With autoscale the rows SHALL share the x axis too, and expandX SHALL widen it; on a shared x axis every row's plot SHALL have the same width, so the axes line up. A record without y, or with an x of another length, SHALL raise ValueError when the verb is called. In text output the sparkline SHALL follow the order of x.

✓ the output matches openspec/specs/formatting/spec.md:942
let d = tableData:
  runner: ["Anna", "Bruno"]
  laps: [(x: @[0.0, 1, 2, 5], y: @[62.0, 60, 61, 58]), (x: @[0.0, 3, 4, 5], y: @[65.0, 63, 66, 59])]
  kit: [@["person-running", "stopwatch"], @["person-biking"]]
let t = tabella(d, rownameCol = "runner"):
  fmtNanoplot "laps", autoscale = true
  fmtIcon "kit"
echo t
echo nanoplotXValues(d["laps", 1]), " ", t.toHtml.count("class=\"tb_nanoplot\"")
lapskit
Anna665862606158
Bruno665865636659
what it prints
┌───────┬────────────┬───────────────────────────┐
│       │ laps       │ kit                       │
╞═══════╪════════════╪═══════════════════════════╡
│ Anna  │ ▅▃▄▁ 58–62 │ person-running, stopwatch │
│ Bruno │ ▇▅█▂ 59–66 │ person-biking             │
└───────┴────────────┴───────────────────────────┘
@[0.0, 3.0, 4.0, 5.0] 2

Vertical reference lines

fmtNanoplot SHALL take referenceX, a list of places on the x axis (numbers, or ISO dates such as "2020-03-11"), and in a line plot of records of x and y SHALL draw a dashed vertical line at each place inside the axis, its text shown on hover. A place outside the axis SHALL draw nothing; a place that is neither a number nor a date SHALL raise ValueError when the verb is called. Text output SHALL be unchanged.

✓ the output matches openspec/specs/formatting/spec.md:971
let d = tableData:
  airport: ["north", "south"]
  flights: [(x: @["2018-07-01", "2019-07-01", "2020-07-01", "2021-07-01"], y: @[6.8, 7.3, 1.8, 2.7]),
            (x: @["2019-07-01", "2020-07-01", "2021-07-01"], y: @[3.4, 1.0, 1.9])]
let t = tabella(d, rownameCol = "airport"):
  fmtNanoplot "flights", autoscale = true, referenceX = @["2020-03-11"]
echo t
echo t.toHtml.count("2020-03-11"), " lines"
flights
north2020-03-117.301.006.807.301.802.70
south2020-03-117.301.003.401.001.90
what it prints
┌───────┬────────────────┐
│       │ flights        │
╞═══════╪════════════════╡
│ north │ ▇█▂▃ 1.80–7.30 │
│ south │ ▄▁▂ 1.00–3.40  │
└───────┴────────────────┘
2 lines

Images anywhere

localImage(file, height = "2em", alt = "") SHALL give an <img> as Text (HTML), the file read when called and inlined as a data URL, and webImage(url, height = "2em", alt = "") the same with the address left as it is, as gt's local_image() and web_image(); they go in a title, a label, a note, or a cell through fmtMarkdown or html. alt SHALL be by default the file's name (the last part of the address), and text output SHALL show it.

✓ the output matches openspec/specs/formatting/spec.md:999
let t = tabella(planets()):
  colsHide ["density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "moons", "rings", "diameter", "type"]
  rowsHide [1, 2, 3, 4, 5, 6, 7]
  tabHeader webImage("https://example.org/sun.png", alt = "☉"), "The first planet"
echo t
echo t.toHtml.count("<img src=\"https://example.org/sun.png\"")
☉
The first planet
planetmass
Mercury0.33
what it prints
        ☉
 The first planet
┌─────────┬──────┐
│ planet  │ mass │
╞═════════╪══════╡
│ Mercury │ 0.33 │
└─────────┴──────┘
1

Named font stacks

systemFonts(name = "system-ui") SHALL give one of Great Tables' fifteen font stacks (fontStackNames: "system-ui", "transitional", "old-style", "humanist", "geometric-humanist", "classical-humanist", "neo-grotesque", "monospace-slab-serif", "monospace-code", "industrial", "rounded-sans", "slab-serif", "antique", "didone", "handwritten") as CSS text, for optTableFont; another name SHALL raise ValueError. defaultFonts() SHALL give gt's default stack.

✓ the output matches openspec/specs/formatting/spec.md:1027
echo systemFonts("old-style")
echo fontStackNames.len
let t = tabella(planets()):
  optTableFont systemFonts("humanist")
echo t.options.tableFontNames.startsWith("'Seravek'")
what it prints
'Iowan Old Style', 'Palatino Linotype', 'URW Palladio L', 'P052', serif
15
true

Nanoplot options for each point

The options of nanoplotOptions for points and bars (dataPointRadius, dataPointStrokeColor, dataPointStrokeWidth, dataPointFillColor, dataBarStrokeColor, dataBarStrokeWidth, dataBarFillColor) SHALL take a list as well as one value: the n-th point or bar takes the n-th value, and the list repeats. The x of a record SHALL also take ISO dates and times ("2026-11-11", "2026-11-11 10:30"), placed by time.

✓ the output matches openspec/specs/formatting/spec.md:1048
let d = tableData:
  week: ["one", "two"]
  steps: [toValue(@[4, 8, 6]), toValue((x: @["2026-11-02", "2026-11-03", "2026-11-09"], y: @[5, 7, 9]))]
let t = tabella(d, rownameCol = "week"):
  fmtNanoplot "steps", options = nanoplotOptions(dataPointFillColor = @["#D64545", "#2E7D32"])
echo t
let x = nanoplotXValues(d["steps", 1])
echo t.toHtml.count("fill=\"#2E7D32\""), " green points; the last is ", (x[2] - x[0]) / 86400, " days after the first"
steps
one84486
two95579
what it prints
┌─────┬─────────┐
│     │ steps   │
╞═════╪═════════╡
│ one │ ▁█▅ 4–8 │
│ two │ ▁▅█ 5–9 │
└─────┴─────────┘
2 green points; the last is 7.0 days after the first

Shape nanoplots

fmtNanoplot(columns, plotType = "shape", ...) SHALL draw each cell's record of x and y as one outline: the points joined in their order and closed, filled, at the same scale across and up, in a square as high as the plot (not from gt or Great Tables). With autoscale every shape of the column SHALL have the scale of the largest one; a missing value SHALL start a new ring. The fill and the line SHALL be dataBarFillColor and dataBarStrokeColor. A cell that is not a record of x and y SHALL raise ValueError. In text a shape SHALL be "◆ shape of N points".

✓ the output matches openspec/specs/formatting/spec.md:1077
let d = tableData:
  field: ["square", "strip"]
  outline: [toValue((x: @[0, 2, 2, 0], y: @[0, 0, 2, 2])), toValue((x: @[0, 4, 4, 0], y: @[0, 0, 1, 1]))]
let t = tabella(d, rownameCol = "field"):
  fmtNanoplot "outline", plotType = "shape", autoscale = true
echo t
echo t.toHtml.count("class=\"tb_shape\""), " shapes; the square is ", shapeSide(@[0.0, 0, 2, 2], @[0.0, 2, 2, 0]), " wide"
outline
square
strip
what it prints
┌────────┬─────────────────────┐
│        │ outline             │
╞════════╪═════════════════════╡
│ square │ ◆ shape of 4 points │
│ strip  │ ◆ shape of 4 points │
└────────┴─────────────────────┘
2 shapes; the square is 2.0 wide

Significant figures, accounting and the exponent

fmtNumber(nSigfig = n) SHALL show n significant figures instead of decimals, also with compact = true, as gt's n_sigfig. accounting = true in fmtNumber, fmtInteger, fmtPercent and fmtCurrency SHALL write a negative value in parentheses, without its minus. fmtScientific(expStyle = "e") (or "E") SHALL write the exponent as 1.23e4, as gt's exp_style. The format functions (formatNumber, formatCompact, formatInteger, formatPercent, formatScientific, formatCurrency) SHALL take the arguments of their verbs, pattern and locale among them.

✓ the output matches openspec/specs/formatting/spec.md:1106
echo formatNumber(904512.0, nSigfig = 3), " ", formatCompact(2_051_000.0, nSigfig = 3)
echo formatNumber(-24334.23, accounting = true), " ", formatPercent(-0.0523, accounting = true)
echo formatScientific(12345.0, expStyle = "e"), " ", formatScientific(12345.0, locale = "de")
echo formatNumber(1.64, pattern = "[{x}]"), " ", formatNumber(236742.37, locale = "es")
what it prints
905,000 2.05M
(24,334.23) (5.2%)
1.23e4 1,23 × 10⁴
[1.64] 236.742,37

A datetime by a strftime format

fmtDatetime(formatStr = ...) and formatDatetime(formatStr = ...) SHALL write a date and time by a strftime format (%b %d %Y (%a) - %I:%M %p), in the table's language, as gt's format and Great Tables' format_str.

✓ the output matches openspec/specs/formatting/spec.md:1125
echo formatDatetime("2023-05-01 18:20:00", formatStr = "%b %d %Y (%a) - %I:%M %p")
echo formatDatetime("2023-05-01 18:20:00", formatStr = "%d %B %Y", locale = "it")
what it prints
May 01 2023 (Mon) - 06:20 PM
01 maggio 2023

Round flags, and the country's name

fmtFlag SHALL show the country's name when a flag is hovered (its title), and with round = true SHALL draw Great Tables' round flags (the circle-flags set, shipped with tabelline, MIT) at height. circleFlag(code) SHALL give one as SVG, and "" for a code it does not know. subMissing(missingText = md"**STABLE**") SHALL take Markdown.

✓ the output matches openspec/specs/formatting/spec.md:1141
let d = tableData:
  c: ["IT", "FRA"]
echo tabella(d).fmtFlag("c").toHtml.contains("title=\"France\"")
echo tabella(d).fmtFlag("c", round = true).toHtml.count("<svg"), " ", circleFlag("XX") == ""
what it prints
true
2 true

source: openspec/specs/formatting/spec.md

nim-sugar 6 requirements · 0 scenarios · 6 examplesWhere tabelline uses Nim to read better than gt and Great Tables: a recipe macro, converters, row predicates and namespaces, with macros only where plain procs cannot do the job.

Chains and recipes

Verbs SHALL chain (tabella(d).tabHeader("x").fmtNumber("y")), each moving the spec along (sink). tabella(data, ...): body SHALL apply the verbs of body, one per line, to the new table: a call verb(args) stands for t = verb(t, args), inside for, if, when and block too, and other statements are left as they are. The two forms SHALL make the same table.

✓ the output matches openspec/specs/nim-sugar/spec.md:15
let t = tabella(tavolaPitagorica(4), rownameCol = "×"):
  tabHeader "Squares"
  for i in 1 .. 4:
    tabFootnote "a square", loc.body(cols = $i, rows = [i - 1])
echo t
Squares
1234
111234
224168
3369112
44812161
1 a square
what it prints
           Squares
┌───┬─────┬─────┬─────┬──────┐
│   │   1 │   2 │   3 │    4 │
╞═══╪═════╪═════╪═════╪══════╡
│ 1 │ 1^1 │   2 │   3 │    4 │
│ 2 │   2 │ 4^1 │   6 │    8 │
│ 3 │   3 │   6 │ 9^1 │   12 │
│ 4 │   4 │   8 │  12 │ 16^1 │
└───┴─────┴─────┴─────┴──────┘
1 a square

Selectors that read like Nim

Columns SHALL be selected by a name, an array or seq of names, or a rule (everything(), numeric(), textual(), startsWith, endsWith, containing); rows by an index, an array, a slice or where(cond), where it is the row and it.col its value.

ran (no expected output) openspec/specs/nim-sugar/spec.md:41
let d = planets()
echo startsWith("d").resolve(d), " ", where(it.moons > 20).resolve(d), " ", toRowSel(1..2).resolve(d)

Blocks for lists of pairs

Inside tabella(data): body, a verb whose first argument is a list of pairs (colsLabel, colsWidth, colsUnits, textCaseMatch, summaryRows, grandSummaryRows, summaryColumns) SHALL also take an indented block, where a line label: value is a pair; in any verb a line name = value SHALL be that named argument; in a summary verb a line fmtX(args) SHALL be fmt, a proc of a float calling formatX(x, args); tabOptions: SHALL take lines name = value. A block SHALL make the same call as the pair form.

✓ the output matches openspec/specs/nim-sugar/spec.md:54
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings", "moons"]
  colsLabel:
    mass: "mass, {{10^24 kg}}"
    diameter: "diameter, {{km}}"
  grandSummaryRows:
    mean: agg.mean
    "largest one": agg.max
    fmtNumber(decimals = 0)
  tabOptions:
    rowStriping = true
echo t
echo t.options.rowStriping
mass, 1024 kgdiameter, km
Mercury0.334879
Venus4.8712104
Earth5.9712756
Mars0.6426792
Jupiter1898.0142984
Saturn568.0120536
Uranus86.851118
Neptune102.049528
mean33350,087
largest one1,898142,984
what it prints
┌─────────────┬───────────────┬──────────────┐
│             │ mass, 10²⁴ kg │ diameter, km │
╞═════════════╪═══════════════╪══════════════╡
│ Mercury     │          0.33 │         4879 │
│ Venus       │          4.87 │        12104 │
│ Earth       │          5.97 │        12756 │
│ Mars        │         0.642 │         6792 │
│ Jupiter     │        1898.0 │       142984 │
│ Saturn      │         568.0 │       120536 │
│ Uranus      │          86.8 │        51118 │
│ Neptune     │         102.0 │        49528 │
╞═════════════╪═══════════════╪══════════════╡
│ mean        │           333 │       50,087 │
│ largest one │         1,898 │      142,984 │
└─────────────┴───────────────┴──────────────┘
true

Values by name with a dot

v.x SHALL be the field x of a record (v["x"]) and, in a row predicate or a proc of a row, it.mass SHALL be the column mass of that row (it["mass"]). A name that Value or Row already has (kind, len, items, fields, data, index, ...) SHALL be that, not the field or column, and a Nim keyword cannot follow a dot: both SHALL still be read with brackets. A name the record or table does not have SHALL raise KeyError when the code runs.

✓ the output matches openspec/specs/nim-sugar/spec.md:96
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings", "diameter"]
  rowsHide where(it.moons < 10)
echo t
massmoons
Jupiter1898.095
Saturn568.0146
Uranus86.828
Neptune102.016
what it prints
┌─────────┬────────┬───────┐
│         │   mass │ moons │
╞═════════╪════════╪═══════╡
│ Jupiter │ 1898.0 │    95 │
│ Saturn  │  568.0 │   146 │
│ Uranus  │   86.8 │    28 │
│ Neptune │  102.0 │    16 │
└─────────┴────────┴───────┘

Columns by place, and rules combined

positions(0, 2) and positions(2 .. 4) SHALL select columns by their place in the data, from 0 as rows are, a negative place counting from the end; a place past the end SHALL raise KeyError. startsWith, endsWith and containing SHALL take several parts, any of them, in brackets (startsWith(["ma", "mo"]): with two texts, startsWith is strutils.startsWith). a + b SHALL select the columns of either, in the order of the data, and a - b those of a that are not in b.

✓ the output matches openspec/specs/nim-sugar/spec.md:122
let d = planets()
echo positions(0, -1).resolve(d).join(", ")
echo startsWith(["ma", "mo"]).resolve(d).join(", ")
echo (positions(2 .. 4) + "moons").resolve(d).join(", ")
echo (numeric() - startsWith(["d", "o"])).resolve(d).join(", ")
what it prints
planet, rings
mass, moons
mass, diameter, density, moons
mass, gravity, mean_temp, moons

Columns by kind and by a test, rows from the end

ofKind(vkBool, ...) SHALL select the columns whose values are of these kinds (a missing value counts as any), as Great Tables' cs.by_dtype() and gt's where(is.logical). named(cond) SHALL select the columns whose name it passes cond, and matches(proc) those whose name passes a proc, as gt's matches() does with a regular expression. a & b SHALL select the columns of both. A negative row index SHALL count from the end (-1 is the last row), and so SHALL Nim's ^1. A block of colsLabel SHALL take plain labels and html/md ones together.

✓ the output matches openspec/specs/nim-sugar/spec.md:145
let d = planets()
echo ofKind(vkBool).resolve(d).join(", ")
echo named(it.len == 4).resolve(d).join(", ")
echo (numeric() & startsWith("d")).resolve(d).join(", ")
echo toRowSel(-1).resolve(d), " ", toRowSel(^2).resolve(d)
let t = tabella(planets()):
  colsLabel:
    planet: "Planet"
    moons: md"*Moons*"
echo t.toHtml.contains("<em>Moons</em>"), " ", t.toHtml.contains(">Planet<")
what it prints
rings
type, mass
diameter, density, day_length, distance
@[7] @[6]
true true

source: openspec/specs/nim-sugar/spec.md

nimib-integration 2 requirements · 5 scenarios · 0 examplestabelline in nimib notebooks.

A table block

import tabelline/nimib SHALL add nbTable t, a block that keeps the HTML and the Markdown of the table, so the table renders with nimib's HTML backend (nbInit) and Markdown backend (nbInitMd). nbTable SHALL also take the data and a body, nbTable data: body, and add tabella(data): body in one step, with any other argument of tabella (rownameCol, ...); nbTable data without a body SHALL add a table of the data as it is, and nbTable t: body a table t changed by the body. The core of tabelline SHALL NOT depend on nimib.

Scenario: A README from a notebook
  • WHEN a notebook made with nbInitMd calls nbTable t
  • THEN the Markdown file holds t.toMarkdown
Scenario: md in a notebook
  • WHEN a notebook does import nimib and imports tabelline, and calls md("...")
  • THEN the call is tabelline's md: nimib 0.5 has no md of its own, so nothing is excluded from the import
Scenario: A table in one step
  • WHEN a notebook calls nbTable planets(), rownameCol = "planet": with tabHeader "Planets" in the body
  • THEN the page shows the planets with their names as the stub and the heading "Planets", and no table needs a name

One stylesheet per page

nbTable SHALL write tabellaCss once per page, with the first table of the page; the next tables SHALL not repeat it. nb.tableHtml(t) SHALL give the HTML of t with the same rule, for a block that puts a table inside its own HTML. A new page (nbInit) SHALL start without it.

Scenario: A page of many tables
  • WHEN a page calls nbTable for 100 tables, with any options
  • THEN the page holds tabellaCss once, in the first table's block
Scenario: A table in another block
  • WHEN a custom block renders nb.tableHtml(t) after an nbTable
  • THEN its HTML has no tabellaCss, and the table looks as it does alone

source: openspec/specs/nimib-integration/spec.md

rendering 7 requirements · 6 scenarios · 7 examplesHow a table spec becomes output: one build step (formats, substitutions, display order, footnote marks, styles) shared by an HTML, a text and a Markdown renderer.

HTML with scoped CSS

toHtml SHALL render a <div class="tabella"> with an id, holding a <style> with tabellaCss and a <table class="tb_table">: the heading and column labels in <thead>, groups, stub and body in <tbody>, footnotes then source notes in one <tfoot>. Without an explicit id, the id SHALL come from a hash of the table, so the same table always renders the same HTML. toHtml(makePage = true) SHALL return a standalone page holding the table, titled after it, and save(path) SHALL write that page to a file.

✓ the output matches openspec/specs/rendering/spec.md:17
let t = tabella(planets(), id = "planets"):
  tabHeader "Planets"
let h = t.toHtml
echo h.startsWith("<div id=\"planets\" class=\"tabella\""), " ", tabellaCss in h, " ", h == t.toHtml
let page = t.toHtml(makePage = true)
echo page.startsWith("<!doctype html>"), " ", "<title>Planets</title>" in page, " ", h in page
what it prints
true true true
true true true
Scenario: A whole page
  • WHEN toHtml(makePage = true) is called, or save("x.html")
  • THEN the result is a whole HTML page with the table's fragment in its body
Scenario: Two tables on a page
  • WHEN a page holds two tables with different options
  • THEN each table looks as its own options say

Text

toText (and $, so echo t) SHALL draw the table with box characters: title and subtitle centred above, spanners and column labels, group labels as rows, the formatted cells aligned as in HTML, and the footnotes and source notes below.

✓ the output matches openspec/specs/rendering/spec.md:44
let t = tabella(tavolaPitagorica(3), rownameCol = "×"):
  tabHeader "Tabellina"
  tabFootnote "by heart", loc.title()
echo t
Tabellina1
123
1123
2246
3369
1 by heart
what it prints
   Tabellina^1
┌───┬───┬───┬───┐
│   │ 1 │ 2 │ 3 │
╞═══╪═══╪═══╪═══╡
│ 1 │ 1 │ 2 │ 3 │
│ 2 │ 2 │ 4 │ 6 │
│ 3 │ 3 │ 6 │ 9 │
└───┴───┴───┴───┘
1 by heart

Markdown

toMarkdown SHALL write a GitHub pipe table, with the title in bold above, group labels as bold rows, and the notes below.

✓ the output matches openspec/specs/rendering/spec.md:67
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "mass", "diameter", "density", "gravity", "day_length", "distance",
            "orbital_period", "mean_temp", "rings"]
  tabHeader "Moons"
echo t.toMarkdown
what it prints
**Moons**

|  | moons |
|:--|--:|
| Mercury | 0 |
| Venus | 0 |
| Earth | 1 |
| Mars | 2 |
| Jupiter | 95 |
| Saturn | 146 |
| Uranus | 28 |
| Neptune | 16 |

The built table as data

extractCells(t, columns, rows, ctx) SHALL give the shown text of the body cells of columns and rows, in the order the table shows them; extractBody(t, ctx) SHALL give the body as a TableData of texts (a group column when there are row groups, a rowname column when there is a stub, then every visible column); extractSummary(t, ctx) SHALL give the summary rows as a TableData of texts (group, "" for a grand summary row, label, and the visible columns). ctx = rcHtml SHALL give HTML.

✓ the output matches openspec/specs/rendering/spec.md:98
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings", "moons"]
  fmtNumber "mass", decimals = 1
  summaryRows fns = {"total": agg.sum}
echo extractCells(t, "mass", rows = [0, 1]).join(" | ")
echo tabella(extractSummary(t))
grouplabelmass
Terrestrialtotal11.8
Gas gianttotal2,466.0
Ice gianttotal188.8
what it prints
0.3 | 4.9
┌─────────────┬───────┬─────────┐
│ group       │ label │ mass    │
╞═════════════╪═══════╪═════════╡
│ Terrestrial │ total │ 11.8    │
│ Gas giant   │ total │ 2,466.0 │
│ Ice giant   │ total │ 188.8   │
└─────────────┴───────┴─────────┘

One stylesheet for every table

tabellaCss SHALL be the rules of every table, the same for all of them, with each value read from a CSS variable named --tb- and the option in kebab-case, falling back to the option's default. A table SHALL carry, in the style of its <div>, a variable for each option it sets to a value other than the default (or than optCssTheme()'s, for a table that takes it), and none for the others.

✓ the output matches openspec/specs/rendering/spec.md:125
echo tabella(planets()).toHtml(withStyle = false).splitLines[0].contains("style=")
echo tabella(planets(), id = "p").tabOptions(tableFontSize = "14px").toHtml(withStyle = false).splitLines[0]
echo "var(--tb-table-font-size, 16px)" in tabellaCss
what it prints
false
<div id="p" class="tabella" style="--tb-table-font-size: 14px">
true
Scenario: A table that takes the page's theme
  • WHEN a table calls optCssTheme() with its default arguments
  • THEN its <div> has the class tb_css_theme, whose rule in tabellaCss sets the theme's variables, and carries only the options it changes from the theme
Scenario: Options a page sets for all its tables
  • WHEN a page's CSS sets .tabella { --tb-table-font-size: 14px }
  • THEN every table on it without its own tableFontSize has 14px text
Scenario: A table's own rules
  • WHEN optCss adds rules to a table
  • THEN they are in a <style> inside that table's <div>, scoped to its id, as before

A table without the stylesheet

toHtml(t, withStyle = false) SHALL render the same fragment without tabellaCss, so a page can write the stylesheet once, or link it as a file, for many tables.

✓ the output matches openspec/specs/rendering/spec.md:153
let t = tabella(planets())
echo tabellaCss in t.toHtml(withStyle = false), " ", t.toHtml(withStyle = false).len < t.toHtml.len
what it prints
false true
Scenario: Many tables, one stylesheet
  • WHEN a page writes tabellaCss once and then toHtml(x, withStyle = false) for many tables
  • THEN every table looks as it does with toHtml(x)

Numbers on one line, and a stub in view

A formatted number in a data cell (aligned right) SHALL not break inside its cell, so a minus or a power of ten stays with its digits on a phone. With tabOptions(stubSticky = true) the stub and the stub head SHALL stay in view while a wide table scrolls sideways in its container (not in gt or Great Tables).

✓ the output matches openspec/specs/rendering/spec.md:172
let t = tabella(planets(), rownameCol = "planet"):
  tabOptions(stubSticky = true)
echo "class=\"tb_table tb_sticky_stub\"" in t.toHtml, " ", "td.tb_right { white-space: nowrap; }" in tabellaCss
what it prints
true true

source: openspec/specs/rendering/spec.md

review-mode 6 requirements · 7 scenarios · 2 examplesThe review mode of a page: a reader comments on the page where it is, and exports the comments in one text for a coding agent. It lives in docs/review.nim, a module that can move to nimib.

Turning the review mode on

import review SHALL add nbReview, a block that turns the review mode on for the page, with every argument optional: page (the key the comments are kept under, the source by default), title (the page's title by default), source (the notebook's path from the root of its repository by default) and script (a link to a shared copy of the script; inlined by default). The page SHALL open in reading mode, with nothing of the review mode but a version line and a ✎ Review button.

A notebook turns it on with import review and nbReview() after nbInit, and nbReview() finds its settings with reviewSettings: for the notebook docs/notes.nim of a repository, titled Notes, they are

✓ the output matches openspec/specs/review-mode/spec.md:21
echo reviewSettings("/home/me/notes/docs/notes.nim", root = "/home/me/notes", title = "Notes")
what it prints
page: docs/notes.nim
source: docs/notes.nim
title: Notes
Scenario: A plain nimib page
  • WHEN a nimib notebook calls nbReview()
  • THEN its page has the review mode, with plain colours when the page has no tokens

The version comes from git

The version of a page SHALL be the number of commits that touched its source, with the last one's short hash and date. Outside git it SHALL be the first 7 characters of a hash of the source, with no date. A page built from a source with uncommitted changes SHALL show the number followed by +.

✓ the output matches openspec/specs/review-mode/spec.md:41
echo reviewVersion(commits = @["a1b2c3d|2026-11-10", "9f8e7d6|2026-11-09"], dirty = false)
what it prints
version: 2, commit: a1b2c3d, updated: 10 Nov 2026
Scenario: A new commit
  • WHEN a commit changes a page's source and the site is built again
  • THEN the page's version goes up by one, and its comments start empty

The version line

A page with the review mode SHALL show Version N · updated D under its lede, or under its title when it has none, with ✎ Review beside it. nbVersion() SHALL put the line where it is called instead.

Scenario: A page with no version line of its own
  • WHEN a page calls nbReview() and not nbVersion()
  • THEN the line and the button are under its lede

Reviewing

In the review mode a reader SHALL be able to select words and comment on them, or write a note on the whole page; go through the comments in the order of the page with ‹ and ›; delete one; paste screenshots in a note. The comment that is open SHALL be in a comment box at the top, saved as it is typed; an empty one SHALL be dropped. The comments SHALL be kept in the browser, one key per page and version.

Scenario: Coming back tomorrow
  • WHEN a reader comments, closes the browser, and opens the page again
  • THEN the comments are there, marked on the text, and the page opens in the mode it was left in

The export

Export SHALL give one text: a title, a ```yaml block (format: nimib-review/5, title, page, source, version, commit, exported, comments), then one section per comment in the order of the page (## n. In “Heading” (#id), ## n. At the top, ## n. On the whole page) with the quote, the words around it and the note. A comment written on another version than the exported one SHALL say From version N (commit c). under its heading, and one whose words the page no longer has SHALL say (Not found on the page any more.). Each screenshot SHALL be named in its note and have its own Copy image. Copy SHALL copy the text only. The export SHALL also have History and Close review.

Scenario: An agent knows what changed
  • WHEN an export of version 12 (commit a1b2c3d) is pasted after the page reached version 14
  • THEN the agent can see what changed since the review with git diff a1b2c3d -- <source>

History

History SHALL list the versions of the page that have comments in this browser, this one first, then the others newest first, each with its number of comments and Clear (which asks with a second tap). An older version SHALL also have Bring here, which moves to this version its comments on the whole page and those whose words this version still has, and keeps the others on their version, and Export, which exports its comments. Export everything SHALL export the comments of every version of the page.

Scenario: Comments on an old build
  • WHEN the page is at version 14 and the browser keeps comments on version 12
  • THEN History lists version 12 with its comments, and Clear deletes them
Scenario: Bringing comments to the new version
  • WHEN version 12 has three comments, and version 14 still has the words of two of them
  • THEN Bring here moves those two to version 14 and keeps the third on version 12, and Export everything exports all three, the third marked as not found

source: openspec/specs/review-mode/spec.md

styling 13 requirements · 3 scenarios · 13 examplesHow a table looks: styles on locations, colours by value, and table-wide options with presets.

Styles at locations

tabStyle(style, locations) SHALL add CSS to the cells at each location. Styles SHALL be built with style.fill(color), style.text(...), style.borders(...) and style.css(...) and joined with &. Locations SHALL be loc.header() (title and subtitle), loc.title(), loc.subtitle(), loc.columnHeader() (stub head, spanners and column labels), loc.stubhead(), loc.columnLabels(cols), loc.spanners(labels) (also loc.spannerLabels), loc.stub(rows), loc.rowGroups(groups), loc.body(cols, rows), loc.footer() (footnotes and source notes), loc.footnotes(), loc.sourceNotes(), and for summary rows loc.summary(groups, columns, rows), loc.summaryStub(groups, rows), loc.grandSummary(columns, rows) and loc.grandSummaryStub(rows) (rows by their labels), as in Great Tables; loc.body SHALL target the data cells only, not the stub (that is loc.stub). A later style SHALL win over an earlier one for the same property, but a style at one part SHALL win over a style at a whole part that holds it (header, column header, footer), as in Great Tables. A footnote at a whole part SHALL be marked on its first element.

✓ the output matches openspec/specs/styling/spec.md:23
let t = tabella(tavolaPitagorica(3), rownameCol = "×"):
  tabStyle style.fill("#FFF3B0") & style.text(weight = "bold"), loc.body(cols = "2", rows = [1])
  tabStyle style.text(color = "#1F4E99"), loc.columnHeader()
echo "background-color: #FFF3B0; font-weight: bold" in t.toHtml
echo t.toHtml.count("color: #1F4E99")
what it prints
true
4

Colour by value

dataColor(columns, rows, palette, domain, reverse, naColor, autoColorText, apply) SHALL colour cells along a palette, each column on its own: a number column from the low to the high end of domain (by default the range of that column's selected cells), any other column by category, missing values with naColor. A domain given from high to low SHALL run the palette the other way. With autoColorText the text SHALL be dark or light, whichever contrasts more with the fill. palette(name) SHALL give named palettes (including pastelli, quaderno, blues, rdbu, viridis) or split a comma-separated list of colours.

✓ the output matches openspec/specs/styling/spec.md:45
let d = tableData:
  small: [1, 2]
  large: [100, 200]
  word: ["a", "b"]
let t = tabella(d):
  dataColor everything(), palette = @["#FFFFFF", "#000000"]
echo t.toHtml.count("background-color: #000000; color: #FFFFFF")
let r = tabella(d):
  dataColor "small", palette = @["#FFFFFF", "#000000"], domain = (2.0, 1.0)
echo "background-color: #000000; color: #FFFFFF" in r.toHtml
what it prints
3
true

Options and presets

TabOptions SHALL hold the table-wide looks with defaults, and tabOptions(name = value, ...) SHALL set any of them by name, checked when compiling. optRowStriping, optAlignTableHeader, optAllCaps, optTableFont, optStylize(style, color) and optCssTheme() SHALL be presets. optStylize(style, color, addRowStriping) SHALL draw gt's and Great Tables' six styles (1 to

  1. in their six colours (blue, cyan, pink, green, red, gray), with the same values for the lines, fills and stripes, and the light outline of styles 2, 4 and 5; any other style or colour

SHALL raise ValueError. optAllCaps(on, locations) SHALL put the column labels, the stub and the row group labels in small capitals, or only the locations named ("column_labels", "stub", "row_group"). optCssTheme() SHALL take every colour, and the font, from CSS variables of the page: --ink (text, the rules above and below and under the column labels), --paper (behind the table), --line (rules between rows), --shade (row groups and stripes), --primary (the rule under the heading) and --font. Without them, --ink SHALL fall back to #1C1C1C and --paper to #FFFFFF; --line and --shade SHALL be the ink mixed into the paper (14% and 4%), and --primary the ink. Each argument of optCssTheme(ink, paper, line, shade, primary, font) SHALL name the variable to read when it starts with --, and SHALL be the CSS value itself otherwise. cssTheme(...) SHALL make a CssTheme with the same arguments, which optCssTheme(theme) takes. On a background of the heading, the column labels, the stub, the row groups or the summary rows that light text reads better on, the text SHALL be white.

✓ the output matches openspec/specs/styling/spec.md:85
let t = tabella(planets()):
  tabOptions:
    rowStriping = true
    headingAlign = "left"
echo t.options.rowStriping, " ", t.options.headingAlign, " ", t.options.tableFontSize
let s = tabella(planets(), rownameCol = "planet"):
  optStylize 1, "red"
echo s.options.stubBackgroundColor, " ", "--tb-stub-color: #FFFFFF" in s.toHtml
let caps = tabella(planets()):
  optAllCaps locations = ["stub"]
echo caps.options.stubTextTransform, " ", caps.options.columnLabelsTextTransform
let themed = tabella(planets()):
  optCssTheme()
let o = themed.options
echo o.tableFontColor
echo o.tableBodyHlinesColor
let mine = tabella(planets()):
  optCssTheme ink = "--foreground", primary = "#D64545"
echo mine.options.tableFontColor, " ", mine.options.headingBorderBottomColor
what it prints
true left 16px
#E4220C true
uppercase inherit
var(--ink, #1C1C1C)
var(--line, color-mix(in oklab, var(--ink, #1C1C1C) 14%, var(--paper, #FFFFFF)))
var(--foreground, #1C1C1C) #D64545
Scenario: A preset on a table
  • WHEN a preset such as optStylize(2, "red") is applied
  • THEN the table sets the options it changes as variables on its <div>, and white text on the dark column labels

Any CSS

style.css(declarations) SHALL make a style from any CSS declarations ("letter-spacing: 0.1em; font-variant: small-caps"), joinable with the other styles.

✓ the output matches openspec/specs/styling/spec.md:124
let t = tabella(tavolaPitagorica(2)):
  tabStyle style.css("font-variant: small-caps; letter-spacing: 1px"), loc.columnLabels()
echo "font-variant: small-caps; letter-spacing: 1px" in t.toHtml
what it prints
true

Padding, outline and lines

optVerticalPadding(scale) and optHorizontalPadding(scale) SHALL scale the padding of the heading, the column labels and the rows; optTableOutline(style, width, color) SHALL draw a line all around the table; optTableLines(extent) SHALL add vertical lines ("all"), take every line away ("none") or bring back the defaults ("default"). New options SHALL hold what they set (dataRowPaddingHorizontal, tableBorderLeftStyle, tableBodyVlinesColor, ...).

✓ the output matches openspec/specs/styling/spec.md:141
let t = tabella(tavolaPitagorica(2)):
  optVerticalPadding 0.5
  optTableOutline color = "#333333"
echo t.options.dataRowPadding, " ", t.options.tableBorderLeftStyle, " ", t.options.tableBorderLeftColor
let noLines = tabella(tavolaPitagorica(2)):
  optTableLines "none"
echo noLines.options.tableBodyHlinesColor
what it prints
4px solid #333333
transparent

Footnote marks, look and order

optFootnoteMarks(marks) SHALL set the marks: "numbers", "letters", "LETTERS", "standard" (*, †, ‡, §), "extended" (with ‖, ¶) or a list of your own, repeated (**) when they run out. optFootnoteSpec(specRef, specFtr) SHALL set how marks look in the table and in the footer (^ raised, i italic, b bold, ( or [ around). optFootnoteOrder(order) SHALL put marked notes first ("marks_first", the default), last ("marks_last"), or keep the order notes were added in ("preserve_order", which numbers the marks in that order too).

✓ the output matches openspec/specs/styling/spec.md:164
let t = tabella(tavolaPitagorica(2), rownameCol = "×"):
  tabFootnote "A note with no mark."
  tabFootnote "Two twos.", loc.body(cols = "2", rows = [1])
  tabFootnote "The first row.", loc.stub(rows = [0])
  optFootnoteMarks "standard"
  optFootnoteSpec "^", "("
  optFootnoteOrder "marks_last"
echo t
12
1*12
224†
A note with no mark.
(*) The first row.
(†) Two twos.
what it prints
┌─────┬───┬─────┐
│     │ 1 │   2 │
╞═════╪═══╪═════╡
│ 1^* │ 1 │   2 │
│ 2   │ 2 │ 4^† │
└─────┴───┴─────┘
A note with no mark.
(*) The first row.
(†) Two twos.
Scenario: More notes than marks
  • WHEN a table has five notes and the standard marks
  • THEN the fifth is marked **

Extra CSS

optCss(css, add = true) SHALL add CSS for the table, every rule scoped to it (rules that start with # are left as they are); add = false SHALL replace what was given before.

✓ the output matches openspec/specs/styling/spec.md:195
let t = tabella(tavolaPitagorica(2), id = "tp"):
  optCss ".tb_title { color: red; }"
echo "#tp .tb_title { color: red; }" in t.toHtml
what it prints
true

Styles from the data

A style value MAY be fromColumn(column, naValue): each body or stub cell SHALL take it from column of its own row (a missing value is naValue, and "" leaves the property out). tabStyle(proc (r: Row): CellStyle, locations) SHALL style each body or stub cell with the style its row gives. tabStyleBody(style, columns, rows, values, pattern, fn, targets) SHALL style the body cells whose value is one of values, contains pattern or makes fn true, or their whole row (targets = "row") or column ("column").

✓ the output matches openspec/specs/styling/spec.md:213
let d = tableData:
  name: ["Mercury", "Earth", "Mars"]
  colour: ["#b1adad", "#4f7cac", nil]
let t = tabella(d):
  tabStyle style.fill(fromColumn("colour", naValue = "#eee")), loc.body("name")
  tabStyleBody style.text(weight = "bold"), values = ["Earth"], targets = "row"
let html = t.toHtml(withStyle = false)
echo html.count("background-color: #4f7cac"), " ", html.count("background-color: #eee"), " ", html.count("font-weight: bold")
what it prints
1 1 2

More options

TabOptions SHALL also hold gt's options for the container (containerWidth, containerHeight, containerOverflowY, containerPaddingX, containerPaddingY), the table (tableLayout, tableFontWeight, tableFontStyle), and the style, width and colour of the rules of the heading, the column labels (top, bottom, sides, between labels), the row groups (top, bottom, sides, with their size, padding and text transform), the body (lines between rows and columns, top and bottom), the stub (with its size and text transform), the footnotes and the source notes (with their background and padding). Their defaults SHALL draw the table as before.

✓ the output matches openspec/specs/styling/spec.md:237
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp"]
  tabOptions:
    rowGroupBorderTopStyle = "dashed"
    stubBorderWidth = "1px"
    tableBodyHlinesStyle = "dotted"
echo styleVars(t.options).split("; ").join("\n")
what it prints
--tb-row-group-border-top-style: dashed
--tb-table-body-hlines-style: dotted
--tb-stub-border-width: 1px
Scenario: Defaults draw the table as before
  • WHEN a table leaves an option at its default
  • THEN the table sets no variable for it, and the stylesheet's fallback draws it as before

The other options for an HTML table

tabOptions SHALL take the options of gt's tab_options() that change an HTML table and that 0.1 did not have, in camelCase: tableAlign ("center", "left", "right"), tableNoDataMessage (shown in the body when no row is shown), tableAdditionalCss (added as optCss adds), tableFontColorLight (text on dark cells: dataColor, dark headings), columnLabelsHidden, columnLabelsUnitsPattern (for the units of colsUnits that give no pattern), rowGroupDefaultLabel (a heading for the rows outside any group), rowGroupAsColumn, stubIndentLength (one level of tabStubIndent), stubSeparate (the rule after the stub), the six stubRowGroup* (font size and weight, text transform, border style, width and colour of the groups as a column), footnotesMultiline and footnotesSep, sourceNotesMultiline and sourceNotesSep (all notes on one line, with a separator), rowStripingIncludeStub (stripes in the stub too, off by default as in gt) and rowStripingIncludeTableBody. The text and Markdown output SHALL follow the ones that are not about looks (hidden labels, the units pattern, the default group label, groups as a column, the notes on one line, the no-data message).

✓ the output matches openspec/specs/styling/spec.md:272
let d = tableData:
  name: ["Io", "Europa", "Titan"]
  planet: ["Jupiter", "Jupiter", ""]
  radius: [1821.6, 1560.8, 2574.7]
let t = tabella(d, rownameCol = "name", groupnameCol = "planet"):
  colsUnits:
    radius: "km"
  tabFootnote "Galilean moons.", loc.rowGroups()
  tabSourceNote "NASA"
  tabSourceNote "JPL"
  tabOptions:
    columnLabelsUnitsPattern = "{1} ({2})"
    rowGroupDefaultLabel = "Other moons"
    sourceNotesMultiline = false
    sourceNotesSep = " · "
echo t
let empty = tabella(d):
  rowsHide [0, 1, 2]
  tabOptions(tableNoDataMessage = "No moons")
echo empty
radius (km)
Other moons
Titan2574.7
Jupiter1
Io1821.6
Europa1560.8
1 Galilean moons.
NASA · JPL
nameplanetradius
No moons
what it prints
┌────────┬─────────────┐
│        │ radius (km) │
╞════════╪═════════════╡
│ Other moons          │
├┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┄┄┄┄┄┤
│ Titan  │      2574.7 │
├────────┼─────────────┤
│ Jupiter^1            │
├┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┄┄┄┄┄┤
│ Io     │      1821.6 │
│ Europa │      1560.8 │
└────────┴─────────────┘
1 Galilean moons.
NASA · JPL
┌──────┬────────┬────────┐
│ name │ planet │ radius │
╞══════╪════════╪════════╡
│ No moons               │
└──────┴────────┴────────┘

Colour names

A colour SHALL be #rgb, #rrggbb, one of the 148 colour names of CSS (CSS Color Module Level 4) or one of R's (sienna4), in any case, wherever tabelline computes with a colour: parseColor, the palettes of dataColor, interpolate and idealTextColor. Anything else SHALL raise ValueError there. The text of a heading or of the column labels SHALL be white on a dark background set by tabOptions, given as a hex value or as a name; a background tabelline cannot read (a var(--x)) SHALL keep the text colour of the table.

✓ the output matches openspec/specs/styling/spec.md:325
echo parseColor("darkgreen").toHex, " ", parseColor("RebeccaPurple").toHex
let t = tabella(tavolaPitagorica(2)):
  dataColor everything(), palette = @["lightblue", "darkgreen"]
echo "background-color: #006400; color: #FFFFFF" in t.toHtml
what it prints
#006400 #663399
true

The arguments of gt's styles

style.text SHALL take vAlign (vertical-align) and indent (text-indent), and style.fill(color, alpha) an opacity from 0 to 1, as gt's cell_text(v_align, indent) and cell_fill(alpha). A colour SHALL also be one of R's colour names that CSS does not have (sienna4, grey50: 518 more, as gt and Great Tables take them), written as its hex value in the HTML; palette("great-tables") SHALL be Great Tables' default palette for dataColor.

✓ the output matches openspec/specs/styling/spec.md:344
echo style.text(vAlign = "top", indent = "2em").css
echo style.fill("red", alpha = 0.5).css, " ", style.fill("sienna4").css
echo rColor("grey50"), " ", palette("great-tables").len
what it prints
@[("vertical-align", "top"), ("text-indent", "2em")]
@[("background-color", "rgba(255, 0, 0, 0.5)")] @[("background-color", "#8B4726")]
#7F7F7F 8

Locations by label, by the rows of a group, and by cell

loc.stub(rows, labels) SHALL take the rows whose stub reads one of labels, with the rows given, as Great Tables' loc.stub(["apricot", 2]). loc.rowGroups(rows = ...) SHALL take the groups of these rows (by index or by where). loc.body(cols, rows, mask) SHALL take only the cells that pass mask, a proc of the cell's value, or of its value and its column, as Great Tables' loc.body(mask = ...). A fill on a spanner SHALL fill its whole cell. dataColor SHALL leave the stub's columns alone, as Great Tables does.

✓ the output matches openspec/specs/styling/spec.md:364
let t = tabella(planets(), rownameCol = "planet"):
  tabStyle style.fill("#FFF3B0"), loc.stub(labels = ["Venus"])
  tabStyle style.fill("#DDEEFF"), loc.body(cols = "moons", mask = proc (v: Value): bool = v > 20)
  tabStyle style.fill("#EEDDFF"),
    loc.body(cols = ["mass", "moons"], mask = proc (v: Value, col: Column): bool = v == agg.max.fn(col.values))
let h = t.toHtml
echo h.count("#FFF3B0"), " ", h.count("#DDEEFF"), " ", h.count("#EEDDFF")
what it prints
1 3 2

source: openspec/specs/styling/spec.md

table-data 7 requirements · 6 scenarios · 6 examplesThe data a table shows: named columns of values, read once from Nim values, columns or CSV, and never changed by the table.

Values

A cell SHALL hold a Value: missing (vkNull), a bool, an int, a float or a string. toValue SHALL convert Nim values, with nil, none(T) and a float NaN as missing. A Value SHALL compare with plain Nim numbers and strings, so row predicates read naturally.

✓ the output matches openspec/specs/table-data/spec.md:14
echo toValue(3) == 3.0, " ", toValue(2.5) > 2, " ", toValue(none(int)).isNull
what it prints
true true true
Scenario: A missing number
  • WHEN a column holds 1, nil and 3
  • THEN it is an int column whose second value is missing

Data from Nim values

toTableData (and tabella directly) SHALL take a sequence of objects or named tuples, one column per field in field order. tableData: SHALL take one name: [values] line per column, converting each value on its own; a name MAY have dots (size.mass: [...], read whole, as tabSpannerDelim wants) or be quoted (`mass kg`, "mass (kg)"). The values MAY be any list (such as a collect). A for or if in the body SHALL add the columns of its own lines, and a name MAY be computed when the line runs: $j: [...], or any expression in parentheses. parseCsv and readCsv SHALL read a CSV text with a header, inferring ints, floats, bools and missing values (empty, NA), and a column mixing ints and floats SHALL be a float column. With comment = "#" (or any prefix) they SHALL skip the lines that start with it after any spaces; by default no line is a comment.

✓ the output matches openspec/specs/table-data/spec.md:37
type Pupil = object
  name: string
  stars: int
echo tabella(@[Pupil(name: "Ada", stars: 3), Pupil(name: "Bruno", stars: 1)])
let d = tableData:
  subject: ["maths", "art"]
  mark: [9, nil]
echo tabella(d)
let tavola = tableData:
  `×`: collect(for i in 1 .. 3: i)
  for j in 1 .. 3:
    $j: collect(for i in 1 .. 3: i * j)
echo tabella(tavola, rownameCol = "×")
echo tabella(parseCsv("# from a notebook\na,b\n1,2.5\n2,3\n", comment = "#"))
namestars
Ada3
Bruno1
subjectmark
maths9
art
123
1123
2246
3369
ab
12.5
23.0
what it prints
┌───────┬───────┐
│ name  │ stars │
╞═══════╪═══════╡
│ Ada   │     3 │
│ Bruno │     1 │
└───────┴───────┘
┌─────────┬──────┐
│ subject │ mark │
╞═════════╪══════╡
│ maths   │    9 │
│ art     │      │
└─────────┴──────┘
┌───┬───┬───┬───┐
│   │ 1 │ 2 │ 3 │
╞═══╪═══╪═══╪═══╡
│ 1 │ 1 │ 2 │ 3 │
│ 2 │ 2 │ 4 │ 6 │
│ 3 │ 3 │ 6 │ 9 │
└───┴───┴───┴───┘
┌───┬─────┐
│ a │   b │
╞═══╪═════╡
│ 1 │ 2.5 │
│ 2 │ 3.0 │
└───┴─────┘
Scenario: Comment lines
  • WHEN a CSV text has lines starting with # and comment = "#" is given
  • THEN those lines are skipped, and a # inside a value is kept
Scenario: No rows
  • WHEN an empty sequence of objects is given
  • THEN the data has the fields as columns and no rows
Scenario: A misspelt column
  • WHEN a verb names a column that is not in the data
  • THEN it raises a KeyError that lists the columns there are

Datasets

tabelline/datasets SHALL provide planets() (NASA's planetary fact sheet), exibble() (gt's example table), tavolaPitagorica(n) (the n×n times table), isole() (the islands of the Mediterranean, the twin of gt's islands) and citta() (the largest cities of the European Union, the twin of gt's towny), built into the module.

✓ the output matches openspec/specs/table-data/spec.md:100
echo tabella(tavolaPitagorica(4), rownameCol = "×")
echo isole().nrows, " islands, ", citta().nrows, " cities; the largest: ", isole()["island", 0], ", ", citta()["city", 0]
1234
11234
22468
336912
4481216
what it prints
┌───┬───┬───┬────┬────┐
│   │ 1 │ 2 │  3 │  4 │
╞═══╪═══╪═══╪════╪════╡
│ 1 │ 1 │ 2 │  3 │  4 │
│ 2 │ 2 │ 4 │  6 │  8 │
│ 3 │ 3 │ 6 │  9 │ 12 │
│ 4 │ 4 │ 8 │ 12 │ 16 │
└───┴───┴───┴────┴────┘
194 islands, 95 cities; the largest: Sicily, Berlin

Lists and records in a cell

A cell SHALL hold a list (vkList, items in order) or a record (vkRecord, named fields in order). toValue SHALL make a list from a seq or an array and a record from an object or a named tuple, so tableData: and toTableData take them as they are; CSV SHALL never make them. v[i] SHALL be an item and v["x"] a field (KeyError when there is none), len their count. $ SHALL write a list as "1, 4, 2" and a record as "x: 1, y: 2"; == SHALL compare item by item; < SHALL order lists item by item; a list or record SHALL NOT be a number, and toFloat SHALL raise ValueError on it. A column of them SHALL have the kind of its cells and not be numeric.

✓ the output matches openspec/specs/table-data/spec.md:127
let moons = tableData:
  planet: ["Earth", "Mars", "Jupiter"]
  moons: [@["Moon"], @["Phobos", "Deimos"], @["Io", "Europa", "Ganymede", "Callisto"]]
  biggest: [(name: "Moon", km: 3474.8), (name: "Phobos", km: 22.5), (name: "Ganymede", km: 5268.2)]
echo tabella(moons, rownameCol = "planet")
let r = moons["biggest", 2]
echo r.name, " ", r.km, " ", moons["moons", 1][0], " ", moons["moons", 2].len
moonsbiggest
EarthMoonname: Moon, km: 3474.8
MarsPhobos, Deimosname: Phobos, km: 22.5
JupiterIo, Europa, Ganymede, Callistoname: Ganymede, km: 5268.2
what it prints
┌─────────┬────────────────────────────────┬────────────────────────────┐
│         │ moons                          │ biggest                    │
╞═════════╪════════════════════════════════╪════════════════════════════╡
│ Earth   │ Moon                           │ name: Moon, km: 3474.8     │
│ Mars    │ Phobos, Deimos                 │ name: Phobos, km: 22.5     │
│ Jupiter │ Io, Europa, Ganymede, Callisto │ name: Ganymede, km: 5268.2 │
└─────────┴────────────────────────────────┴────────────────────────────┘
Ganymede 5268.2 Phobos 4

gt's datasets

tabelline/datasets SHALL have four of gt's datasets as Great Tables ships them (MIT): gtcars() (47 cars, 15 columns), countrypops() (the population of every country, 1960 to 2022), illness() (a patient's tests, days 3 to 9) and metro() (the stations of the Paris Metro).

✓ the output matches openspec/specs/table-data/spec.md:154
let cars = gtcars()
echo cars.nrows, " ", cars.ncols, " ", cars["model", 0]
echo "countrypops: ", countrypops().names.join(", "), "; illness: ", illness().nrows, " rows, metro: ", metro().nrows, " rows"
what it prints
47 15 GT
countrypops: country_name, country_code_2, country_code_3, year, population; illness: 39 rows, metro: 314 rows

Data frames of nanuq

import tabelline/nanuq SHALL make toTableData(df) and tabella(df) (so tabella(df): body) work for a nanuq DataFrame, copying every column in order: integers as ints, floats as floats, booleans as bools, strings as text, any other type as the text Polars writes for it, and a null as a missing value. It SHALL be the only module of tabelline that imports nanuq; nanuq SHALL be part of the docs feature, so the core keeps needing only Nim's standard library.

Scenario: A summary made in nanuq
  • WHEN a DataFrame is grouped and summarised in nanuq and given to tabella(df): body
  • THEN the table has the frame's columns in order, numbers aligned right, and the body's verbs apply as for any data
Scenario: Nulls
  • WHEN a column of the DataFrame holds a null
  • THEN that cell is missing (isNull), and subMissing shows it as for any data

Text with a zero in front

parseCsv SHALL read a column as text when one of its values is a number written with a zero in front ("0400", not "0" or "0.5"), as pandas and Polars keep such codes, times and postcodes; a missing value SHALL stay missing. import tabelline/nanuq SHALL turn a list column of a nanuq DataFrame (of integers, floats, Booleans or strings) into lists, which nanoplots draw.

✓ the output matches openspec/specs/table-data/spec.md:186
let d = parseCsv("tst,sza\n0530,84.9\n1200,\n")
echo d["tst", 0], " ", d["tst", 0].kind, " ", d["sza", 0].kind, " ", d["sza", 1].isNull
what it prints
0530 vkString vkFloat true

source: openspec/specs/table-data/spec.md

table-parts 33 requirements · 6 scenarios · 35 examplesThe parts of a display table, after gt and Great Tables: the header, the column labels and spanners, the stub and its head, row groups, the body, and the footer with footnotes and source notes; and the verbs that set them.

A table spec for the data

tabella(data) SHALL make a table spec (Tabella) for the data: one boxhead entry per column, labelled with its name, numbers aligned right and text left. rownameCol SHALL make a column the stub, groupnameCol SHALL group the rows by a column in order of first appearance. Every verb SHALL take a Tabella and return a new one, leaving the data untouched.

✓ the output matches openspec/specs/table-parts/spec.md:16
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
echo t
moons
Terrestrial
Mercury0
Venus0
Earth1
Mars2
Gas giant
Jupiter95
Saturn146
Ice giant
Uranus28
Neptune16
what it prints
┌─────────┬───────┐
│         │ moons │
╞═════════╪═══════╡
│ Terrestrial     │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Mercury │     0 │
│ Venus   │     0 │
│ Earth   │     1 │
│ Mars    │     2 │
├─────────┼───────┤
│ Gas giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Jupiter │    95 │
│ Saturn  │   146 │
├─────────┼───────┤
│ Ice giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus  │    28 │
│ Neptune │    16 │
└─────────┴───────┘
Scenario: Verbs do not change their input
  • WHEN let b = a.tabHeader("x")
  • THEN a has no title and b has

Header, stubhead and source notes

tabHeader(title, subtitle), tabStubhead(label) and tabSourceNote(note) SHALL set the title and subtitle, the stub's label, and add a source note. Labels and notes SHALL be plain text, or Markdown with md(...), or HTML with html(...).

✓ the output matches openspec/specs/table-parts/spec.md:54
let t = tabella(tavolaPitagorica(3), rownameCol = "×"):
  tabHeader "Times table", "from 1 to 3"
  tabStubhead "×"
  tabSourceNote md("Learned **by heart**")
echo t
Times table
from 1 to 3
×123
1123
2246
3369
Learned by heart
what it prints
   Times table
   from 1 to 3
┌───┬───┬───┬───┐
│ × │ 1 │ 2 │ 3 │
╞═══╪═══╪═══╪═══╡
│ 1 │ 1 │ 2 │ 3 │
│ 2 │ 2 │ 4 │ 6 │
│ 3 │ 3 │ 6 │ 9 │
└───┴───┴───┴───┘
Learned by heart

Column labels and spanners

colsLabel SHALL relabel columns, colsAlign, colsWidth, colsHide, colsMove and colsMoveToStart SHALL align, size, hide and reorder them. tabSpanner(label, columns, level = 1) SHALL put a label over columns; spanners of a higher level sit above lower ones, and two spanners of one level SHALL NOT overlap.

✓ the output matches openspec/specs/table-parts/spec.md:81
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "density", "gravity", "day_length", "mean_temp", "rings", "moons"]
  colsLabel:
    orbital_period: "year"
  tabSpanner "Size", ["mass", "diameter"]
  tabSpanner "Orbit", ["distance", "orbital_period"]
echo t
SizeOrbit
massdiameterdistanceyear
Mercury0.33487957.988.0
Venus4.8712104108.2224.7
Earth5.9712756149.6365.2
Mars0.6426792228.0687.0
Jupiter1898.0142984778.54331.0
Saturn568.01205361432.010747.0
Uranus86.8511182867.030589.0
Neptune102.0495284515.059800.0
what it prints
┌─────────┬────────┬──────────┬──────────┬─────────┐
│         │       Size        │       Orbit        │
│         │   mass │ diameter │ distance │    year │
╞═════════╪════════╪══════════╪══════════╪═════════╡
│ Mercury │   0.33 │     4879 │     57.9 │    88.0 │
│ Venus   │   4.87 │    12104 │    108.2 │   224.7 │
│ Earth   │   5.97 │    12756 │    149.6 │   365.2 │
│ Mars    │  0.642 │     6792 │    228.0 │   687.0 │
│ Jupiter │ 1898.0 │   142984 │    778.5 │  4331.0 │
│ Saturn  │  568.0 │   120536 │   1432.0 │ 10747.0 │
│ Uranus  │   86.8 │    51118 │   2867.0 │ 30589.0 │
│ Neptune │  102.0 │    49528 │   4515.0 │ 59800.0 │
└─────────┴────────┴──────────┴──────────┴─────────┘
Scenario: Overlapping spanners
  • WHEN a second level-1 spanner covers a column of the first
  • THEN tabSpanner raises a ValueError

Row groups

Rows SHALL be grouped by groupnameCol or by tabRowGroup(label, rows). Groups SHALL show in the order they are made, after the rows that are in no group.

✓ the output matches openspec/specs/table-parts/spec.md:115
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "mass", "diameter", "density", "gravity", "day_length", "orbital_period", "mean_temp", "rings"]
  tabRowGroup "Giants", where(it["type"] != "Terrestrial")
echo t
distancemoons
Mercury57.90
Venus108.20
Earth149.61
Mars228.02
Giants
Jupiter778.595
Saturn1432.0146
Uranus2867.028
Neptune4515.016
what it prints
┌─────────┬──────────┬───────┐
│         │ distance │ moons │
╞═════════╪══════════╪═══════╡
│ Mercury │     57.9 │     0 │
│ Venus   │    108.2 │     0 │
│ Earth   │    149.6 │     1 │
│ Mars    │    228.0 │     2 │
├─────────┼──────────┼───────┤
│ Giants                     │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Jupiter │    778.5 │    95 │
│ Saturn  │   1432.0 │   146 │
│ Uranus  │   2867.0 │    28 │
│ Neptune │   4515.0 │    16 │
└─────────┴──────────┴───────┘

Footnotes

tabFootnote(note, locations) SHALL add a note in the footer and mark it at each location. Marks SHALL be numbered in reading order of their locations (title, spanners, column labels, then the groups, stub and body row by row), whatever the order the notes were added; the same note at several places SHALL get one mark. footnotesMarks SHALL choose numbers, letters, capitals or the symbols *, †, ‡, §.

✓ the output matches openspec/specs/table-parts/spec.md:147
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "rings"]
  tabFootnote "Hotter than Mercury.", loc.body(cols = "mean_temp", rows = where(it.planet == "Venus"))
  tabFootnote "As of 2024.", loc.columnLabels("moons")
echo t
mean_tempmoons1
Mercury1670
Venus46420
Earth151
Mars-652
Jupiter-11095
Saturn-140146
Uranus-19528
Neptune-20016
1 As of 2024.
2 Hotter than Mercury.
what it prints
┌─────────┬───────────┬─────────┐
│         │ mean_temp │ moons^1 │
╞═════════╪═══════════╪═════════╡
│ Mercury │       167 │       0 │
│ Venus   │     464^2 │       0 │
│ Earth   │        15 │       1 │
│ Mars    │       -65 │       2 │
│ Jupiter │      -110 │      95 │
│ Saturn  │      -140 │     146 │
│ Uranus  │      -195 │      28 │
│ Neptune │      -200 │      16 │
└─────────┴───────────┴─────────┘
1 As of 2024.
2 Hotter than Mercury.

Spanners from column names

tabSpannerDelim(delim = ".", columns, split = "last", limit = -1, reverse = false) SHALL split column names at delim: the last part SHALL become the label and the parts before it spanners, the first part highest. Next to each other, columns with the same parts SHALL share a spanner. limit SHALL cap the number of splits, counted from the split side; reverse SHALL read the parts the other way round.

✓ the output matches openspec/specs/table-parts/spec.md:179
let d = tableData:
  planet: ["Earth", "Mars"]
  size.diameter: [12756, 6792]
  size.mass: [5.97, 0.642]
  orbit.period.days: [365.2, 687.0]
  orbit.period.years: [1.0, 1.88]
  orbit.distance: [149.6, 228.0]
let t = tabella(d, rownameCol = "planet"):
  tabSpannerDelim()
echo t
orbit
sizeperiod
diametermassdaysyearsdistance
Earth127565.97365.21.0149.6
Mars67920.642687.01.88228.0
what it prints
┌───────┬──────────┬───────┬───────┬───────┬──────────┐
│       │                  │          orbit           │
│       │       size       │    period     │          │
│       │ diameter │  mass │  days │ years │ distance │
╞═══════╪══════════╪═══════╪═══════╪═══════╪══════════╡
│ Earth │    12756 │  5.97 │ 365.2 │   1.0 │    149.6 │
│ Mars  │     6792 │ 0.642 │ 687.0 │  1.88 │    228.0 │
└───────┴──────────┴───────┴───────┴───────┴──────────┘
Scenario: A name with no delimiter
  • WHEN a selected column has no delim in its name
  • THEN its label stays and it gets no spanner

Caption

tabCaption(caption) SHALL give the table a caption: an HTML <caption> above the table (for screen readers, and for figures in documents), a first line in text, an italic line in Markdown. rmCaption() SHALL take it away.

✓ the output matches openspec/specs/table-parts/spec.md:212
let t = tabella(tavolaPitagorica(2)):
  tabCaption "Table 1: the times table of 2"
echo "<caption class=\"tb_caption\">Table 1: the times table of 2</caption>" in t.toHtml
echo t
Table 1: the times table of 2
×12
112
224
what it prints
true
Table 1: the times table of 2
┌───┬───┬───┐
│ × │ 1 │ 2 │
╞═══╪═══╪═══╡
│ 1 │ 1 │ 2 │
│ 2 │ 2 │ 4 │
└───┴───┴───┘

Removing parts

rmHeader(), rmStubhead(), rmCaption(), rmSpanners(spanners, levels), rmFootnotes(indices) and rmSourceNotes(indices) SHALL take parts away, so tables built from a shared start can drop what they do not need. With no arguments, rmSpanners, rmFootnotes and rmSourceNotes SHALL remove all of them; indices SHALL count from 0 in the order the parts were added.

✓ the output matches openspec/specs/table-parts/spec.md:236
let base = tabella(tavolaPitagorica(2), rownameCol = "×"):
  tabHeader "Times", "of two"
  tabSourceNote "One."
  tabSourceNote "Two."
let less = tabella(base):
  rmHeader()
  rmSourceNotes [0]
echo less
12
112
224
Two.
what it prints
┌───┬───┬───┐
│   │ 1 │ 2 │
╞═══╪═══╪═══╡
│ 1 │ 1 │ 2 │
│ 2 │ 2 │ 4 │
└───┴───┴───┘
Two.

Labels from a proc

colsLabelWith(columns, fn) SHALL relabel columns (by default all of them) with a proc over their labels.

✓ the output matches openspec/specs/table-parts/spec.md:261
let t = tabella(tavolaPitagorica(2), rownameCol = "×"):
  colsLabelWith proc (s: string): string = "×" & s
echo t
×1×2
112
224
what it prints
┌───┬────┬────┐
│   │ ×1 │ ×2 │
╞═══╪════╪════╡
│ 1 │  1 │  2 │
│ 2 │  2 │  4 │
└───┴────┴────┘

Moving columns

colsMove(columns, after), colsMoveToStart(columns) and colsMoveToEnd(columns) SHALL move columns; colsReorder(columns) SHALL put the given columns in the given order in the places they hold, leaving the other columns where they are.

✓ the output matches openspec/specs/table-parts/spec.md:281
let d = tableData:
  a: [1]
  b: [2]
  c: [3]
  d: [4]
let t = tabella(d):
  colsMoveToEnd "a"
  colsReorder ["d", "b"]
echo t
dcba
4321
what it prints
┌───┬───┬───┬───┐
│ d │ c │ b │ a │
╞═══╪═══╪═══╪═══╡
│ 4 │ 3 │ 2 │ 1 │
└───┴───┴───┴───┘

Order of rows and groups

rowOrder(columns, reverse) SHALL show the rows sorted by the columns (the first decides, the next break ties), within their groups, with missing values last; rowGroupOrder(groups) SHALL show the row groups in the given order, the others after them as they were.

✓ the output matches openspec/specs/table-parts/spec.md:306
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
  rowOrder "moons", reverse = true
  rowGroupOrder ["Ice giant", "Gas giant"]
echo t
moons
Ice giant
Uranus28
Neptune16
Gas giant
Saturn146
Jupiter95
Terrestrial
Mars2
Earth1
Mercury0
Venus0
what it prints
┌─────────┬───────┐
│         │ moons │
╞═════════╪═══════╡
│ Ice giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus  │    28 │
│ Neptune │    16 │
├─────────┼───────┤
│ Gas giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Saturn  │   146 │
│ Jupiter │    95 │
├─────────┼───────┤
│ Terrestrial     │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Mars    │     2 │
│ Earth   │     1 │
│ Mercury │     0 │
│ Venus   │     0 │
└─────────┴───────┘

Text helpers

Labels and notes SHALL be plain text (escaped in HTML), md(text) (inline Markdown: **bold**, *italic*, `code`, links, ^sup^ and ~sub~ when closed with no space inside, so "~50" stays as it is) or html(text) (used as is in HTML, its tags stripped in text and Markdown).

✓ the output matches openspec/specs/table-parts/spec.md:342
let t = tabella(tavolaPitagorica(2)):
  tabHeader md("The **times** table"), html("of <span style=\"color: red\">two</span>")
echo "<strong>times</strong>" in t.toHtml, " ", "<span style=\"color: red\">two</span>" in t.toHtml
echo t
The times table
of two
×12
112
224
what it prints
true true
The times table
   of two
┌───┬───┬───┐
│ × │ 1 │ 2 │
╞═══╪═══╪═══╡
│ 1 │ 1 │ 2 │
│ 2 │ 2 │ 4 │
└───┴───┴───┘

Summary rows

summaryRows(fns, groups, columns, side, missingText) SHALL add, under each row group (or each of groups), one row for each aggregate of fns, labelled in the stub; fns SHALL be pairs of a label and an aggregate, {"total": agg.sum}. columns SHALL say which columns are summed up (the numeric ones by default); the other visible columns, and a cell with nothing to sum up, SHALL show missingText (by default "—"). With side = sTop the rows SHALL come right after the group's label, before its rows. A table with summary rows and no row names SHALL get a stub, for the labels. summaryRows SHALL raise a ValueError on a table without row groups.

✓ the output matches openspec/specs/table-parts/spec.md:370
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
  summaryRows:
    total: agg.sum
echo t
moons
Terrestrial
Mercury0
Venus0
Earth1
Mars2
total3
Gas giant
Jupiter95
Saturn146
total241
Ice giant
Uranus28
Neptune16
total44
what it prints
┌─────────┬───────┐
│         │ moons │
╞═════════╪═══════╡
│ Terrestrial     │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Mercury │     0 │
│ Venus   │     0 │
│ Earth   │     1 │
│ Mars    │     2 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total   │     3 │
├─────────┼───────┤
│ Gas giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Jupiter │    95 │
│ Saturn  │   146 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total   │   241 │
├─────────┼───────┤
│ Ice giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus  │    28 │
│ Neptune │    16 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total   │    44 │
└─────────┴───────┘
Scenario: Summary above the group
  • WHEN side = sTop is given
  • THEN the summary rows come right after the group's label, before its rows
Scenario: Some groups only
  • WHEN groups = ["Ice giant"] is given
  • THEN only that group gets summary rows, and a group that does not exist raises a KeyError
Scenario: A group with no numbers
  • WHEN every value of a summarised column in a group is missing
  • THEN its summary cell shows missingText

Grand summary rows

grandSummaryRows(fns, columns, side, missingText) SHALL add rows that sum up every row of the table, whatever its group, at the bottom (or at the top with side = sTop), set apart from the body by a double rule.

✓ the output matches openspec/specs/table-parts/spec.md:424
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
  summaryRows:
    total: agg.sum
  grandSummaryRows:
    "all moons": agg.sum
echo t
moons
Terrestrial
Mercury0
Venus0
Earth1
Mars2
total3
Gas giant
Jupiter95
Saturn146
total241
Ice giant
Uranus28
Neptune16
total44
all moons288
what it prints
┌───────────┬───────┐
│           │ moons │
╞═══════════╪═══════╡
│ Terrestrial       │
├┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Mercury   │     0 │
│ Venus     │     0 │
│ Earth     │     1 │
│ Mars      │     2 │
├┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total     │     3 │
├───────────┼───────┤
│ Gas giant         │
├┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Jupiter   │    95 │
│ Saturn    │   146 │
├┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total     │   241 │
├───────────┼───────┤
│ Ice giant         │
├┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus    │    28 │
│ Neptune   │    16 │
├┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total     │    44 │
╞═══════════╪═══════╡
│ all moons │   288 │
└───────────┴───────┘

Aggregates and their format

An aggregate SHALL be a proc from the column's non-missing values to a Value. agg.sum, agg.mean, agg.median, agg.min, agg.max, agg.count and agg.std (of a sample) SHALL be built in, and aggregate(proc) SHALL make one from any proc that returns a value or something toValue converts. A summary cell SHALL be formatted with the last format given to its whole column, agg.count as an integer, and a number with no format with two decimals; fmt SHALL format the rows of one call instead, from a proc of a float, of a value, or a FormatFn.

✓ the output matches openspec/specs/table-parts/spec.md:473
let middle = aggregate(proc (vs: seq[Value]): Value = vs[vs.len div 2])
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "mass", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
  fmtInteger "diameter"
  grandSummaryRows:
    planets: agg.count
    largest: agg.max
    "middle one": middle
  grandSummaryRows:
    mean: agg.mean
    fmt = (x: float) => formatNumber(x, decimals = 1)
echo t
diametermoons
Mercury4,8790
Venus12,1040
Earth12,7561
Mars6,7922
Jupiter142,98495
Saturn120,536146
Uranus51,11828
Neptune49,52816
planets88
largest142,984146
middle one142,98495
mean50,087.136.0
what it prints
┌────────────┬──────────┬───────┐
│            │ diameter │ moons │
╞════════════╪══════════╪═══════╡
│ Mercury    │    4,879 │     0 │
│ Venus      │   12,104 │     0 │
│ Earth      │   12,756 │     1 │
│ Mars       │    6,792 │     2 │
│ Jupiter    │  142,984 │    95 │
│ Saturn     │  120,536 │   146 │
│ Uranus     │   51,118 │    28 │
│ Neptune    │   49,528 │    16 │
╞════════════╪══════════╪═══════╡
│ planets    │        8 │     8 │
│ largest    │  142,984 │   146 │
│ middle one │  142,984 │    95 │
│ mean       │ 50,087.1 │  36.0 │
└────────────┴──────────┴───────┘

The look of summary rows

Summary rows SHALL be drawn apart from the body: in HTML with the classes tb_summary_row and tb_grand_summary_row, a rule above the first row (below the last, when they come first) and the options summaryRowBackgroundColor, summaryRowTextTransform, summaryRowPadding, summaryRowPaddingHorizontal, summaryRowBorderStyle, summaryRowBorderWidth, summaryRowBorderColor, and the same with grandSummaryRow, as gt's; in text with a dotted rule (a group's) or a double rule (the table's); in Markdown with the label in italics (a group's) or in bold (the table's).

✓ the output matches openspec/specs/table-parts/spec.md:517
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
  summaryRows:
    total: agg.sum
    groups = ["Ice giant"]
  grandSummaryRows:
    "all moons": agg.sum
  tabOptions grandSummaryRowBackgroundColor = "#FFF3B0"
  tabStyle style.text(weight = "bold"), loc.grandSummary()
echo t.toMarkdown
echo "background-color: #FFF3B0" in t.toHtml
what it prints
|  | moons |
|:--|--:|
| **Terrestrial** |  |
| Mercury | 0 |
| Venus | 0 |
| Earth | 1 |
| Mars | 2 |
| **Gas giant** |  |
| Jupiter | 95 |
| Saturn | 146 |
| **Ice giant** |  |
| Uranus | 28 |
| Neptune | 16 |
| *total* | 44 |
| **all moons** | 288 |
true

Merged columns

colsMerge(columns, rows, pattern, autohide = true) SHALL show the formatted values of columns in the first one, by pattern: {1}, {2}, ... SHALL be the columns' cells, and a part between << and >> SHALL be left out when a value it names is missing. Without a pattern the cells SHALL be joined by spaces. The other columns SHALL be hidden unless autohide = false. colsMergeUncert(colVal, colUncert) SHALL show value ± uncertainty, colsMergeRange(colBegin, colEnd) SHALL show begin–end and colsMergeNPct(colN, colPct) SHALL show n (pct), with no percentage after a zero count; each SHALL show just the first value when the second is missing.

✓ the output matches openspec/specs/table-parts/spec.md:559
let d = tableData:
  mission: ["Voyager 1", "Galileo", "Cassini"]
  launch: [1977, 1989, 1997]
  ended: [nil, 2003, 2017]
  target: ["Jupiter, Saturn", "Jupiter", "Saturn"]
  moon: [nil, "Io", "Titan"]
let t = tabella(d, rownameCol = "mission"):
  colsMergeRange "launch", "ended"
  colsMerge ["target", "moon"], pattern = "{1}<< and {2}>>"
echo t
launchtarget
Voyager 11977Jupiter, Saturn
Galileo1989–2003Jupiter and Io
Cassini1997–2017Saturn and Titan
what it prints
┌───────────┬───────────┬──────────────────┐
│           │    launch │ target           │
╞═══════════╪═══════════╪══════════════════╡
│ Voyager 1 │      1977 │ Jupiter, Saturn  │
│ Galileo   │ 1989–2003 │ Jupiter and Io   │
│ Cassini   │ 1997–2017 │ Saturn and Titan │
└───────────┴───────────┴──────────────────┘

Added columns

colsAdd(name, values, before, after) SHALL add a column, at the end or before or after another one, from Values, from Nim values, or from a proc of each row. The data of the table it was added to SHALL stay as it was.

✓ the output matches openspec/specs/table-parts/spec.md:587
let t = tabella(planets(), rownameCol = "planet"):
  colsHide everything()
  colsAdd "moons per Earth mass", proc (r: Row): Value = toValue(r.moons.toFloat / r.mass.toFloat * 5.97)
  fmtNumber "moons per Earth mass", decimals = 1
echo t
moons per Earth mass
Mercury0.0
Venus0.0
Earth1.0
Mars18.6
Jupiter0.3
Saturn1.5
Uranus1.9
Neptune0.9
what it prints
┌─────────┬──────────────────────┐
│         │ moons per Earth mass │
╞═════════╪══════════════════════╡
│ Mercury │                  0.0 │
│ Venus   │                  0.0 │
│ Earth   │                  1.0 │
│ Mars    │                 18.6 │
│ Jupiter │                  0.3 │
│ Saturn  │                  1.5 │
│ Uranus  │                  1.9 │
│ Neptune │                  0.9 │
└─────────┴──────────────────────┘

Summary columns

summaryColumns(fns, columns, fmt, side = sRight, missingText) SHALL add a column for each aggregate of fns, its label the name, summing up columns (the numeric ones by default) across each row, at the right of the table or at the left of the data. The new column SHALL be formatted like the first column it sums up, or by fmt. Summary rows SHALL sum it up like any column.

✓ the output matches openspec/specs/table-parts/spec.md:616
let medals = tableData:
  country: ["Norway", "Germany", "Italy"]
  gold: [16, 12, 7]
  silver: [8, 10, 8]
  bronze: [13, 5, 9]
let t = tabella(medals, rownameCol = "country"):
  summaryColumns:
    total: agg.sum
  grandSummaryRows:
    all: agg.sum
echo t
goldsilverbronzetotal
Norway1681337
Germany1210527
Italy78924
all35262788
what it prints
┌─────────┬──────┬────────┬────────┬───────┐
│         │ gold │ silver │ bronze │ total │
╞═════════╪══════╪════════╪════════╪═══════╡
│ Norway  │   16 │      8 │     13 │    37 │
│ Germany │   12 │     10 │      5 │    27 │
│ Italy   │    7 │      8 │      9 │    24 │
╞═════════╪══════╪════════╪════════╪═══════╡
│ all     │   35 │     26 │     27 │    88 │
└─────────┴──────┴────────┴────────┴───────┘

Added and hidden rows

rowsAdd(rows, before, after) SHALL add rows, from a TableData of some of the columns or from Nim objects, the other columns missing, at the end or before or after a row of the data; a value of the group column SHALL put a row in its group, made when new. rowsHide(rows) SHALL hide rows, which summary rows then leave out, and rowsUnhide(rows) SHALL show them again.

✓ the output matches openspec/specs/table-parts/spec.md:648
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings"]
  rowsHide where(it["type"] != "Ice giant")
  rowsAdd [(planet: "Pluto", `type`: "Dwarf planet", moons: 5)]
echo t
moons
Ice giant
Uranus28
Neptune16
Dwarf planet
Pluto5
what it prints
┌─────────┬───────┐
│         │ moons │
╞═════════╪═══════╡
│ Ice giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus  │    28 │
│ Neptune │    16 │
├─────────┼───────┤
│ Dwarf planet    │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Pluto   │     5 │
└─────────┴───────┘

Stub indent

tabStubIndent(rows, indent) SHALL indent the stub cells of rows by a level from 0 to 5, given as a number or as "increase" or "decrease" (one level more or less than now).

✓ the output matches openspec/specs/table-parts/spec.md:675
let budget = tableData:
  item: ["Hardware", "Laptops", "Screens", "Travel"]
  eur: [5200, 4000, 1200, 900]
let t = tabella(budget, rownameCol = "item"):
  tabStubIndent [1, 2], "increase"
  fmtInteger "eur"
echo t
eur
Hardware5,200
Laptops4,000
Screens1,200
Travel900
what it prints
┌───────────┬───────┐
│           │   eur │
╞═══════════╪═══════╡
│ Hardware  │ 5,200 │
│   Laptops │ 4,000 │
│   Screens │ 1,200 │
│ Travel    │   900 │
└───────────┴───────┘

Aligned on the decimal mark

colsAlignDecimal(columns, decMark, locale) SHALL align the formatted numbers of columns on their decimal mark (the locale's by default), padding each on the right with figure spaces, and a punctuation space for a number with no mark, and SHALL align the columns right.

✓ the output matches openspec/specs/table-parts/spec.md:701
let d = tableData:
  x: [1.5, 10.25, 3.0, 120.125]
let t = tabella(d):
  fmtNumber "x", decimals = 3, dropTrailingZeros = true
  colsAlignDecimal "x"
echo t.toMarkdown
what it prints
| x |
|--:|
| 1.5   |
| 10.25  |
| 3     |
| 120.125 |

Rotated labels

colsLabelRotate(columns, dir) SHALL turn the column labels of columns on their side in HTML, read from the bottom up ("sideways-lr", the default), from the top down ("sideways-rl"), or slanted at 45 degrees, read upwards to the right ("slanted", not from gt); the text and Markdown outputs SHALL keep them as they are. Another dir SHALL raise a ValueError.

✓ the output matches openspec/specs/table-parts/spec.md:726
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp"]
  colsLabelRotate ["moons", "rings"]
echo t.toHtml.count("writing-mode: vertical-rl; transform: rotate(180deg)")
what it prints
2

Preview of a big table

tabellaPreview(data, topN, bottomN, inclRownums, moreRows) SHALL make a table of the first topN rows, the rows of moreRows (a row selector, not from gt: indices from 0, a range, a set such as {4, 6..7}, or where(...)) and the last bottomN rows of data, in their order, with a shaded row for each run of rows left out that names them ("6..99"), and the row numbers (from 1) in the stub when inclRownums. A run of a single row SHALL be shown, not left out, so a table with no more than topN + bottomN + 1 rows is shown whole. Like tabella, it SHALL take a body of verbs.

✓ the output matches openspec/specs/table-parts/spec.md:746
let preview = tabellaPreview(planets(), topN = 2, bottomN = 1):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp"]
echo preview
planettypemoonsrings
1MercuryTerrestrial0false
2VenusTerrestrial0false
3..7
8NeptuneIce giant16true
what it prints
┌──────┬─────────┬─────────────┬───────┬───────┐
│      │ planet  │ type        │ moons │ rings │
╞══════╪═════════╪═════════════╪═══════╪═══════╡
│ 1    │ Mercury │ Terrestrial │     0 │ false │
│ 2    │ Venus   │ Terrestrial │     0 │ false │
│ 3..7 │         │             │       │       │
│ 8    │ Neptune │ Ice giant   │    16 │ true  │
└──────┴─────────┴─────────────┴───────┴───────┘
✓ the output matches openspec/specs/table-parts/spec.md:763
let preview = tabellaPreview(planets(), topN = 2, bottomN = 1, moreRows = where(it.planet == "Jupiter")):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp"]
echo preview
planettypemoonsrings
1MercuryTerrestrial0false
2VenusTerrestrial0false
3..4
5JupiterGas giant95true
6..7
8NeptuneIce giant16true
what it prints
┌──────┬─────────┬─────────────┬───────┬───────┐
│      │ planet  │ type        │ moons │ rings │
╞══════╪═════════╪═════════════╪═══════╪═══════╡
│ 1    │ Mercury │ Terrestrial │     0 │ false │
│ 2    │ Venus   │ Terrestrial │     0 │ false │
│ 3..4 │         │             │       │       │
│ 5    │ Jupiter │ Gas giant   │    95 │ true  │
│ 6..7 │         │             │       │       │
│ 8    │ Neptune │ Ice giant   │    16 │ true  │
└──────┴─────────┴─────────────┴───────┴───────┘

Columns of nanoplots

colsNanoplot(columns, rows, plotType, ..., newColName = "nanoplots", newColLabel, before, after, autohide = true) SHALL add a column with a nanoplot per row of the values of columns, in their order (a missing value is NA), at the end or before or after a column, labelled newColLabel (its name by default), and SHALL hide columns unless autohide is false. The other arguments SHALL be those of fmtNanoplot. With xVals (not from gt), one place on the x axis for each of columns, the same in every row, each cell SHALL be a record of x and y, so that referenceX draws its vertical lines; xVals of another length than columns SHALL raise ValueError.

✓ the output matches openspec/specs/table-parts/spec.md:792
let t = tabella(tavolaPitagorica(4), rownameCol = "×"):
  colsNanoplot ["1", "2", "3", "4"], newColLabel = "the row", autoscale = true
echo t
the row
11611234
21612468
316136912
4161481216
what it prints
┌───┬───────────┐
│   │ the row   │
╞═══╪═══════════╡
│ 1 │ ▁▁▂▂ 1–4  │
│ 2 │ ▁▂▃▄ 2–8  │
│ 3 │ ▂▃▅▆ 3–12 │
│ 4 │ ▂▄▆█ 4–16 │
└───┴───────────┘
✓ the output matches openspec/specs/table-parts/spec.md:809
let d = tableData:
  region: ["north", "south"]
  y2012: [8.1, 18.4]
  y2013: [9.0, 21.0]
  y2014: [8.6, 20.2]
  y2015: [7.7, 17.9]
let t = tabella(d, rownameCol = "region"):
  colsNanoplot ["y2012", "y2013", "y2014", "y2015"], newColLabel = "2012–2015", autoscale = true,
    xVals = @[2012.0, 2013.0, 2014.0, 2015.0], referenceX = @["2013"]
echo t
echo t.toHtml.count("stroke-dasharray"), " lines"
2012–2015
north201321.07.708.109.008.607.70
south201321.07.7018.421.020.217.9
what it prints
┌───────┬────────────────┐
│       │ 2012–2015      │
╞═══════╪════════════════╡
│ north │ ▁▂▁▁ 7.70–9.00 │
│ south │ ▇██▆ 17.9–21.0 │
└───────┴────────────────┘
2 lines

Fields of a record in a merge pattern

A colsMerge pattern SHALL read the fields of a record: {2.lo} is the field lo of the record in column 2, and {lo} the field lo of column 1. Each field SHALL be formatted as its column is, and SHALL count as missing for a <<...>> part when it is missing. A pattern of one column SHALL show that column's records in the pattern. The verb SHALL raise ValueError when a field the pattern names is not in every record of its column, or the column does not hold records.

✓ the output matches openspec/specs/table-parts/spec.md:840
let d = tableData:
  sensor: ["north", "south"]
  span: [(lo: 0.82, hi: 1.56), (lo: 9.13, hi: 12.71)]
  unit: ["mm", "cm"]
let t = tabella(d, rownameCol = "sensor"):
  fmtNumber "span", decimals = 1
  colsMerge ["span", "unit"], pattern = "{lo}–{hi}<< {2}>>"
echo t
span
north0.8–1.6 mm
south9.1–12.7 cm
what it prints
┌───────┬─────────────┐
│       │ span        │
╞═══════╪═════════════╡
│ north │ 0.8–1.6 mm  │
│ south │ 9.1–12.7 cm │
└───────┴─────────────┘

Stub of several columns

tabella(data, rownameCol = ["mfr", "model"]) SHALL make a stub of those columns, the leftmost the highest level and the last the row names. A value of a higher level equal to the one above it, under the same higher levels and in the same group, SHALL be drawn once: in HTML a <th> spanning its rows, in text and Markdown a blank cell. The stubhead SHALL span the stub. loc.stub(rows, cols) SHALL pick stub columns (all of them by default), loc.body SHALL leave them out, and stubColumns(t) SHALL give them in order. extractBody SHALL give every level, on every row.

✓ the output matches openspec/specs/table-parts/spec.md:869
let d = tableData:
  mfr: ["Ferrari", "Ferrari", "Ford", "Ford", "Fiat"]
  model: ["Roma", "Portofino", "GT", "Mustang", "500"]
  hp: [612, 600, 647, 450, 69]
let t = tabella(d, rownameCol = ["mfr", "model"]):
  tabStubhead "car"
  tabStyle style.text(weight = "bold"), loc.stub(cols = "mfr")
echo t
echo "stub: ", stubColumns(t).join(", "), "; cells over two rows: ", t.toHtml.count("rowspan=\"2\"")
carhp
FerrariRoma612
Portofino600
FordGT647
Mustang450
Fiat50069
what it prints
┌─────────┬───────────┬─────┐
│ car     │           │  hp │
╞═════════╪═══════════╪═════╡
│ Ferrari │ Roma      │ 612 │
│         │ Portofino │ 600 │
│ Ford    │ GT        │ 647 │
│         │ Mustang   │ 450 │
│ Fiat    │ 500       │  69 │
└─────────┴───────────┴─────┘
stub: mfr, model; cells over two rows: 2

Groups as a column

With tabOptions(rowGroupAsColumn = true), or tabella(data, rownameCol, groupnameCol, rowGroupAsColumn = true) (as gt's row_group_as_column), the label of each group SHALL be the first column of the stub, spanning the group's rows and summary rows, instead of a row above them; the grand summary rows' labels SHALL span the whole stub. In text and Markdown the label SHALL be on the group's first row.

✓ the output matches openspec/specs/table-parts/spec.md:901
let d = tableData:
  model: ["GT", "Mustang", "Roma", "Portofino"]
  kind: ["sport", "sport", "touring", "touring"]
  hp: [647, 450, 612, 600]
let t = tabella(d, rownameCol = "model", groupnameCol = "kind", rowGroupAsColumn = true):
  summaryRows:
    total: agg.sum
echo t
hp
sportGT647
Mustang450
total1097
touringRoma612
Portofino600
total1212
what it prints
┌─────────┬───────────┬──────┐
│         │           │   hp │
╞═════════╪═══════════╪══════╡
│ sport   │ GT        │  647 │
│         │ Mustang   │  450 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┤
│         │ total     │ 1097 │
├─────────┼───────────┼──────┤
│ touring │ Roma      │  612 │
│         │ Portofino │  600 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┤
│         │ total     │ 1212 │
└─────────┴───────────┴──────┘

A spanner gathers its columns

tabSpanner SHALL move its columns next to the first of them, in the order given, so its label spans them all, as gt's gather = TRUE; gather = false SHALL leave them where they are.

✓ the output matches openspec/specs/table-parts/spec.md:932
let t = tabella(planets(), rownameCol = "planet"):
  colsHide ["type", "density", "gravity", "day_length", "orbital_period", "mean_temp", "rings"]
  rowsHide 2 .. 7
  tabSpanner "size", ["mass", "diameter", "moons"]
echo t
sizedistance
massdiametermoons
Mercury0.334879057.9
Venus4.87121040108.2
what it prints
┌─────────┬──────┬──────────┬───────┬──────────┐
│         │          size           │          │
│         │ mass │ diameter │ moons │ distance │
╞═════════╪══════╪══════════╪═══════╪══════════╡
│ Mercury │ 0.33 │     4879 │     0 │     57.9 │
│ Venus   │ 4.87 │    12104 │     0 │    108.2 │
└─────────┴──────┴──────────┴───────┴──────────┘

Summary rows with the same label are one row

Two summary verbs that give a row of the same label, in the same group and on the same side, SHALL make one row, each filling its own columns, as gt does. extractSummary(t, values = true) SHALL give the values of the summary cells instead of their text, as gt's extract_summary().

✓ the output matches openspec/specs/table-parts/spec.md:955
let t = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
  colsHide ["density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings", "diameter"]
  rowsHide 0 .. 3
  summaryRows:
    total: agg.sum
    columns = "moons"
  summaryRows:
    total: agg.sum
    columns = "mass"
    fmtNumber(decimals = 0)
echo t
echo extractSummary(t, values = true)["mass", 0].kind
massmoons
Gas giant
Jupiter1898.095
Saturn568.0146
total2,466241
Ice giant
Uranus86.828
Neptune102.016
total18944
what it prints
┌─────────┬────────┬───────┐
│         │   mass │ moons │
╞═════════╪════════╪═══════╡
│ Gas giant                │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Jupiter │ 1898.0 │    95 │
│ Saturn  │  568.0 │   146 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total   │  2,466 │   241 │
├─────────┼────────┼───────┤
│ Ice giant                │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus  │   86.8 │    28 │
│ Neptune │  102.0 │    16 │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ total   │    189 │    44 │
└─────────┴────────┴───────┘
vkFloat

A line break in Markdown

In md(...) text, two spaces before a newline, or a backslash before it, SHALL be a line break (<br> in HTML, a space in text output), as in Markdown.

✓ the output matches openspec/specs/table-parts/spec.md:995
let t = tabella(planets()):
  colsHide ["type", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings", "diameter", "moons"]
  rowsHide 1 .. 7
  tabSpanner md("Mass  \n(10²⁴ kg)"), "mass"
echo t
echo "<br>" in t.toHtml
planetMass
(10²⁴ kg)
mass
Mercury0.33
what it prints
┌─────────┬────────────────┐
│         │ Mass (10²⁴ kg) │
│ planet  │           mass │
╞═════════╪════════════════╡
│ Mercury │           0.33 │
└─────────┴────────────────┘
true

The stub of a table already made

tabStub(rownameCol, groupnameCol) SHALL choose the stub (and the row groups) of a table already made, as Great Tables' tab_stub(), the same as tabella(data, rownameCol = ..., groupnameCol = ...); tabStub(["a", "b"]) SHALL make a stub of several columns. Verbs called before it SHALL keep what they did to the other columns. tabRowGroup(label, id = ...) SHALL give a new label, plain or Markdown, to a group that is already there (one made by groupnameCol is named by its value).

✓ the output matches openspec/specs/table-parts/spec.md:1022
let t = tabella(planets()):
  colsHide ["mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "moons"]
  tabStub "planet", groupnameCol = "type"
  tabRowGroup md"*Gas* giants", id = "Gas giant"
echo t
rings
Terrestrial
Mercuryfalse
Venusfalse
Earthfalse
Marsfalse
Gas giants
Jupitertrue
Saturntrue
Ice giant
Uranustrue
Neptunetrue
what it prints
┌─────────┬───────┐
│         │ rings │
╞═════════╪═══════╡
│ Terrestrial     │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Mercury │ false │
│ Venus   │ false │
│ Earth   │ false │
│ Mars    │ false │
├─────────┼───────┤
│ Gas giants      │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Jupiter │ true  │
│ Saturn  │ true  │
├─────────┼───────┤
│ Ice giant       │
├┄┄┄┄┄┄┄┄┄┼┄┄┄┄┄┄┄┤
│ Uranus  │ true  │
│ Neptune │ true  │
└─────────┴───────┘

Fuller Markdown

md() SHALL also read HTML entities (&mdash;, &#x1F310;), _em_ and __strong__ (not inside a word, so snake_case stays), ~~struck~~, <https://...> links, paragraphs (a blank line) and lists (- a, 1. a), as gt's Markdown does in a cell; one paragraph SHALL have no <p>. mdToHtml(text) SHALL give the HTML.

✓ the output matches openspec/specs/table-parts/spec.md:1059
echo mdToHtml("A &mdash; _it_ ~~old~~ snake_case")
echo mdToHtml("- a\n- b")
echo textToPlain(md("A &#x2014; B"))
what it prints
A &mdash; <em>it</em> <del>old</del> snake_case
<ul><li>a</li><li>b</li></ul>
A — B

source: openspec/specs/table-parts/spec.md

way-of-working 9 requirements · 11 scenarios · 0 examplesHow tabelline is made: specs with examples that run, pages kept up to date, stories and a devlog built as nimib notebooks, previews before merges.

Behaviour lives in the specs

Every agreed behaviour SHALL be a requirement with scenarios in openspec/specs/. New work SHALL start as an OpenSpec change in openspec/changes/ (proposal, spec deltas, tasks), be built in one PR, and be archived when it ships. Ideas not yet picked up SHALL live in BACKLOG.md.

Scenario: An idea becomes work
  • WHEN a backlog idea is picked up
  • THEN it becomes a change, its backlog entry is marked in progress, and when the change is archived the entry is removed and CHANGELOG.md gets a line

Examples that run

A requirement that describes Nim API SHALL have an example: a nim block followed by a text block with what it prints. nim r tools/specexamples.nim SHALL run every example of the specs in one program and fail when an output differs; --update SHALL write the actual outputs back. CI SHALL run them on every push and pull request.

Scenario: A change breaks an example
  • WHEN a change to the code makes an example print something else
  • THEN tools/specexamples.nim exits with an error showing the expected and the actual output

Pages are notebooks

Every page SHALL be a nimib notebook in docs/ that writes an HTML file, in the theme of the docs (useTabelline), with the code that made each table shown next to it. The pages SHALL share their style, fonts and scripts as files in docs/assets/, linked relatively, nothing loaded from another site; -d:singleFile SHALL build each page as one file with everything inlined. CI SHALL build all pages (docs/all.nim) and deploy them to GitHub Pages from main; the HTML SHALL NOT be committed.

Scenario: Reading two pages
  • WHEN a reader opens the home page, then the Guide
  • THEN the style and the fonts are downloaded once
Scenario: A one-page preview
  • WHEN a page is built with -d:singleFile
  • THEN its HTML file works alone, with no other file beside it

Pages kept up to date, and a devlog

The site SHALL have pages kept up to date as tabelline changes (the Guide, the specs page and the others on the home page), and a devlog of dated posts, each telling one step as it happened. A post SHALL NOT be rewritten afterwards, but it SHALL take edits: typos, links and small corrections. The home page SHALL list the pages in groups, by the question a reader brings, with names a newcomer can read. The devlog index SHALL list only the posts, newest first, read from the posts' sources. The specs page SHALL show every spec with its examples, their output and the HTML table each example makes.

Scenario: A new post
  • WHEN a post docs/devlog/<slug>.nim is added
  • THEN it appears on the devlog index at the next build with nothing else to edit, and gets a line in the README
Scenario: A typo in an old post
  • WHEN a reader finds a typo in a dated post
  • THEN it is fixed in the post, and the post keeps its date

Every page can be reviewed

Every page of the docs SHALL have the review mode (the spec review-mode), turned on by the theme: useTabelline SHALL call nbReview(), and useTabelline(review = false) SHALL leave it out. The pages SHALL share one copy of the script (docs/assets/review.js), as they share their style (the change share-site-assets).

Scenario: A new page
  • WHEN a new page is added to docs/
  • THEN it has a version line and ✎ Review with nothing to add to the page

Stories

The site SHALL have a Stories section: every release's use it thread SHALL tell a real subject in tables made with tabelline, as a story in docs/stories/<slug>.nim whose first line is ## story: <release> | <title> | <lede>. A release MAY have more stories than its use it thread's (such as one on how a story's data was made). The home page and the stories page SHALL show every story in a gallery, in release order (the first release first; in a release, the use it thread's story first), read from the stories' sources. Stories SHALL be kept up to date, and the roadmap SHALL link each use it thread to its story. A story that was published at another address SHALL keep it, forwarding to the story.

Scenario: A new story
  • WHEN a story docs/stories/<slug>.nim is added
  • THEN it appears in the gallery of the home page and of the stories page at the next build with nothing else to edit, and gets a line in the README

English, preview first

Specs, code, commits, PRs and the devlog SHALL be in English (Italian words are welcome as names). A change SHALL be shown to Pietro as a published preview before it is merged, and nothing SHALL go to main without his go.

Docs for agents in plain text

The site SHALL publish, next to the Reference, api.md (every exported name with its signatures, doc comment, gt's and Great Tables' names and an example of the specs with its output, after an index of one line per name) and api.json (the same as data), built from the source with the pages. llms.txt SHALL list these plain-text docs first, with the feature map's gt.json and the specs' Markdown at the release's tag, and the README SHALL say how to install tabelline.

Scenario: An agent looks up a gt name
  • WHEN an agent greps api.md for fmt_number
  • THEN it finds the entry of fmtNumber, with its signature and an example that ran

Skills for agents, tested

The repository SHALL hold, in skills/, the skills for agents that use tabelline: tabelline (what the docs do not say: how to work, the traps agents met, recipes for hard tables) and table-building (true of any table with any library: what to decide first, in what order to build, and to look at the page before saying it is done), installable as a Claude Code plugin from the repository. A skill SHALL NOT copy the API or the book. Every Nim example of a skill SHALL run against the code and print the text shown after it (tools/skillexamples.nim, in CI). Every rule of a skill SHALL come from an agent's run, with an eval case in the skill's evals/ that tools/skillevals.nim grades.

Scenario: A skill's example goes out of date
  • WHEN a change to tabelline alters what an example of skills/tabelline/SKILL.md prints
  • THEN nim r tools/skillexamples.nim fails in CI until the skill is updated in the same PR
Scenario: An agent's table is graded
  • WHEN an agent has ported a table in a folder and nim r tools/skillevals.nim skills/tabelline/evals/port-gt-extras <folder> runs
  • THEN each grader of the case is printed as passed or failed, and the exit code is 1 if one failed

source: openspec/specs/way-of-working/spec.md

Open changes

None at the moment: see the backlog for what may come next.