Nometabelline
MateriaReference
Classekept up to date

Reference · rebuilt on every push

Every name tabelline exports

404 names in 16 modules: the signature of each, its doc comment, and an example that ran when this page was built.

This page is made from the source. Each entry says what kind of name it is (a proc, a template, a macro, a type), shows its signatures (one for each overload), its doc comment, and, when one of the specs' examples uses it, that example and the table it makes. A name that gt or Great Tables has too links to their reference pages; a name that is tabelline's own links to Not from gt. 291 of 404 names have a doc comment so far; the others say so.

Start from the Guide to learn tabelline: this page is for looking a name up.

Links to a name, for people and agents

Every name has a link of its own, the # beside it: the module and the name, such as api/#verbs-tabHeader, which stays the same when the API grows. The plain name works too, api/#tabHeader, for the first name of that spelling on the page. Modules and sections are linked by their headings, such as api/#formats.

Modules

What each module is for, what it exports, and what it imports: from tabelline, and from Nim's standard library. Only two need a package from outside: tabelline/nimib needs nimib, and tabelline/nanuq needs nanuq.

The modules
each after the modules it imports, as on this page
tabelline/colors
what it isColours for dataColor: hex parsing, palettes, linear interpolation and the text colour that reads best on a fill (WCAG relative luminance).
exports13 names: 1 type, 11 funcs, 1 const
exports again—
imports—
imported bytabelline, core, render_html, verbs
from Nimstrutils, math, tables
tabelline/core
what it isThe data model of tabelline.
exports109 names: 37 types, 59 funcs, 3 templates, 5 procs, 3 converters, 2 consts
exports againstd/options
importscolors
imported bytabelline, build, datasets, extract, formats, nanoplots, pictures, render_html, render_text, units, verbs
from Nimstrutils, math, options, sequtils, tables
tabelline/localize
what it isLocales: the conventions of a language and region, from Unicode CLDR (locales.nim, currencies.nim, written by tools/cldr.nim).
exports13 names: 1 type, 2 consts, 10 funcs
exports again—
importslocales (data), currencies (data)
imported byformats
from Nimstrutils, algorithm, times
tabelline/formats
what it isFormatting values: plain functions that turn numbers into text (formatNumber, formatPercent, ..., usable on their own, like Great Tables' vals), and the fmt* verbs that attach them to columns and rows of a table.
exports72 names: 1 type, 33 funcs, 3 consts, 35 procs
exports againlocalize
importscore, countries (data), localize
imported bytabelline, build, nanoplots, pictures, render_html, units, verbs
from Nimstrutils, math, times, sequtils, strformat, unicode
tabelline/units
what it isUnits and chemical formulas written as text, in gt's units notation: "kg/m^3", "m s^-2", "m /s" (a unit after a solidus is a power −1), "T_eff", ":mu:g", "degC", "%H2O%".
exports6 names: 3 funcs, 3 procs
exports again—
importscore, formats
imported bytabelline, build
from Nimstrutils, sequtils, unicode
tabelline/verbs
what it isThe verbs that build a table spec, named after gt and Great Tables in camelCase: tab* add parts (header, spanners, notes, styles, options), cols* change columns, dataColor and opt* change the looks.
exports99 names: 66 procs, 29 funcs, 2 consts, 1 macro, 1 type
exports again—
importscore, colors, formats
imported bytabelline, nanoplots, render_html
from Nimmacros, strutils, sequtils, tables, math, algorithm
tabelline/build
what it isBuilding a table for display: the step every renderer shares, after gt's build_data().
exports30 names: 4 types, 15 funcs, 11 procs
exports again—
importscore, formats, units
imported bytabelline, extract, render_html, render_text
from Nimtables, sequtils, strutils, algorithm, unicode
tabelline/render_html
what it isRendering to HTML: one <div> holding a <table>, styled by tabellaCss, one stylesheet for every table, with the options the table changes as CSS variables on the <div>.
exports6 names: 1 const, 2 lets, 3 procs
exports again—
importscore, formats, build, colors, verbs
imported bytabelline
from Nimstrutils, strformat, sequtils, tables, hashes
tabelline/render_text
what it isRendering to plain text (box drawing, for terminals and echo) and to Markdown (a GitHub pipe table, for nimib's Markdown backend and READMEs).
exports3 names: 3 procs
exports again—
importscore, build
imported bytabelline
from Nimstrutils, unicode, sequtils, math
tabelline/extract
what it isThe built table as data: what a reader sees, cell by cell, as gt's extract_body(), extract_cells() and extract_summary() give it.
exports3 names: 3 procs
exports again—
importscore, build
imported bytabelline
from Nimsequtils, strutils
tabelline/pictures
what it isPictures in cells: icons and images, drawn without loading anything remote.
exports10 names: 1 type, 9 procs
exports again—
importscore, formats
imported bytabelline
from Nimstrutils, tables, base64, os, math
tabelline/nanoplots
what it isNanoplots: tiny plots in cells, as inline SVG, after Great Tables' fmt_nanoplot() and gt's cols_nanoplot() (ported from Great Tables' _utils_nanoplots.py, MIT, licenses/great-tables-MIT.txt).
exports14 names: 1 type, 4 funcs, 7 procs, 2 consts
exports again—
importscore, formats, verbs
imported bytabelline
from Nimstrutils, math, algorithm, sequtils, hashes, times, unicode
tabelline
what it isGreat tables for Nim.
exports3 names: 3 macros
exports againcore, formats, units, colors, verbs, build, render_html, render_text, extract, pictures, nanoplots
importscore, formats, units, colors, verbs, build, render_html, render_text, extract, pictures, nanoplots
imported bynimib
from Nimmacros, strutils
tabelline/datasets
what it isSmall datasets for examples and tests, built into the module (no files to find at run time).
exports13 names: 4 consts, 9 procs
exports again—
importscore
imported by—
from Nim—
tabelline/nimib
what it istabelline in nimib notebooks: nbTable t shows a table as a block of the page.
exports8 names: 1 type, 4 procs, 1 method, 1 func, 1 macro
exports again—
importstabelline
imported by—
from Nimjson, macros, pkg/nimib
tabelline/nanuq
what it istabelline/nanuq: a table straight from a nanuq <https://github.com/pietroppeter/nanuq>_ DataFrame (Polars for Nim).
exports2 names: 2 procs
exports again—
imports—
imported by—
from Nimoptions, pkg/nanuq as nq
From Nim: modules of the standard library, and pkg/nimib, the one package from outside. (data): a module of CLDR tables, not documented here.

Reading a signature

A signature here is what Nim sees, and it is not always what you write. tabelline has some sugar, and it changes how a signature reads:

Beside types, a signature uses a few words of Nim. The one you meet most is sink, on the table every verb takes. It tells Nim that the proc takes ownership of the value: when the caller does not use it again, as in a chain or a tabella body, Nim moves it instead of copying it; when the caller does, Nim copies it. The code means the same either way, and you never write sink yourself.

sink and lent are Nim's move semantics annotations (the manual speaks of sink parameters, and of lent as a borrowed result). They come from the same idea as Rust's ownership and borrowing, but as an opt-in: Rust's borrow checker rejects code that uses a value after giving it away, while Nim, which manages memory for you, takes these words as permission to move a value instead of copying it. Where it cannot move, it copies, so the code compiles either way: the compiler gets to optimise, and you never fight it. var marks a parameter the proc may change; openArray, varargs and static are something else, types made for parameters. The guide has a note on sink too.

The words of Nim in a signature
what it meanson this page
sinktakes ownership of the argument: moved when the caller is done with it, copied otherwise; you write nothing101 names, such as tabHeader
lentreturns a value borrowed from the argument, without a copy, which you cannot change1 name: []
varcan change the argument, which must be a variable2 names, such as table
openArraytakes an array or a seq34 names, such as interpolate
varargstakes any number of arguments; in a macro, varargs[untyped] takes code19 names, such as tabella
statica value known when compiling, such as the length of an array2 names, such as toColSel

Colours

tabelline/colors · src/tabelline/colors.nim

Colours for dataColor: hex parsing, palettes, linear interpolation and the text colour that reads best on a fill (WCAG relative luminance).

namekind
Rgbtype
isCssColorNamefunc
rColorfunc
cssColorfunc
parseColorfunc
toHexfunc
mixfunc
interpolatefunc
luminancefunc
contrastfunc
idealTextColorfunc
palettesconst
palettefunc
×3: three overloads. A name opens its entry below.
13 names, 7 with a doc comment

Rgbtype#

Rgb = tuple[r, g, b: float]

No doc comment yet.

isCssColorNamefunc#

func isCssColorName(name: string): bool

One of the 148 colour names of CSS.

rColorfunc#

func rColor(name: string): string

The hex value of one of R's colour names beyond CSS's, which gt and Great Tables take (sienna4 is "#8B4726", grey50 "#7F7F7F"); "" for any other text.

cssColorfunc#

func cssColor(c: string): string

A colour as CSS reads it: one of R's names becomes its hex value, anything else (a hex value, a CSS name, var(--x)) is left as it is.

parseColorfunc#

func parseColor(c: string): Rgb

#rgb, #rrggbb, any of the 148 CSS colour names (darkgreen, rebeccapurple) or of R's (sienna4, grey50).

toHexfunc#

func toHex(c: Rgb): string

No doc comment yet.

mixfunc#

func mix(a, b: Rgb; t: float): Rgb

No doc comment yet.

interpolatefunc#

func interpolate(
    palette: openArray[string],
    t: float
): string

The colour at t in 0..1 along a palette of evenly spaced stops.

luminancefunc#

func luminance(c: Rgb): float

No doc comment yet.

contrastfunc#

func contrast(a, b: Rgb): float

No doc comment yet.

idealTextColorfunc#

func idealTextColor(
    fill: string,
    dark = "#1a1a1a",
    light = "#FFFFFF"
): string

Dark or light text, whichever contrasts more with fill.

palettesconst#

palettes = (data: [(0, "", []), (0, "", []), (0, "", []), (0, "", []),
                   (0, "", []), (0, "", []), (0, "", []), (0, "", []), (
    8053033860643646504, "rdylgn",
    ["#D73027", "#FC8D59", "#FEE08B", "#D9EF8B", "#91CF60", "#1A9850"]),
                   (0, "", []), (0, "", []), (0, "", []), (-8928340921496638260,
    "quaderno", ["#FFFFFF", "#DCEBFA", "#A9CCF0", "#6FA3DB", "#3C6FB6"]), (
    1723379612904976973, "rdbu",
    ["#2166AC", "#92C5DE", "#F7F7F7", "#F4A582", "#B2182B"]), (0, "", []),
                   (0, "", []), (134456633375568208, "greens", ["#F7FCF5",
    "#C7E9C0", "#74C476", "#238B45", "#00441B"]), (-6731458568632991919, "reds",
    ["#FFF5F0", "#FCBBA1", "#FB6A4A", "#CB181D", "#67000D"]), (0, "", []),
                   (0, "", []), (0, "", []), (0, "", []), (0, "", []), (
    -5639196860620556009, "great-tables", ["#000000", "#DF536B", "#61D04F",
    "#2297E6", "#28E2E5", "#CD0BBC", "#F5C710", "#9E9E9E"]), (0, "", []),
                   (0, "", []), (2460717392810645242, "blues", ["#F7FBFF",
    "#C6DBEF", "#6BAED6", "#2171B5", "#08306B"]), (5823032332022599610,
    "matite", ["#E63946", "#F4A261", "#E9C46A", "#2A9D8F", "#457B9D", "#8E7DBE"]),
                   (0, "", []), (1203107158067285821, "viridis", ["#440154",
    "#3B528B", "#21908C", "#5DC963", "#FDE725"]), (0, "", []), (
    2396891131824504447, "pastelli", ["#FFF3B0", "#FFD6A5", "#FFADAD",
                                      "#E4C1F9", "#A0C4FF", "#9BF6FF", "#CAFFBF"])],
            counter: 10)

No doc comment yet.

palettefunc#

func palette(name: string): seq[string]

A named palette (see palettes), or a comma-separated list of colours.

Data, text and selectors

tabelline/core · src/tabelline/core.nim

The data model of tabelline.

namekind
Values
ValueKindtype
Valuetype
nullfunc
toValuefunc ×12
listfunc
recordfunc
isNullfunc
isNumberfunc
isListfunc
isRecordfunc
toFloatfunc
lenfunc
[]func ×5
containsfunc
.template ×2
$func
==func ×4
<func ×4
<=func ×2
cellNamesfunc
Data
Columntype
TableDatatype
nrowsfunc
ncolsfunc
namesfunc
colIndexfunc
hasColumnfunc
kindOffunc
isNumericfunc
addColumnproc
toTableDataproc ×2
toValuesfunc
parseCsvproc
readCsvproc
Rowtype
Text
TextKindtype
Texttype
mdfunc
htmlfunc
toTextconverter
toTextfunc
isEmptyfunc
Selectors
ColSelKindtype
ColSeltype
toColSelconverter ×3
colsfunc
everythingfunc
startsWithfunc
endsWithfunc
containingfunc
numericfunc
textualfunc
positionsfunc ×2
+func
-func
&func ×2
ofKindfunc
matchesfunc
namedtemplate
resolvefunc
RowSelKindtype
RowSeltype
allRowsfunc
toRowSelconverter ×6
wheretemplate
resolveproc
Styles
CellStyletype
StyleNstype
LocNstype
styleconst
locconst
fillfunc
textfunc
Sidetype
bordersfunc
cssfunc
toCssfunc
Spec
Aligntype
ColRoletype
ColInfotype
Spannertype
RenderContexttype
FormatFntype
FormatRuletype
LocKindtype
Targettype
Loctype
StyleRuletype
Footnotetype
TransformRuletype
Aggregatetype
AggNstype
SummaryRuletype
MergeKindtype
MergeRuletype
FootnoteMarkstype
TabOptionstype
Tabellatype
colInfofunc
visibleDatafunc
hasSummariesfunc
hasStubfunc
hasRowNamesfunc
hasGroupsfunc
stubColumnsfunc
groupAsColumnfunc
stubWidthfunc
PatternReftype
patternRefsfunc
×3: three overloads. A name opens its entry below.
109 names, 58 with a doc comment

Two layers, like gt and Great Tables:

The data is a ref, so copying a Tabella (as every verb does, or moves with sink) copies only the spec, never the data.

Values

ValueKindtype#

ValueKind = enum
  vkNull, vkBool, vkInt, vkFloat, vkString, vkList, vkRecord

No doc comment yet.

Valuetype#

Value = object
  case kind*: ValueKind
  of vkNull:
    nil
  of vkBool:
    b*: bool
  of vkInt:
    i*: int
  of vkFloat:
    f*: float
  of vkString:
    s*: string
  of vkList:
    items*: seq[Value]
  of vkRecord:
    fields*: seq[(string, Value)]

One cell of the table data. vkNull is a missing value. A cell can hold more than one value: a list (@[1, 4, 2]) or a record ((x: 1, y: 2)), with fields in order.

nullfunc#

func null(): Value

No doc comment yet.

toValuefunc#

func toValue(v: Value): Value
func toValue(x: bool): Value
func toValue(x: SomeInteger): Value
func toValue(x: SomeFloat): Value
func toValue(x: string): Value
func toValue(x: char): Value
func toValue(x: enum): Value
func toValue[T](x: Option[T]): Value
func toValue(x: typeof(nil)): Value
func toValue[T](x: seq[T]): Value
func toValue[I, T](
    x: array[I, T]
): Value
func toValue[T: object | tuple](
    x: T
): Value

A seq is a list: toValue(@[1, 4, 2]).

an example, from the specs
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

listfunc#

func list(
    items: varargs[Value, toValue]
): Value

A list of values in one cell: list(1, 4, 2).

recordfunc#

func record(
    fields: openArray[(string, Value)]
): Value

A record in one cell, its fields in order: record({"x": toValue(1), "y": toValue(2)}).

isNullfunc#

func isNull(v: Value): bool

No doc comment yet.

isNumberfunc#

func isNumber(v: Value): bool

No doc comment yet.

isListfunc#

func isList(v: Value): bool

No doc comment yet.

isRecordfunc#

func isRecord(v: Value): bool

No doc comment yet.

toFloatfunc#

func toFloat(v: Value): float

The value as a float; NaN for anything else that is not a number. Raises ValueError for a list or a record: they hold several values.

an example, from the specs
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

lenfunc#

func len(v: Value): int

The number of items of a list or fields of a record; 0 for any other value.

[]func#

func `[]`(v: Value; i: int): Value
func `[]`(v: Value; name: string): Value
func `[]`(
    d: TableData,
    name: string
): lent Column
func `[]`(
    d: TableData,
    name: string,
    row: int
): Value
func `[]`(r: Row; name: string): Value

An item of a list: v[0]. Raises IndexDefect beyond its end, ValueError for a value that is not a list.

containsfunc#

func contains(
    v: Value,
    name: string
): bool

Whether a record has a field name: "x" in v.

an example, from the specs
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

.template#

template `.`(
    v: Value,
    field: untyped
): Value
template `.`(
    r: Row,
    field: untyped
): Value

A field of a record by its name: v.x is v["x"]. A name that Value already has (kind, i, f, s, b, items, fields, len, ...) is that, not the field: write v["kind"].

$func#

func `$`(v: Value): string

No doc comment yet.

==func#

func `==`(a, b: Value): bool
func `==`(a: Value; b: SomeNumber): bool
func `==`(a: Value; b: string): bool
func `==`(a: Value; b: bool): bool

No doc comment yet.

<func#

func `<`(a: Value; b: SomeNumber): bool
func `<`(a: SomeNumber; b: Value): bool
func `<`(a: Value; b: string): bool
func `<`(a, b: Value): bool

Numbers and texts in order; lists item by item, as words are; anything else is not ordered.

<=func#

func `<=`(a: Value; b: SomeNumber): bool
func `<=`(a: SomeNumber; b: Value): bool

No doc comment yet.

cellNamesfunc#

func cellNames(v: Value): seq[string]

The names in a cell, for verbs that take several (icons, images, flags): the items of a list, or the parts of a text separated by commas.

Data

Columntype#

Column = object
  name*: string
  values*: seq[Value]

No doc comment yet.

TableDatatype#

TableData = ref object
  columns*: seq[Column]

Named columns of equal length. Built once (from rows, columns or CSV) and only read.

nrowsfunc#

func nrows(d: TableData): int

No doc comment yet.

an example, from the specs
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

ncolsfunc#

func ncols(d: TableData): int

No doc comment yet.

namesfunc#

func names(d: TableData): seq[string]

No doc comment yet.

an example, from the specs
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

colIndexfunc#

func colIndex(
    d: TableData,
    name: string
): int

No doc comment yet.

hasColumnfunc#

func hasColumn(
    d: TableData,
    name: string
): bool

No doc comment yet.

kindOffunc#

func kindOf(c: Column): ValueKind

The kind of a column: the kind of its non-missing values (vkFloat when ints and floats mix).

isNumericfunc#

func isNumeric(c: Column): bool

No doc comment yet.

addColumnproc#

proc addColumn(
    d: TableData,
    name: string,
    values: seq[Value]
)

No doc comment yet.

toTableDataproc#

proc toTableData[T: object | tuple](
    rows: openArray[T]
): TableData
proc toTableData(
    columns: openArray[(string, seq[Value])]
): TableData

Rows as Nim objects or named tuples, one field per column: toTableData(@[(name: "Mercury", moons: 0), (name: "Earth", moons: 1)]).

toValuesfunc#

func toValues[T](
    xs: openArray[T]
): seq[Value]

No doc comment yet.

parseCsvproc#

proc parseCsv(
    text: string,
    sep = ',',
    comment = ""
): TableData

A CSV text with a header line. Each value is read as an int, a float, a bool, a missing value (empty, NA) or else a string; a column mixing ints and floats is a float column. A column with a number written with a zero in front ("0400", a code) stays text, as written. With a comment such as "#", a line that starts with it (after any spaces) is skipped, so a file can say where its data comes from.

an example, from the specs
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

readCsvproc#

proc readCsv(
    path: string,
    sep = ',',
    comment = ""
): TableData

parseCsv of a file.

Rowtype#

Row = object
  data*: TableData
  index*: int

One row of the data, as seen by a row predicate (where): it.mass, it.index.

Text

TextKindtype#

TextKind = enum
  tkPlain, tkMarkdown, tkHtml

No doc comment yet.

Texttype#

Text = object
  kind*: TextKind
  s*: string

A label or note: plain text (escaped when rendered), Markdown, or raw HTML.

mdfunc#

func md(s: string): Text

Markdown text, for labels and notes: md("**Mass** (10^24^ kg)").

htmlfunc#

func html(s: string): Text

Raw HTML text, used as is.

an example, from the specs
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

toTextconverter#

converter toText(s: string): Text

No doc comment yet.

toTextfunc#

func toText(t: Text): Text

A Text is already one (so a colsLabel block can mix "Mass" and md("...")).

isEmptyfunc#

func isEmpty(t: Text): bool

No doc comment yet.

Selectors

ColSelKindtype#

ColSelKind = enum
  csNames, csAll, csStartsWith, csEndsWith, csContains, csNumeric, csTextual,
  csPositions, csUnion, csMinus, csBoth, csKinds, csMatches

No doc comment yet.

ColSeltype#

ColSel = object
  case kind*: ColSelKind
  of csNames:
    names*: seq[string]
  of csStartsWith, csEndsWith, csContains:
    parts*: seq[string]
  of csPositions:
    positions*: seq[int]
  of csUnion, csMinus, csBoth:
    sels*: seq[ColSel]
  of csKinds:
    kinds*: set[ValueKind]
  of csMatches:
    test*: proc (name: string): bool
  else:
    nil

Which columns a verb applies to. A string or an array of strings converts to one, and everything(), startsWith(...), endsWith(...), containing(...), numeric(), textual(), positions(...), ofKind(...) (by the kind of the values), matches(...) and named(...) (any rule on the name) select by rule; a + b is the columns of either (in the order of the data), a - b those of a that are not in b, a & b those of both. Resolved against the data when the verb is called.

toColSelconverter#

converter toColSel(name: string): ColSel
converter toColSel[N: static int](
    names: array[N, string]
): ColSel
converter toColSel(
    names: seq[string]
): ColSel

No doc comment yet.

colsfunc#

func cols(
    names: varargs[string]
): ColSel

No doc comment yet.

an example, from the specs
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

everythingfunc#

func everything(): ColSel

No doc comment yet.

an example, from the specs
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

startsWithfunc#

func startsWith(
    prefixes: varargs[string]
): ColSel

The columns whose name starts with any of prefixes: startsWith(["pop_", "pct_"]) (in brackets: startsWith(a, b) with two texts is strutils.startsWith).

endsWithfunc#

func endsWith(
    suffixes: varargs[string]
): ColSel

No doc comment yet.

containingfunc#

func containing(
    parts: varargs[string]
): ColSel

No doc comment yet.

numericfunc#

func numeric(): ColSel

No doc comment yet.

textualfunc#

func textual(): ColSel

No doc comment yet.

positionsfunc#

func positions(ix: varargs[int]): ColSel
func positions(
    s: HSlice[int, int]
): ColSel

Columns by their place in the data, from 0, as rows are: positions(0, 2); a negative place counts from the end (-1 is the last column).

+func#

func `+`(a, b: ColSel): ColSel

The columns of a or b: startsWith("pop") + "year".

-func#

func `-`(a, b: ColSel): ColSel

The columns of a that are not in b: numeric() - "year".

&func#

func `&`(a, b: ColSel): ColSel
func `&`(a, b: CellStyle): CellStyle

The columns of both a and b: startsWith("pop") & numeric().

ofKindfunc#

func ofKind(
    kinds: varargs[ValueKind]
): ColSel

The columns whose values are of these kinds (a missing value counts as any kind), as gt's where(is.logical) and Great Tables' cs.by_dtype(pl.Boolean): ofKind(vkBool).

matchesfunc#

func matches(
    test: proc (name: string): bool
): ColSel

The columns whose name passes test, any proc of a string, as gt's matches() (which takes a regular expression): matches(proc (n: string): bool = n.len == 4).

namedtemplate#

template named(cond: untyped): ColSel

The columns whose name, it, makes cond true: named(it.len == 4 and it[0] == 'y').

resolvefunc#

func resolve(
    sel: ColSel,
    d: TableData
): seq[string]

No doc comment yet.

RowSelKindtype#

RowSelKind = enum
  rsAll, rsIndices, rsWhere

No doc comment yet.

RowSeltype#

RowSel = object
  case kind*: RowSelKind
  of rsIndices:
    indices*: seq[int]
  of rsWhere:
    pred*: proc (r: Row): bool
  of rsAll:
    nil

Which rows a verb applies to: all of them (the default), indices ([0, 2], 0..3, 0-based; -1 or ^1 is the last row) or a predicate (where(it.mass > 1)).

allRowsfunc#

func allRows(): RowSel

No doc comment yet.

toRowSelconverter#

converter toRowSel(i: int): RowSel
converter toRowSel(
    i: BackwardsIndex
): RowSel
converter toRowSel[N: static int](
    ix: array[N, int]
): RowSel
converter toRowSel(ix: seq[int]): RowSel
converter toRowSel(
    s: HSlice[int, int]
): RowSel
converter toRowSel[T: Ordinal](
    s: set[T]
): RowSel

^1 is the last row, as -1 is.

wheretemplate#

template where(cond: untyped): RowSel

Rows where cond holds, with it the row: where(it["type"] == "Gas giant").

an example, from the specs
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

resolveproc#

proc resolve(
    sel: RowSel,
    d: TableData
): seq[int]

No doc comment yet.

Styles

CellStyletype#

CellStyle = object
  css*: seq[(string, string)]

CSS declarations for some cells. Build with style.fill, style.text, style.borders and join with &: style.fill("#fff3b0") & style.text(weight = "bold").

StyleNstype#

StyleNs = object

A background colour (a hex value, a CSS or R colour name), with alpha from 0 (clear) to 1, as gt's cell_fill(color, alpha).

LocNstype#

LocNs = object

A background colour (a hex value, a CSS or R colour name), with alpha from 0 (clear) to 1, as gt's cell_fill(color, alpha).

styleconst#

style = ()

No doc comment yet.

locconst#

loc = ()

No doc comment yet.

fillfunc#

func fill(
    _: StyleNs,
    color: string,
    alpha = 1.0
): CellStyle

A background colour (a hex value, a CSS or R colour name), with alpha from 0 (clear) to 1, as gt's cell_fill(color, alpha).

an example, from the specs
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

textfunc#

func text(
    _: StyleNs,
    color = "",
    font = "",
    size = "",
    align = "",
    vAlign = "",
    weight = "",
    style = "",
    decorate = "",
    transform = "",
    whitespace = "",
    indent = ""
): CellStyle

The text of the cells: vAlign is "top", "middle" or "bottom" (gt's v_align), indent a CSS length, "1.5em" (gt's indent).

an example, from the specs
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

Sidetype#

Side = enum
  sTop = "top", sRight = "right", sBottom = "bottom", sLeft = "left"

No doc comment yet.

bordersfunc#

func borders(
    _: StyleNs,
    sides: set[Side] = {sTop, sRight, sBottom, sLeft},
    color = "#000000",
    style = "solid",
    weight = "1px"
): CellStyle

No doc comment yet.

cssfunc#

func css(
    _: StyleNs,
    declarations: string
): CellStyle

Any CSS, as declarations: style.css("letter-spacing: 0.1em; font-variant: small-caps").

toCssfunc#

func toCss(s: CellStyle): string

No doc comment yet.

Spec

Aligntype#

Align = enum
  alAuto = "auto", alLeft = "left", alCenter = "center", alRight = "right"

No doc comment yet.

ColRoletype#

ColRole = enum
  crData, crStub, crGroup

No doc comment yet.

ColInfotype#

ColInfo = object
  name*: string
  label*: Text
  units*: string             ## units in gt's notation, shown with the label (`colsUnits`)
  unitsPattern*: string      ## how: `{1}` is the label, `{2}` the units
  align*: Align
  width*: string
  hidden*: bool
  role*: ColRole

The boxhead entry of one column: how its label and cells are shown.

Spannertype#

Spanner = object
  label*: Text
  columns*: seq[string]
  level*: int

A label over a run of columns; level 1 sits right above the column labels.

RenderContexttype#

RenderContext = enum
  rcHtml, rcText

No doc comment yet.

FormatFntype#

FormatFn = proc (v: Value; ctx: RenderContext): string

Turns one value into its shown text. In rcHtml the result is HTML (escape what you add).

FormatRuletype#

FormatRule = object
  columns*: seq[string]
  rows*: seq[int]            ## empty: every row
  fn*: FormatFn
  nullsToo*: bool            ## also called on missing values (substitutions are)
  applies*: proc (v: Value): bool ## a substitution: the values it replaces, even with ""
  wholeValue*: bool          ## takes a list or record whole (pictures); else item by item

No doc comment yet.

LocKindtype#

LocKind = enum
  lkTitle, lkSubtitle, lkStubhead, lkSpanners, lkColumnLabels, lkStub,
  lkRowGroups, lkBody, lkFootnotes, lkSourceNotes, lkHeader, lkColumnHeader,
  lkFooter, lkSummary, lkSummaryStub, lkGrandSummary, lkGrandSummaryStub

No doc comment yet.

Targettype#

Target = object
  kind*: LocKind
  cells*: seq[(int, string)]
  names*: seq[string]
  labels*: seq[string]
  columns*: seq[string]

A resolved location: cells for the body and the stub (row, column), names for column labels, spanners and row groups. For summary rows, names are the groups, labels the labels of the summary rows (empty: all of them) and columns the columns.

Loctype#

Loc = object
  kind*: LocKind
  cols*: ColSel
  rows*: RowSel
  names*: seq[string]
  labels*: seq[string]       ## summary rows, by label; stub rows, by their label
  mask*: proc (v: Value; col: Column): bool ## `loc.body(mask = ...)`: the cells that pass

An unresolved location, from the loc namespace: loc.body(cols = "mass", rows = [0]).

StyleRuletype#

StyleRule = object
  target*: Target
  style*: CellStyle

No doc comment yet.

Footnotetype#

Footnote = object
  note*: Text
  target*: Target

No doc comment yet.

TransformRuletype#

TransformRule = object
  target*: Target
  fn*: proc (s: string): string

A proc over the shown text of the cells at a location (textTransform).

Aggregatetype#

Aggregate = object
  name*: string              ## "sum", "count", ... ("" for a proc of your own)
  fn*: proc (values: seq[Value]): Value

How a summary row sums up a column: a proc from the column's non-missing values (of the group, or of the whole table) to one value. Built in: agg.sum, agg.mean, agg.median, agg.min, agg.max, agg.count, agg.std; any proc with aggregate(myProc).

AggNstype#

AggNs = object

Summary rows added by summaryRows (for some groups) or grandSummaryRows (grand).

SummaryRuletype#

SummaryRule = object
  grand*: bool
  groups*: seq[string]       ## the groups summarised (empty: all of them)
  columns*: seq[string]      ## the columns summarised; the others show `missingText`
  fns*: seq[(string, Aggregate)] ## (label, aggregate): one row each
  shown*: Table[string, string] ## label -> the text shown in the stub, when `textTransform` changed it
  top*: bool                 ## above the group (or the table) instead of below
  fmt*: FormatFn             ## nil: the column's format
  missingText*: string

Summary rows added by summaryRows (for some groups) or grandSummaryRows (grand).

MergeKindtype#

MergeKind = enum
  mkPattern, mkUncert, mkRange, mkNPct

No doc comment yet.

MergeRuletype#

MergeRule = object
  kind*: MergeKind
  columns*: seq[string]      ## the first is where the merged text goes
  rows*: seq[int]            ## empty: every row
  pattern*: string           ## `{1}`, `{2}`, ... with `<<...>>` for a part dropped when a value is missing

Columns shown together in the first one (colsMerge and its cousins), at render time.

FootnoteMarkstype#

FootnoteMarks = enum
  fmNumbers, fmLetters, fmCapitals, fmStandard, fmExtended

No doc comment yet.

TabOptionstype#

TabOptions = object
  tableWidth* = "auto"
  tableMarginLeft* = "auto"
  tableMarginRight* = "auto"
  tableFontNames* = "system-ui, -apple-system, \'Segoe UI\', Roboto, Helvetica, Arial, sans-serif"
  tableFontSize* = "16px"
  tableFontColor* = "#333333"
  tableBackgroundColor* = "#FFFFFF"
  tableBorderTopColor* = "#A8A8A8"
  tableBorderTopWidth* = "2px"
  tableBorderBottomColor* = "#A8A8A8"
  tableBorderBottomWidth* = "2px"
  headingAlign* = "center"
  headingBackgroundColor* = ""
  headingTitleFontSize* = "125%"
  headingTitleFontWeight* = "initial"
  headingSubtitleFontSize* = "85%"
  headingSubtitleFontWeight* = "normal"
  headingBorderBottomColor* = "#D3D3D3"
  columnLabelsBackgroundColor* = ""
  columnLabelsFontSize* = "100%"
  columnLabelsFontWeight* = "normal"
  columnLabelsTextTransform* = "inherit"
  columnLabelsBorderBottomColor* = "#D3D3D3"
  columnLabelsBorderBottomWidth* = "2px"
  rowGroupBackgroundColor* = ""
  rowGroupFontWeight* = "initial"
  rowGroupBorderColor* = "#D3D3D3"
  stubBackgroundColor* = ""
  stubFontWeight* = "initial"
  stubSticky* = false        ## the stub stays in view when a wide table scrolls sideways
  headingPadding* = "4px"
  headingPaddingHorizontal* = "5px"
  columnLabelsPadding* = "5px"
  columnLabelsPaddingHorizontal* = "5px"
  dataRowPadding* = "8px"
  dataRowPaddingHorizontal* = "5px"
  tableBorderTopStyle* = "solid"
  tableBorderBottomStyle* = "solid"
  tableBorderLeftStyle* = "none"
  tableBorderLeftWidth* = "2px"
  tableBorderLeftColor* = "#D3D3D3"
  tableBorderRightStyle* = "none"
  tableBorderRightWidth* = "2px"
  tableBorderRightColor* = "#D3D3D3"
  tableBodyVlinesColor* = "" ## "" for no vertical lines
  tableBodyHlinesColor* = "#D3D3D3"
  rowStriping* = false
  rowStripingBackgroundColor* = "rgba(128,128,128,0.05)"
  summaryRowBackgroundColor* = "" ## "" for the table's background
  summaryRowTextTransform* = "inherit"
  summaryRowPadding* = "8px"
  summaryRowPaddingHorizontal* = "5px"
  summaryRowBorderStyle* = "solid"
  summaryRowBorderWidth* = "2px"
  summaryRowBorderColor* = "#D3D3D3"
  grandSummaryRowBackgroundColor* = ""
  grandSummaryRowTextTransform* = "inherit"
  grandSummaryRowPadding* = "8px"
  grandSummaryRowPaddingHorizontal* = "5px"
  grandSummaryRowBorderStyle* = "double"
  grandSummaryRowBorderWidth* = "6px"
  grandSummaryRowBorderColor* = "#D3D3D3"
  footnotesFontSize* = "90%"
  footnotesMarks* = fmNumbers
  footnotesMarksCustom*: seq[string] ## marks of your own; when set, `footnotesMarks` is ignored
  footnotesSpecRef* = "^"    ## how marks look in the table: ^ raised, i italic, b bold, ( or [ around
  footnotesSpecFtr* = "^"    ## the same, in the footer
  footnotesOrder* = "marks_first" ## or "marks_last", "preserve_order"
  sourceNotesFontSize* = "90%"
  containerOverflowX* = "auto"
  containerOverflowY* = "auto"
  containerWidth* = "auto"
  containerHeight* = "auto"
  containerPaddingX* = "0px"
  containerPaddingY* = "0px"
  tableLayout* = "auto"      ## or "fixed", as CSS's table-layout
  tableFontWeight* = "normal"
  tableFontStyle* = "normal"
  headingBorderBottomStyle* = "solid"
  headingBorderBottomWidth* = "2px"
  headingBorderLrStyle* = "none"
  headingBorderLrWidth* = "1px"
  headingBorderLrColor* = "#D3D3D3"
  columnLabelsBorderTopStyle* = "none"
  columnLabelsBorderTopWidth* = "2px"
  columnLabelsBorderTopColor* = "#D3D3D3"
  columnLabelsBorderBottomStyle* = "solid"
  columnLabelsBorderLrStyle* = "none"
  columnLabelsBorderLrWidth* = "1px"
  columnLabelsBorderLrColor* = "#D3D3D3"
  columnLabelsVlinesStyle* = "none"
  columnLabelsVlinesWidth* = "1px"
  columnLabelsVlinesColor* = "#D3D3D3"
  rowGroupFontSize* = "100%"
  rowGroupTextTransform* = "inherit"
  rowGroupPadding* = "8px"
  rowGroupPaddingHorizontal* = "5px"
  rowGroupBorderTopStyle* = "solid"
  rowGroupBorderTopWidth* = "2px"
  rowGroupBorderTopColor* = "" ## "" for `rowGroupBorderColor`
  rowGroupBorderBottomStyle* = "solid"
  rowGroupBorderBottomWidth* = "2px"
  rowGroupBorderBottomColor* = "" ## "" for `rowGroupBorderColor`
  rowGroupBorderLeftStyle* = "none"
  rowGroupBorderLeftWidth* = "1px"
  rowGroupBorderLeftColor* = "#D3D3D3"
  rowGroupBorderRightStyle* = "none"
  rowGroupBorderRightWidth* = "1px"
  rowGroupBorderRightColor* = "#D3D3D3"
  tableBodyHlinesStyle* = "solid"
  tableBodyHlinesWidth* = "1px"
  tableBodyVlinesStyle* = "solid"
  tableBodyVlinesWidth* = "1px"
  tableBodyBorderTopStyle* = "none"
  tableBodyBorderTopWidth* = "2px"
  tableBodyBorderTopColor* = "#D3D3D3"
  tableBodyBorderBottomStyle* = "none"
  tableBodyBorderBottomWidth* = "2px"
  tableBodyBorderBottomColor* = "#D3D3D3"
  stubFontSize* = "100%"
  stubTextTransform* = "inherit"
  stubBorderStyle* = "solid"
  stubBorderWidth* = "2px"
  stubBorderColor* = ""      ## "" for `tableBodyHlinesColor`
  footnotesBackgroundColor* = "" ## "" for the table's background
  footnotesPadding* = "4px"
  footnotesPaddingHorizontal* = "5px"
  footnotesBorderBottomStyle* = "none"
  footnotesBorderBottomWidth* = "2px"
  footnotesBorderBottomColor* = "#D3D3D3"
  footnotesBorderLrStyle* = "none"
  footnotesBorderLrWidth* = "2px"
  footnotesBorderLrColor* = "#D3D3D3"
  sourceNotesBackgroundColor* = "" ## "" for the table's background
  sourceNotesPadding* = "4px"
  sourceNotesPaddingHorizontal* = "5px"
  sourceNotesBorderBottomStyle* = "none"
  sourceNotesBorderBottomWidth* = "2px"
  sourceNotesBorderBottomColor* = "#D3D3D3"
  sourceNotesBorderLrStyle* = "none"
  sourceNotesBorderLrWidth* = "2px"
  sourceNotesBorderLrColor* = "#D3D3D3"
  extraCss* = ""             ## more CSS, scoped to the table when it starts with ` ` or `.`
  tableAlign* = "center"     ## or "left", "right": where the table sits in its container
  tableNoDataMessage* = "No data to display" ## shown in the body of a table with no rows
  tableAdditionalCss* = ""   ## more CSS, as `optCss` (both add)
  tableFontColorLight* = "#FFFFFF" ## text on dark cells (`dataColor`, dark headings)
  columnLabelsHidden* = false
  columnLabelsUnitsPattern* = "{1}, {2}" ## label and units, when `colsUnits` gives no pattern
  rowGroupDefaultLabel* = "" ## a heading for the rows outside any group ("" for none)
  rowGroupAsColumn* = false  ## group labels as the first column of the stub
  stubIndentLength* = "1em"  ## the indent of one level (`tabStubIndent`)
  stubSeparate* = true       ## a rule between the stub and the body
  stubRowGroupFontSize* = "100%"
  stubRowGroupFontWeight* = "initial"
  stubRowGroupTextTransform* = "inherit"
  stubRowGroupBorderStyle* = "solid"
  stubRowGroupBorderWidth* = "2px"
  stubRowGroupBorderColor* = "#D3D3D3"
  footnotesMultiline* = true ## one footnote per line; false: all on one line
  footnotesSep* = " "        ## between footnotes on one line
  sourceNotesMultiline* = true
  sourceNotesSep* = " "
  rowStripingIncludeStub* = false
  rowStripingIncludeTableBody* = true

Table-wide looks, like gt's tab_options(). Change any subset with tabOptions(rowStriping = true, tableFontSize = "14px").

Tabellatype#

Tabella = object
  data*: TableData
  boxhead*: seq[ColInfo]
  title*, subtitle*: Text
  caption*: Text
  stubhead*: Text
  rownameCol*, groupnameCol*: string
  stubCols*: seq[string]     ## the stub's other columns, left of `rownameCol`
  groupLabels*: OrderedTable[string, Text] ## group id -> label, in display order
  rowGroups*: seq[string]    ## group id of each row ("" when ungrouped)
  rowOrder*: seq[int]        ## rows in display order (empty: as in the data)
  spanners*: seq[Spanner]
  formats*: seq[FormatRule]
  substitutions*: seq[FormatRule]
  styles*: seq[StyleRule]
  transforms*: seq[TransformRule]
  footnotes*: seq[Footnote]
  sourceNotes*: seq[Text]
  summaries*: seq[SummaryRule]
  merges*: seq[MergeRule]
  hiddenRows*: seq[int]      ## rows not shown (`rowsHide`)
  indents*: Table[int, int]  ## row -> indent level of its stub cell, 1 to 5
  decimalAligned*: seq[string] ## columns aligned on the decimal mark
  decimalMarks*: seq[string] ## the mark for each of them
  options*: TabOptions
  locale*: string
  id*: string

A display table: the data and everything said about how to show it.

colInfofunc#

func colInfo(
    t: Tabella,
    name: string
): ColInfo

No doc comment yet.

visibleDatafunc#

func visibleData(
    t: Tabella
): seq[ColInfo]

The data columns shown in the body, in display order (not the stub, groups or hidden ones).

hasSummariesfunc#

func hasSummaries(t: Tabella): bool

No doc comment yet.

hasStubfunc#

func hasStub(t: Tabella): bool

A stub is shown for the row names, and for the labels of summary rows (as in gt, a table with summary rows and no row names gets an empty stub).

hasRowNamesfunc#

func hasRowNames(t: Tabella): bool

No doc comment yet.

hasGroupsfunc#

func hasGroups(t: Tabella): bool

No doc comment yet.

stubColumnsfunc#

func stubColumns(
    t: Tabella
): seq[string]

The columns of the stub, the highest level first: tabella(data, rownameCol = ["mfr", "model"]) gives @["mfr", "model"].

an example, from the specs
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

groupAsColumnfunc#

func groupAsColumn(t: Tabella): bool

The group labels are a column of the stub (rowGroupAsColumn), not a row above each group.

stubWidthfunc#

func stubWidth(t: Tabella): int

How many columns the stub takes: the group labels (as a column), the higher levels, the row names (or the summary labels).

PatternReftype#

PatternRef = object
  column*: int               ## from 0
  field*: string             ## "" for the whole value

One {...} of a merge pattern: {2} is column 2, {2.lo} the field lo of the record in column 2, and {lo} the field lo of column 1.

patternRefsfunc#

func patternRefs(
    pattern: string
): seq[(string, PatternRef)]

The {...} of pattern, with the text inside the braces; a { with no } is text.

Locales

tabelline/localize · src/tabelline/localize.nim

Locales: the conventions of a language and region, from Unicode CLDR (locales.nim, currencies.nim, written by tools/cldr.nim).

namekind
Localetype
dateSkeletonsconst
timeSkeletonsconst
normalizeTagfunc
hasLocalefunc
getLocalefunc
skeletonfunc
Currencies
currencyInfofunc
isCurrencyfunc
The patterns
splitPatternfunc
negativePatternfunc
withCurrencyfunc
Dates and times
formatPatternfunc
×3: three overloads. A name opens its entry below.
13 names, 12 with a doc comment

getLocale("de-CH") gives the marks of numbers, the patterns of percentages and currencies, and the names and patterns of dates and times. Dates and times are written with CLDR's patterns (formatPattern): y, MMMM, d, EEEE, HH, mm, a, ...

Localetype#

Locale = object
  tag*: string               ## the tag found in CLDR ("de-CH"; "en" for an unknown tag)
  decimal*, group*, percentSign*: string
  percentPattern*, currencyPattern*, accountingPattern*: string ## CLDR patterns: "#,##0 %"
  months*, monthsAbbr*: array[12, string] ## names in a date: "1 gennaio"
  monthsAlone*, monthsAloneAbbr*: array[12, string] ## names on their own: "gennaio 2026"
  days*, daysAbbr*: array[7, string] ## Sunday first
  quarters*, quartersAbbr*: array[4, string]
  am*, pm*, eraBC*, eraAD*: string
  dateFormats*, timeFormats*: array[4, string] ## full, long, medium, short
  dateTime*: string          ## "{1}, {0}": the date, then the time
  skeletons*: seq[(string, string)] ## "yMMMd" -> "d MMM y"

No doc comment yet.

dateSkeletonsconst#

dateSkeletons = ["yMd", "yMEd", "yMMM", "yMMMM", "yMMMd", "yMMMEd", "GyMd",
                 "GyMMMd", "GyMMMEd", "yM", "Md", "MEd", "MMMd", "MMMEd",
                 "MMMMd", "GyMMM", "yQQQ", "yQQQQ", "Gy", "y", "M", "MMM", "d",
                 "Ed"]

The flexible date styles of gt: each is a CLDR skeleton, written in each locale's own order.

timeSkeletonsconst#

timeSkeletons = ["Hms", "Hm", "H", "hms", "hm", "h", "ms"]

The flexible time styles of gt that need no time zone.

normalizeTagfunc#

func normalizeTag(tag: string): string

"de_CH", "DE-ch" and "de-CH" are the same locale.

hasLocalefunc#

func hasLocale(tag: string): bool

Whether CLDR has data for this tag (after normalizeTag).

getLocalefunc#

func getLocale(tag: string): Locale

The conventions of a locale: getLocale("it").months[0] is "gennaio". An unknown region falls back to its language ("it-XX" is "it"), an unknown language to "en".

an example, from the specs
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 %

skeletonfunc#

func skeleton(
    l: Locale,
    name: string
): string

The pattern of a flexible style in this locale ("" when it is not one).

Currencies

currencyInfofunc#

func currencyInfo(
    code: string
): tuple[name, symbol: string, digits: int]

The English name, the symbol and the decimals of an ISO 4217 code: currencyInfo("JPY") is ("Japanese Yen", "¥", 0). An unknown code is its own symbol.

an example, from the specs
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

isCurrencyfunc#

func isCurrency(code: string): bool

Whether CLDR knows this ISO 4217 code.

The patterns

splitPatternfunc#

func splitPattern(
    pattern: string
): tuple[prefix, suffix: string]

The text before and after the number in a CLDR number pattern (its positive part): "#,##0.00 ¤" is ("", " ¤"), "¤#,##0.00" is ("¤", "").

negativePatternfunc#

func negativePattern(
    pattern: string
): tuple[prefix, suffix: string]

The text around a negative number: the pattern's negative part, or "" (a minus sign is added).

withCurrencyfunc#

func withCurrency(
    number, symbol, pattern: string
): string

The number and the symbol, placed and spaced as the pattern says.

Dates and times

formatPatternfunc#

func formatPattern(
    l: Locale,
    pattern: string,
    year = 0,
    month = 0,
    day = 0,
    weekday = -1,
    hour = -1,
    minute = 0,
    second = 0
): string

Writes a date or a time with a CLDR pattern: formatPattern(getLocale("it"), "d MMMM y", 2026, 11, 7) is "7 novembre 2026". weekday is 0 for Sunday. Text between quotes is kept.

Formats

tabelline/formats · src/tabelline/formats.nim

Formatting values: plain functions that turn numbers into text (formatNumber, formatPercent, ..., usable on their own, like Great Tables' vals), and the fmt* verbs that attach them to columns and rows of a table.

namekind
Locales
Markstype
localeMarksfunc
escapeHtmlfunc
Value formatting
sigfigDecimalsfunc
formatNumberfunc
formatCompactfunc
toSuperscriptfunc
toSubscriptfunc
formatScientificfunc
formatPercentfunc
currencySymbolfunc
formatCurrencyfunc
formatRomanfunc
dateStylesconst
formatDateproc
formatIntegerfunc
formatEngineeringfunc
formatNumberSifunc
formatPartsperfunc
formatBytesfunc
formatIndexfunc
formatSpelledNumfunc
timeStylesconst
formatTimefunc
strftimeToCldrfunc
formatDatetimeproc
formatDurationfunc
tfStylesconst
formatTffunc
formatFlagfunc
Inline markdown
inlineMarkdownfunc
mdToHtmlfunc
textToHtmlfunc
decodeEntitiesfunc
textToPlainfunc
Verbs
fmtproc ×2
fmtNumberproc
fmtIntegerproc
fmtPercentproc
fmtCurrencyproc
fmtScientificproc
fmtRomanproc
fmtDateproc
fmtMarkdownproc
subMissingproc
subZeroproc
fmtEngineeringproc
fmtNumberSiproc
fmtPartsperproc
fmtBytesproc
fmtIndexproc
fmtSpelledNumproc
fmtTimeproc
fmtDatetimeproc
fmtDurationproc
fmtUrlproc
fmtEmailproc
countryNamefunc
circleFlagfunc
fmtFlagproc
Substitutions
subSmallValsproc
subLargeValsproc
subValuesproc ×2
fmtTfproc
Fractions, bins, ...
formatFractionfunc
formatBinsproc
formatCountryfunc
fmtFractionproc
fmtBinsproc
fmtPassthroughproc
fmtCountryproc
fmtAutoproc
×3: three overloads. A name opens its entry below.
72 names, 66 with a doc comment

A verb resolves its columns and rows when it is called, and the formats run when the table is rendered: the last format given for a cell wins.

Locales

Markstype#

Marks = tuple[sep, dec: string]

No doc comment yet.

localeMarksfunc#

func localeMarks(locale: string): Marks

Digit group and decimal marks for a locale, from CLDR: localeMarks("it") is (".", ","), localeMarks("de-CH") is ("'", "."), localeMarks("fr") is (" ", ",") with a narrow no-break space. An unknown locale, or "", is "en".

escapeHtmlfunc#

func escapeHtml(s: string): string

No doc comment yet.

Value formatting

sigfigDecimalsfunc#

func sigfigDecimals(
    x: float,
    nSigfig: int
): int

How many decimals show nSigfig significant figures of x: 3 for 0.01234 and 3 figures, 0 for 12345 (which shows as 12,300: the figures after the third are rounded to zeros).

formatNumberfunc#

func formatNumber(
    x: float,
    decimals = 2,
    useSeps = true,
    dropTrailingZeros = false,
    sepMark = ",",
    decMark = ".",
    forceSign = false,
    nSigfig = 0,
    accounting = false,
    pattern = "{x}",
    locale = ""
): string

formatNumber(1234.5678) is "1,234.57"; formatNumber(1234.5, 1, sepMark = ".", decMark = ",") is "1.234,5". nSigfig shows that many significant figures instead of decimals (gt's n_sigfig): formatNumber(0.012345, nSigfig = 3) is "0.0123". accounting writes a negative number in parentheses, "(12.50)"; pattern puts the number in a text, "{x} kg"; locale takes its marks ("it": "1.234,57"), as fmtNumber does.

an example, from the specs
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

formatCompactfunc#

func formatCompact(
    x: float,
    decimals = 1,
    decMark = ".",
    nSigfig = 0,
    pattern = "{x}",
    locale = ""
): string

Large numbers with a suffix: 1234567 is "1.2M"; with nSigfig = 3, "1.23M".

an example, from the specs
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

toSuperscriptfunc#

func toSuperscript(s: string): string

toSuperscript("-2") is "⁻²" (^s when a character has no superscript).

toSubscriptfunc#

func toSubscript(s: string): string

toSubscript("2") is "₂" (_s when a character has no subscript).

formatScientificfunc#

func formatScientific(
    x: float,
    decimals = 2,
    decMark = ".",
    ctx = rcText,
    expStyle = "x10n",
    pattern = "{x}",
    locale = ""
): string

formatScientific(5.97e24) is "5.97 × 10²⁴"; expStyle "e" is "5.97e24" and "E" "5.97E24", as gt's exp_style; locale takes its decimal mark ("de": "5,97 × 10²⁴").

formatPercentfunc#

func formatPercent(
    x: float,
    decimals = 1,
    scaleValues = true,
    decMark = ".",
    sepMark = ",",
    pattern = "#,##0%",
    percentSign = "%",
    accounting = false,
    locale = ""
): string

formatPercent(0.123) is "12.3%"; pattern is a locale's (getLocale("fr").percentPattern is "#,##0 %", with a no-break space), which locale = "fr" takes, with its marks. accounting writes "(12.3%)" for −0.123.

currencySymbolfunc#

func currencySymbol(
    code: string
): string

The symbol of an ISO 4217 code, from CLDR (English): "EUR" is "€", "CHF" is "CHF", "CAD" is "CA$". An unknown code is its own symbol.

formatCurrencyfunc#

func formatCurrency(
    x: float,
    currency = "USD",
    decimals = -1,
    sepMark = ",",
    decMark = ".",
    placement = "",
    pattern = "¤#,##0.00",
    accounting = false,
    useSubunits = true,
    locale = ""
): string

formatCurrency(49.95, "EUR") is "€49.95". decimals = -1 takes the currency's (0 for JPY, 3 for BHD, 2 for most); useSubunits = false drops them. The symbol goes where pattern puts it (a locale's currencyPattern: "#,##0.00 ¤" in Italian, which locale = "it" takes, with its marks), or placement "left" or "right". accounting writes a negative amount in parentheses.

an example, from the specs
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

formatRomanfunc#

func formatRoman(
    n: int,
    upper = true
): string

formatRoman(2026) is "MMXXVI".

dateStylesconst#

dateStyles = [("iso", "y-MM-dd"), ("wday_month_day_year", "EEEE, MMMM d, y"),
              ("wd_m_day_year", "EEE, MMM d, y"),
              ("wday_day_month_year", "EEEE d MMMM y"),
              ("month_day_year", "MMMM d, y"), ("m_day_year", "MMM d, y"),
              ("day_m_year", "d MMM y"), ("day_month_year", "d MMMM y"),
              ("day_month", "d MMMM"), ("day_m", "d MMM"), ("year", "y"),
              ("month", "LLLL"), ("day", "dd"), ("year.mn.day", "y/MM/dd"),
              ("y.mn.day", "yy/MM/dd"), ("year_week", "Y-\'W\'ww"),
              ("year_quarter", "y-\'Q\'Q"), ("year_month", "LLLL y"),
              ("dd/mm/yyyy", "dd/MM/y"), ("mm/dd/yyyy", "MM/dd/y")]

gt's fixed date styles, as CLDR patterns, with names in the locale's language. The flexible ones (dateSkeletons: "yMMMd", "yMMMEd", ...) also follow the locale's order.

formatDateproc#

proc formatDate(
    s: string,
    dateStyle = "iso",
    locale = ""
): string

An ISO date ("2015-01-15", or the date part of a datetime) in one of dateStyles, a flexible style of dateSkeletons ("yMMMd"), or a std/times pattern (English names), in the language of locale: formatDate("2015-01-15", "day_month_year", "it") is "15 gennaio 2015". Text that is not a date is returned as is.

an example, from the specs
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

formatIntegerfunc#

func formatInteger(
    x: float,
    useSeps = true,
    sepMark = ",",
    accounting = false,
    pattern = "{x}",
    locale = ""
): string

formatInteger(1234.6) is "1,235"; locale = "it", "1.235".

formatEngineeringfunc#

func formatEngineering(
    x: float,
    decimals = 2,
    decMark = ".",
    ctx = rcText
): string

Scientific notation with exponents in steps of three: formatEngineering(12345) is "12.35 × 10³".

formatNumberSifunc#

func formatNumberSi(
    x: float,
    unit = "",
    decimals = 2,
    inclSpace = true,
    decMark = "."
): string

A number with an SI prefix: formatNumberSi(12345, "g") is "12.35 kg".

formatPartsperfunc#

func formatPartsper(
    x: float,
    toUnits = "per-mille",
    decimals = 2,
    scaleValues = true,
    inclSpace = "auto",
    decMark = ".",
    sepMark = ","
): string

Fractions as parts per thousand ("per-mille", ‰), ten thousand ("per-myriad", ‱), hundred thousand ("pcm"), million ("ppm"), billion ("ppb"), trillion ("ppt") or quadrillion ("ppq"). inclSpace = "auto" puts a space before the letters and none before ‰ and ‱.

formatBytesfunc#

func formatBytes(
    x: float,
    standard = "decimal",
    decimals = 1,
    inclSpace = true,
    decMark = "."
): string

Sizes in bytes: formatBytes(1500) is "1.5 kB", formatBytes(1536, "binary") is "1.5 KiB".

formatIndexfunc#

func formatIndex(
    n: int,
    upper = true,
    indexAlgo = "repeat"
): string

Letters for 1, 2, 3, ...: "A", "B", ... "Z", then "AA", "BB" (indexAlgo = "repeat") or "AA", "AB" ("excel").

formatSpelledNumfunc#

func formatSpelledNum(n: int): string

Numbers from zero to one hundred in English words: formatSpelledNum(42) is "forty-two"; other numbers stay as digits.

timeStylesconst#

timeStyles = ["iso", "iso-short", "h_m_s_p", "h_m_p", "h_p", "h_m", "h_m_s"]

Named time styles: 14:35:00, 14:35, 2:35:00 PM, 2:35 PM, 2 PM, 14:35, 14:35:00. The flexible ones (timeSkeletons: "Hm", "hm", ...) follow the locale.

formatTimefunc#

func formatTime(
    s: string,
    timeStyle = "iso",
    locale = ""
): string

A time ("14:35", "14:35:07", or the time of an ISO datetime) in one of timeStyles or timeSkeletons, with the locale's AM and PM: formatTime("14:35", "hm", "it") is "2:35 PM". Text that is not a time is returned as is.

an example, from the specs
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

strftimeToCldrfunc#

func strftimeToCldr(f: string): string

A strftime format ("%Y-%m-%d %H:%M", as Python's and Great Tables' format_str) as a CLDR pattern: %Y %y %m %d %e %B %b %A %a %H %I %M %S %p and %%; other text is kept as it is.

formatDatetimeproc#

proc formatDatetime(
    s: string,
    dateStyle = "iso",
    timeStyle = "iso",
    sep = " ",
    locale = "",
    formatStr = ""
): string

An ISO datetime ("2026-11-07T14:35:00" or "2026-11-07 14:35") as a date and a time, in the date and time styles; a date without a time shows only the date. formatStr writes it with a strftime format instead, as Great Tables' format_str: "%d %B %Y, %H:%M" is "07 November 2026, 14:35", in the locale's language.

formatDurationfunc#

func formatDuration(
    x: float,
    inputUnits = "seconds",
    outputUnits: openArray[string] = [],
    durationStyle = "narrow",
    trimZeroUnits = true,
    maxOutputUnits = 0
): string

A length of time in weeks, days, hours, minutes and seconds: formatDuration(7503) is "2h 5m 3s"; durationStyle "wide" (2 hours 5 minutes 3 seconds), "colon-sep" (02:05:03) or "iso" (PT2H5M3S). The smallest output unit is rounded.

an example, from the specs
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

tfStylesconst#

tfStyles = [("true-false", "true", "false"), ("yes-no", "yes", "no"),
            ("up-down", "up", "down"), ("check-mark", "✓", "✗"),
            ("circles", "●", "○"), ("squares", "■", "□"),
            ("diamonds", "◆", "◇"), ("arrows", "↑", "↓"),
            ("triangles", "▲", "▼"), ("triangles-lr", "▶", "◀")]

Named pairs of texts for booleans, as gt's tf_style.

formatTffunc#

func formatTf(
    b: bool,
    tfStyle = "check-mark"
): string

A boolean in one of tfStyles: formatTf(true, "yes-no") is "yes".

formatFlagfunc#

func formatFlag(
    codes: string,
    sep = " "
): string

Country codes (ISO 3166-1, two or three letters, comma or space separated) as flag emoji: formatFlag("IT") and formatFlag("ITA") are "🇮🇹". Anything else is left as it is.

Inline markdown

inlineMarkdownfunc#

func inlineMarkdown(s: string): string

Inline Markdown: **bold** and __bold__, *italic* and _italic_, ~~struck~~, `code`, [text](url) and <https://...>, ~sub~, ^sup^, HTML entities (&mdash;), and <br>, two spaces before a newline or a backslash before it for a line break. With no dependency (nimib's Markdown is not needed here); md() adds paragraphs and lists.

mdToHtmlfunc#

func mdToHtml(s: string): string

Markdown with paragraphs (a blank line between them) and lists (- item, 1. item), each line inline Markdown. One paragraph is its inline HTML, with no <p> around it, so a label stays a label.

textToHtmlfunc#

func textToHtml(t: Text): string

No doc comment yet.

decodeEntitiesfunc#

func decodeEntities(s: string): string

The text of HTML entities: &mdash; is "—", &#8212; and &#x2014; too (for text and Markdown output); an entity it does not know is left as it is.

textToPlainfunc#

func textToPlain(t: Text): string

No doc comment yet.

Verbs

fmtproc#

proc fmt(
    t: sink Tabella,
    columns: ColSel,
    fn: FormatFn,
    rows = allRows()
): Tabella
proc fmt(
    t: sink Tabella,
    columns: ColSel,
    fn: proc (v: Value): string,
    rows = allRows()
): Tabella

The general formatter: fn(value, ctx) gives the text of each (non-missing) cell.

fmtNumberproc#

proc fmtNumber(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    decimals = 2,
    nSigfig = 0,
    dropTrailingZeros = false,
    useSeps = true,
    accounting = false,
    scaleBy = 1.0,
    compact = false,
    pattern = "{x}",
    forceSign = false,
    locale = "",
    sepMark = "",
    decMark = ""
): Tabella

Numbers with a fixed number of decimals and digit grouping: fmtNumber("mass", decimals = 1). nSigfig = 3 shows three significant figures instead (gt's n_sigfig, also with compact); accounting writes negative numbers in parentheses.

an example, from the specs
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

fmtIntegerproc#

proc fmtInteger(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    useSeps = true,
    accounting = false,
    scaleBy = 1.0,
    pattern = "{x}",
    forceSign = false,
    locale = "",
    sepMark = ""
): Tabella

No doc comment yet.

an example, from the specs
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

fmtPercentproc#

proc fmtPercent(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    decimals = 1,
    scaleValues = true,
    accounting = false,
    locale = ""
): Tabella

Fractions as percentages: 0.123 is "12.3%" (scaleValues = false for values already in %), "12,3 %" in French; accounting writes "(12.3%)" for −0.123.

an example, from the specs
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 %

fmtCurrencyproc#

proc fmtCurrency(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    currency = "USD",
    decimals = -1,
    placement = "",
    accounting = false,
    useSubunits = true,
    locale = ""
): Tabella

Numbers as amounts of a currency (any ISO 4217 code), with its symbol and its decimals, in the locale's way: "€49.95" in English, "49,95 €" in Italian. placement "left" or "right" puts the symbol there whatever the locale; accounting writes negative amounts in parentheses.

an example, from the specs
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

fmtScientificproc#

proc fmtScientific(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    decimals = 2,
    expStyle = "x10n",
    locale = ""
): Tabella

Scientific notation: 5.97e24 is "5.97 × 10²⁴"; expStyle "e" or "E" writes "5.97e24".

an example, from the specs
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

fmtRomanproc#

proc fmtRoman(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    upper = true
): Tabella

No doc comment yet.

fmtDateproc#

proc fmtDate(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    dateStyle = "iso",
    locale = ""
): Tabella

ISO date strings in a dateStyles style ("month_day_year", ...), a flexible style ("yMMMd"), or a std/times pattern, in the locale's language.

an example, from the specs
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*

fmtMarkdownproc#

proc fmtMarkdown(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows()
): Tabella

Cell text as Markdown (inline: emphasis, code, links).

subMissingproc#

proc subMissing(
    t: sink Tabella,
    columns: ColSel = everything(),
    rows = allRows(),
    missingText: Text = toText("—")
): Tabella

Shows missing values as missingText (by default they are blank): a text, or Markdown, md("**STABLE**"), as gt's missing_text = md(...).

an example, from the specs
let d = tableData:
  n: [0, nil, 3]
let t = tabella(d):
  subMissing()
  subZero zeroText = "none"
echo t
n
none
—
3

subZeroproc#

proc subZero(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    zeroText = "nil"
): Tabella

Shows zeros as zeroText.

an example, from the specs
let d = tableData:
  n: [0, nil, 3]
let t = tabella(d):
  subMissing()
  subZero zeroText = "none"
echo t
n
none
—
3

fmtEngineeringproc#

proc fmtEngineering(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    decimals = 2,
    locale = ""
): Tabella

Scientific notation with exponents in steps of three: 12345 is "12.35 × 10³".

an example, from the specs
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

fmtNumberSiproc#

proc fmtNumberSi(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    unit = "",
    decimals = 2,
    inclSpace = true,
    locale = ""
): Tabella

Numbers with SI prefixes and a unit: 12345 with unit = "g" is "12.35 kg".

an example, from the specs
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

fmtPartsperproc#

proc fmtPartsper(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    toUnits = "per-mille",
    decimals = 2,
    scaleValues = true,
    inclSpace = "auto",
    locale = ""
): Tabella

Fractions as parts per thousand (‰), ten thousand (‱), million (ppm), ... see formatPartsper.

an example, from the specs
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‰

fmtBytesproc#

proc fmtBytes(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    standard = "decimal",
    decimals = 1,
    inclSpace = true,
    locale = ""
): Tabella

Sizes in bytes: kB, MB, GB (standard = "decimal") or KiB, MiB, GiB ("binary").

an example, from the specs
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

fmtIndexproc#

proc fmtIndex(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    upper = true,
    indexAlgo = "repeat"
): Tabella

Whole numbers as letters: 1 is "A", 27 is "AA" (see formatIndex).

an example, from the specs
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

fmtSpelledNumproc#

proc fmtSpelledNum(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows()
): Tabella

Whole numbers from zero to one hundred in English words.

an example, from the specs
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

fmtTimeproc#

proc fmtTime(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    timeStyle = "iso",
    locale = ""
): Tabella

Times ("14:35:00", or the time of a datetime) in one of timeStyles or timeSkeletons.

fmtDatetimeproc#

proc fmtDatetime(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    dateStyle = "iso",
    timeStyle = "iso",
    sep = " ",
    formatStr = "",
    locale = ""
): Tabella

ISO datetimes as a date and a time, each in its style, or with a strftime formatStr ("%Y/%m/%d %H:%M"), as Great Tables' format_str.

an example, from the specs
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

fmtDurationproc#

proc fmtDuration(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    inputUnits = "seconds",
    outputUnits: openArray[string] = [],
    durationStyle = "narrow",
    trimZeroUnits = true,
    maxOutputUnits = 0
): Tabella

Numbers as lengths of time: 7503 seconds is "2h 5m 3s" (see formatDuration).

an example, from the specs
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

fmtUrlproc#

proc fmtUrl(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    label = "",
    asButton = false,
    color = "",
    target = "",
    showUnderline = true
): Tabella

Addresses as links: the address is the text, unless label is given or the cell is a Markdown link [label](address); asButton draws them as small buttons.

an example, from the specs
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

fmtEmailproc#

proc fmtEmail(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    label = "",
    asButton = false,
    color = "",
    target = "",
    showUnderline = true
): Tabella

Email addresses as mailto: links, as fmtUrl does for web addresses.

countryNamefunc#

func countryName(code: string): string

The English name of a country or territory by its two- or three-letter code (ISO 3166-1), from Unicode CLDR: countryName("IT") and countryName("ITA") are "Italy". Other text is returned as it is.

circleFlagfunc#

func circleFlag(
    code: string,
    height = "1em"
): string

The round flag of a two- or three-letter country code, as inline SVG (HatScripts' circle-flags, MIT, which Great Tables draws too); "" when there is none.

fmtFlagproc#

proc fmtFlag(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    sep = " ",
    useTitle = true,
    round = false,
    height = "1em"
): Tabella

Two-letter (or three-letter) country codes as flags, one or several (a list, or separated by commas). The flags are emoji, which load nothing but are drawn by the reader's system (as two letters on Windows); round = true draws Great Tables' round flags instead, as inline SVG of height. With useTitle the country's name is the HTML title, shown on hover.

an example, from the specs
let d = tableData:
  country: ["IT", "JPN", "FR,DE"]
let t = tabella(d):
  fmtFlag "country"
echo t
country
🇮🇹
🇯🇵
🇫🇷 🇩🇪

Substitutions

subSmallValsproc#

proc subSmallVals(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    threshold = 0.01,
    smallPattern = "<{x}",
    sign = "+"
): Tabella

Shows numbers closer to zero than threshold (but not zero) as smallPattern, with the threshold for {x}: "<0.01". sign = "-" does the same for negative numbers ("<−0.01").

an example, from the specs
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

subLargeValsproc#

proc subLargeVals(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    threshold = 1000000000000.0,
    largePattern = ">={x}",
    sign = "+"
): Tabella

Shows numbers at or beyond threshold as largePattern: ">=1T". sign = "-" does the same for numbers at or below minus the threshold.

an example, from the specs
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

subValuesproc#

proc subValues(
    t: sink Tabella,
    columns: ColSel = everything(),
    rows = allRows(),
    fn: proc (v: Value): bool,
    replacement: string
): Tabella
proc subValues[T](
    t: sink Tabella,
    columns: ColSel = everything(),
    rows = allRows(),
    values: openArray[T],
    replacement: string
): Tabella

Shows the values for which fn holds as replacement.

an example, from the specs
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

fmtTfproc#

proc fmtTf(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    tfStyle = "check-mark",
    trueText = "",
    falseText = "",
    naText = "",
    colors: openArray[string] = [],
    html = false
): Tabella

Booleans as two texts: a named tfStyle ("true-false", "yes-no", "check-mark", "circles", "arrows", ... see tfStyles) or your own trueText and falseText; naText for missing values; colors (for true, false) colour them in HTML; with html = true the texts are HTML (an SVG symbol, say) and are not escaped.

an example, from the specs
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*

Fractions, bins, ...

formatFractionfunc#

func formatFraction(
    x: float,
    accuracy = "low",
    denominator = 0,
    simplify = true,
    layout = "inline",
    useSeps = true,
    sepMark = ",",
    ctx = rcText
): string

A number as a mixed fraction: formatFraction(2.25) is "2 1/4", formatFraction(0.333) is "1/3". accuracy is "low" (denominators up to 9), "med" (99) or "high" (999); a denominator fixes it ("2/16"), reduced when simplify. layout = "diagonal" shows "2¼"-style fractions (<sup> and <sub> in HTML).

formatBinsproc#

proc formatBins(
    s: string,
    sep = "--",
    fmt: proc (x: float): string = nil
): string

A bin written as an interval, "[10,20)" or "(0,5]", as a range: "10–20". sep goes between the two ends (-- is an en dash); fmt formats each end.

formatCountryfunc#

func formatCountry(
    codes: string,
    sep = ", "
): string

Country codes (comma or space separated) as names: formatCountry("IT, FR") is "Italy, France".

fmtFractionproc#

proc fmtFraction(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    accuracy = "low",
    denominator = 0,
    simplify = true,
    layout = "inline",
    useSeps = true,
    pattern = "{x}",
    locale = ""
): Tabella

Numbers as mixed fractions: 2.25 is "2 1/4" (see formatFraction).

an example, from the specs
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

fmtBinsproc#

proc fmtBins(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    sep = "--",
    fmt: proc (x: float): string = nil
): Tabella

Intervals such as "[10,20)" as ranges, "10–20"; fmt formats both ends: fmtBins("size", fmt = x => formatNumber(x, 0)).

an example, from the specs
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

fmtPassthroughproc#

proc fmtPassthrough(
    t: sink Tabella,
    columns: ColSel = everything(),
    rows = allRows(),
    escape = true,
    pattern = "{x}"
): Tabella

Values shown as they are, in a pattern; with escape = false a value is HTML.

an example, from the specs
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

fmtCountryproc#

proc fmtCountry(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    pattern = "{x}",
    sep = ", "
): Tabella

Two- or three-letter country codes as English names, from CLDR: "IT" is "Italy".

an example, from the specs
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

fmtAutoproc#

proc fmtAuto(
    t: sink Tabella,
    columns: ColSel = everything(),
    rows = allRows(),
    scope: openArray[string] = ["numbers", "currency"],
    lgNumPref = "sci",
    locale = ""
): Tabella

A format for each column, from its values: numbers with as many decimals as they need (up to 3), very small or large ones in scientific notation (lgNumPref = "suf": large ones with a suffix, "12.3M"), and a currency when the column's name ends with an ISO 4217 code ("price_eur").

an example, from the specs
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

Units

tabelline/units · src/tabelline/units.nim

Units and chemical formulas written as text, in gt's units notation: "kg/m^3", "m s^-2", "m /s" (a unit after a solidus is a power −1), "T_eff", ":mu:g", "degC", "%H2O%".

namekind
Chemistry
formatChemfunc
formatUnitsfunc
withUnitsfunc
Verbs
fmtUnitsproc
fmtChemproc
colsUnitsproc
×3: three overloads. A name opens its entry below.
6 names, 6 with a doc comment

formatUnits and formatChem turn them into HTML (<sup>, <sub>) or into plain text with Unicode super- and subscripts (kg/m³), so the text and Markdown outputs show them too. In a label, units go between {{ and }}: "Density, {{kg/m^3}}".

Chemistry

formatChemfunc#

func formatChem(
    s: string,
    ctx = rcText
): string

A chemical formula or reaction, in gt's notation: formatChem("CuSO4 * 5H2O") is "CuSO₄⋅5 H₂O", formatChem("2H2 + O2 -> 2H2O") is "2 H₂ + O₂ → 2 H₂O".

an example, from the specs
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

formatUnitsfunc#

func formatUnits(
    s: string,
    ctx = rcText
): string

Units in gt's notation: formatUnits("kg/m^3") is "kg/m³", formatUnits("m /s") is "m s⁻¹", formatUnits("T_eff") is "Tₑff" in text and T<sub>eff</sub> in HTML. A part between % signs is a chemical formula: "g %CO2%".

withUnitsfunc#

func withUnits(s: string; ctx: RenderContext;
               plain: proc (s: string): string

A label with units between {{ and }}: the units are formatted, the rest goes through plain.

Verbs

fmtUnitsproc#

proc fmtUnits(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows()
): Tabella

Cells written in gt's units notation, shown as units: "m s^-2" is "m s⁻²".

an example, from the specs
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

fmtChemproc#

proc fmtChem(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows()
): Tabella

Cells written as chemical formulas or reactions: "H2SO4" is "H₂SO₄".

an example, from the specs
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

colsUnitsproc#

proc colsUnits(
    t: sink Tabella,
    units: openArray[(string, string)],
    unitsPattern = ""
): Tabella

Units for column labels, in gt's notation: colsUnits({"density": "kg/m^3"}) shows the label "density, kg/m³". unitsPattern places them: {1} is the label, {2} the units ("": the option columnLabelsUnitsPattern, "{1}, {2}"). Inside tabella(data): body, also as a block, one pair per line (see tabella): colsUnits: then density: "kg/m^3".

an example, from the specs
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

The verbs

tabelline/verbs · src/tabelline/verbs.nim

The verbs that build a table spec, named after gt and Great Tables in camelCase: tab* add parts (header, spanners, notes, styles, options), cols* change columns, dataColor and opt* change the looks.

namekind
Creating
initTabellaproc ×6
Parts
tabHeaderproc
tabStubheadproc
tabSpannerproc
tabSpannerDelimproc
tabCaptionproc
tabSourceNoteproc
tabRowGroupproc
tabStubproc ×2
rmHeaderproc
rmStubheadproc
rmCaptionproc
rmSpannersproc
rmFootnotesproc
rmSourceNotesproc
Locations
titlefunc
subtitlefunc
stubheadfunc
columnLabelsfunc
spannersfunc
stubfunc
rowGroupsfunc ×2
bodyfunc ×3
sourceNotesfunc
headerfunc
columnHeaderfunc
footerfunc
spannerLabelsfunc
footnotesfunc
summaryfunc
summaryStubfunc
grandSummaryfunc
grandSummaryStubfunc
resolveproc
tabStyleproc ×2
tabFootnoteproc
Text
textTransformproc
textReplaceproc
textCaseMatchproc
Columns
colsLabelproc ×3
colsAlignproc
colsWidthproc
colsHideproc
colsUnhideproc
colsMoveproc
colsLabelWithproc ×2
colsMoveToEndproc
colsReorderproc
colsMoveToStartproc
Rows
rowOrderproc
rowGroupOrderproc
Summary rows
aggconst
sumfunc
meanfunc
medianfunc
stdfunc
minfunc
maxfunc
countfunc
aggregateproc
toFormatFnproc
summaryRowsproc ×2
grandSummaryRowsproc ×2
Colour from the data
dataColorproc
Options
tabOptionsmacro
optRowStripingproc
optAlignTableHeaderproc
optAllCapsproc
optTableFontproc
fontStackNamesconst
systemFontsfunc
defaultFontsfunc
CssThemetype
cssThemefunc
optCssThemeproc ×2
optVerticalPaddingproc
optHorizontalPaddingproc
optTableOutlineproc
optStylizeproc
optTableLinesproc
optFootnoteMarksproc ×3
optFootnoteSpecproc
optFootnoteOrderproc
optCssproc
Merges
colsMergeproc
colsMergeUncertproc
colsMergeRangeproc
colsMergeNPctproc
Adding columns
colsAddproc ×3
summaryColumnsproc ×2
Adding rows
rowsAddproc ×2
rowsHideproc
rowsUnhideproc
Stub and alignment
tabStubIndentproc ×2
colsAlignDecimalproc
Rotated labels
colsLabelRotateproc
Styles from the data
fromColumnfunc
tabStyleBodyproc
Preview
initTabellaPreviewproc
×3: three overloads. A name opens its entry below.
99 names, 78 with a doc comment

Each takes a Tabella and returns the new one (sink, so a chain moves the spec along instead of copying it).

Creating

initTabellaproc#

proc initTabella(
    data: TableData,
    rownameCol = "",
    groupnameCol = "",
    id = "",
    locale = "",
    autoAlign = true
): Tabella
proc initTabella(
    data: TableData,
    rownameCol: openArray[string],
    groupnameCol = "",
    id = "",
    locale = "",
    autoAlign = true,
    rowGroupAsColumn = false
): Tabella
proc initTabella(
    data: TableData,
    rownameCol: string,
    groupnameCol: string,
    rowGroupAsColumn: bool,
    id = "",
    locale = "",
    autoAlign = true
): Tabella
proc initTabella[T: object | tuple](
    rows: openArray[T],
    rownameCol = "",
    groupnameCol = "",
    id = "",
    locale = ""
): Tabella
proc initTabella[T: object | tuple](
    rows: openArray[T],
    rownameCol: openArray[string],
    groupnameCol = "",
    id = "",
    locale = "",
    rowGroupAsColumn = false
): Tabella
proc initTabella(
    t: sink Tabella
): Tabella

A display table for data. rownameCol makes a column the stub (row labels), groupnameCol groups the rows by a column, in order of first appearance.

Parts

tabHeaderproc#

proc tabHeader(
    t: sink Tabella,
    title: Text,
    subtitle: Text = toText("")
): Tabella

No doc comment yet.

an example, from the specs
let t = tabella(tavolaPitagorica(3), rownameCol = "×"):
  tabHeader "Tabellina"
  tabFootnote "by heart", loc.title()
echo t
Tabellina1
123
1123
2246
3369
1 by heart

tabStubheadproc#

proc tabStubhead(
    t: sink Tabella,
    label: Text
): Tabella

No doc comment yet.

an example, from the specs
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

tabSpannerproc#

proc tabSpanner(
    t: sink Tabella,
    label: Text,
    columns: ColSel,
    level = 1,
    gather = true
): Tabella

A label over columns. Higher levels sit above lower ones. With gather (the default, as in gt) the columns are moved next to the first of them, in the order given, so the label spans them all; with gather = false they stay where they are.

an example, from the specs
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

tabSpannerDelimproc#

proc tabSpannerDelim(
    t: sink Tabella,
    delim = ".",
    columns: ColSel = everything(),
    split = "last",
    limit = -1,
    reverse = false
): Tabella

Spanners and labels from column names: "size.mass" gets the label "mass" under a spanner "size". Names with more parts get more levels; next to each other, the same parts make one spanner. limit caps the splits, counted from the split side ("last" or "first"); reverse reads the parts the other way round.

an example, from the specs
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

tabCaptionproc#

proc tabCaption(
    t: sink Tabella,
    caption: Text
): Tabella

A caption for the table (an HTML <caption>), for screen readers and for figures.

an example, from the specs
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

tabSourceNoteproc#

proc tabSourceNote(
    t: sink Tabella,
    note: Text
): Tabella

No doc comment yet.

an example, from the specs
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

tabRowGroupproc#

proc tabRowGroup(
    t: sink Tabella,
    label: Text,
    rows: RowSel = RowSel(kind: rsIndices),
    id = ""
): Tabella

Puts rows in a group (made when it is new). Groups show in the order they are made, and rows in no group come first. With the id of a group already there (one made by groupnameCol is named by its value), label is its new label: tabRowGroup(md("[gt](...)"), id = "gt") makes a link of it, as gt's tab_row_group(label = md(...)).

an example, from the specs
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

tabStubproc#

proc tabStub(
    t: sink Tabella,
    rownameCol = "",
    groupnameCol = ""
): Tabella
proc tabStub(
    t: sink Tabella,
    rownameCol: openArray[string],
    groupnameCol = ""
): Tabella

Chooses the stub (and the row groups) of a table already made, as Great Tables' tab_stub(rowname_col, groupname_col): the same as tabella(data, rownameCol = ..., groupnameCol = ...). Verbs called before it keep what they did to other columns.

an example, from the specs
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

rmHeaderproc#

proc rmHeader(t: sink Tabella): Tabella

Removes the title and the subtitle.

an example, from the specs
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.

rmStubheadproc#

proc rmStubhead(
    t: sink Tabella
): Tabella

No doc comment yet.

rmCaptionproc#

proc rmCaption(t: sink Tabella): Tabella

No doc comment yet.

rmSpannersproc#

proc rmSpanners(
    t: sink Tabella,
    spanners: openArray[string] = [],
    levels: openArray[int] = []
): Tabella

Removes the spanners with these labels, or at these levels; with neither, every spanner.

rmFootnotesproc#

proc rmFootnotes(
    t: sink Tabella,
    footnotes: openArray[int] = []
): Tabella

Removes the footnotes at these indices (0-based, in the order they were added), or all.

rmSourceNotesproc#

proc rmSourceNotes(
    t: sink Tabella,
    sourceNotes: openArray[int] = []
): Tabella

Removes the source notes at these indices (0-based), or all.

an example, from the specs
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.

Locations

titlefunc#

func title(_: LocNs): Loc

No doc comment yet.

an example, from the specs
let t = tabella(tavolaPitagorica(3), rownameCol = "×"):
  tabHeader "Tabellina"
  tabFootnote "by heart", loc.title()
echo t
Tabellina1
123
1123
2246
3369
1 by heart

subtitlefunc#

func subtitle(_: LocNs): Loc

No doc comment yet.

stubheadfunc#

func stubhead(_: LocNs): Loc

No doc comment yet.

an example, from the specs
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!

columnLabelsfunc#

func columnLabels(
    _: LocNs,
    cols: ColSel = everything()
): Loc

No doc comment yet.

an example, from the specs
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.

spannersfunc#

func spanners(
    _: LocNs,
    labels: varargs[string]
): Loc

No doc comment yet.

stubfunc#

func stub(
    _: LocNs,
    rows = allRows(),
    cols: ColSel = everything(),
    labels: openArray[string] = []
): Loc

The stub's cells of rows; with labels, the rows whose stub reads one of them (loc.stub(labels = ["banana"])), together with the rows given (rows = [0], labels = ["banana"]), as Great Tables' loc.stub(rows = [0, "banana"]).

an example, from the specs
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.

rowGroupsfunc#

func rowGroups(
    _: LocNs,
    groups: varargs[string]
): Loc
func rowGroups(
    _: LocNs,
    rows: RowSel
): Loc

The groups of these rows: loc.rowGroups(rows = where(it.mass > 100)), as Great Tables' loc.row_groups(rows = ...).

an example, from the specs
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

bodyfunc#

func body(
    _: LocNs,
    cols: ColSel = everything(),
    rows = allRows()
): Loc
func body(
    _: LocNs,
    cols: ColSel = everything(),
    rows = allRows(),
    mask: proc (v: Value; col: Column): bool
): Loc
func body(
    _: LocNs,
    cols: ColSel = everything(),
    rows = allRows(),
    mask: proc (v: Value): bool
): Loc

The data cells of cols and rows.

an example, from the specs
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

sourceNotesfunc#

func sourceNotes(_: LocNs): Loc

No doc comment yet.

headerfunc#

func header(_: LocNs): Loc

The title and the subtitle together.

columnHeaderfunc#

func columnHeader(_: LocNs): Loc

The stub head, the spanners and the column labels together.

spannerLabelsfunc#

func spannerLabels(
    _: LocNs,
    labels: varargs[string]
): Loc

The same as loc.spanners, by Great Tables' name.

footnotesfunc#

func footnotes(_: LocNs): Loc

No doc comment yet.

summaryfunc#

func summary(
    _: LocNs,
    groups: openArray[string] = [],
    columns: ColSel = everything(),
    rows: openArray[string] = []
): Loc

The cells of the summary rows of groups (all, by default), in columns, for the rows labelled rows (all, by default).

summaryStubfunc#

func summaryStub(
    _: LocNs,
    groups: openArray[string] = [],
    rows: openArray[string] = []
): Loc

The labels of the summary rows, in the stub.

grandSummaryfunc#

func grandSummary(
    _: LocNs,
    columns: ColSel = everything(),
    rows: openArray[string] = []
): Loc

The cells of the grand summary rows.

grandSummaryStubfunc#

func grandSummaryStub(
    _: LocNs,
    rows: openArray[string] = []
): Loc

The labels of the grand summary rows, in the stub.

resolveproc#

proc resolve(l: Loc; t: Tabella): Target

No doc comment yet.

tabStyleproc#

proc tabStyle(
    t: sink Tabella,
    style: CellStyle,
    locations: varargs[Loc]
): Tabella
proc tabStyle(
    t: sink Tabella,
    fn: proc (r: Row): CellStyle,
    locations: varargs[Loc]
): Tabella

Styles the cells at locations: tabStyle(style.fill("#FFF3B0"), loc.body(rows = [2])). A value may come from another column of each row: style.fill(fromColumn("colour")).

an example, from the specs
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

tabFootnoteproc#

proc tabFootnote(
    t: sink Tabella,
    note: Text,
    locations: varargs[Loc]
): Tabella

A note in the footer, marked at each of locations (no location: a plain footnote, no mark).

an example, from the specs
let t = tabella(tavolaPitagorica(3), rownameCol = "×"):
  tabHeader "Tabellina"
  tabFootnote "by heart", loc.title()
echo t
Tabellina1
123
1123
2246
3369
1 by heart

Text

textTransformproc#

proc textTransform(
    t: sink Tabella,
    fn: proc (s: string): string,
    locations: varargs[Loc]
): Tabella

Changes the shown text at locations (by default the body) with a proc: for cells the proc gets the formatted text when the table is rendered (HTML in HTML), for labels and notes their text now. textTransform(toUpperAscii, loc.stub()).

an example, from the specs
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!

textReplaceproc#

proc textReplace(
    t: sink Tabella,
    pattern, replacement: string,
    locations: varargs[Loc]
): Tabella

Replaces every pattern (plain text, not a regex) with replacement.

an example, from the specs
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!

textCaseMatchproc#

proc textCaseMatch(
    t: sink Tabella,
    cases: openArray[(string, string)],
    default = "",
    replace = "all",
    locations: varargs[Loc]
): Tabella

Changes texts by cases, {"old": "new"}: with replace = "all" a text equal to a case becomes its new text (and any other default, when given); with "partial" each case is replaced inside the text. Inside tabella(data): body, also as a block, one pair per line (see tabella): textCaseMatch: then "Gas giant": "giant" and locations = loc.body("type").

an example, from the specs
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!

Columns

colsLabelproc#

proc colsLabel(
    t: sink Tabella,
    column: string,
    label: Text
): Tabella
proc colsLabel(
    t: sink Tabella,
    labels: openArray[(string, string)]
): Tabella
proc colsLabel(
    t: sink Tabella,
    labels: openArray[(string, Text)]
): Tabella

colsLabel({"mass": "Mass", "diameter": "Diameter"}). Inside tabella(data): body, also as a block, one pair per line (see tabella): colsLabel: then mass: "Mass" and diameter: "Diameter".

an example, from the specs
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

colsAlignproc#

proc colsAlign(
    t: sink Tabella,
    align: Align,
    columns: ColSel = everything()
): Tabella

No doc comment yet.

colsWidthproc#

proc colsWidth(
    t: sink Tabella,
    widths: openArray[(string, string)]
): Tabella

CSS widths: colsWidth({"name": "120px", "notes": "30%"}). Inside tabella(data): body, also as a block, one pair per line (see tabella): colsWidth: then name: "120px" and notes: "30%".

colsHideproc#

proc colsHide(
    t: sink Tabella,
    columns: ColSel
): Tabella

No doc comment yet.

an example, from the specs
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

colsUnhideproc#

proc colsUnhide(
    t: sink Tabella,
    columns: ColSel
): Tabella

No doc comment yet.

an example, from the specs
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

colsMoveproc#

proc colsMove(
    t: sink Tabella,
    columns: ColSel,
    after: string
): Tabella

Moves columns (in their given order) right after the column after.

colsLabelWithproc#

proc colsLabelWith(
    t: sink Tabella,
    columns: ColSel,
    fn: proc (s: string): string
): Tabella
proc colsLabelWith(
    t: sink Tabella,
    fn: proc (s: string): string
): Tabella

Relabels columns with a proc over their labels: colsLabelWith(everything(), capitalizeAscii).

an example, from the specs
let t = tabella(tavolaPitagorica(2), rownameCol = "×"):
  colsLabelWith proc (s: string): string = "×" & s
echo t
×1×2
112
224

colsMoveToEndproc#

proc colsMoveToEnd(
    t: sink Tabella,
    columns: ColSel
): Tabella

No doc comment yet.

an example, from the specs
let d = tableData:
  a: [1]
  b: [2]
  c: [3]
  d: [4]
let t = tabella(d):
  colsMoveToEnd "a"
  colsReorder ["d", "b"]
echo t
dcba
4321

colsReorderproc#

proc colsReorder(
    t: sink Tabella,
    columns: ColSel
): Tabella

Puts columns in the given order, in the places they hold: the other columns stay put.

an example, from the specs
let d = tableData:
  a: [1]
  b: [2]
  c: [3]
  d: [4]
let t = tabella(d):
  colsMoveToEnd "a"
  colsReorder ["d", "b"]
echo t
dcba
4321

colsMoveToStartproc#

proc colsMoveToStart(
    t: sink Tabella,
    columns: ColSel
): Tabella

No doc comment yet.

Rows

rowOrderproc#

proc rowOrder(
    t: sink Tabella,
    columns: ColSel,
    reverse = false
): Tabella

Shows the rows sorted by columns (the first decides, the next break ties), within their groups; reverse sorts from high to low. Missing values go last.

an example, from the specs
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

rowGroupOrderproc#

proc rowGroupOrder(
    t: sink Tabella,
    groups: openArray[string]
): Tabella

Shows the row groups in this order; groups not listed follow, as they were.

an example, from the specs
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

Summary rows

aggconst#

agg = ()

No doc comment yet.

sumfunc#

func sum(_: AggNs): Aggregate

The sum of the numbers (an int when they are all ints).

meanfunc#

func mean(_: AggNs): Aggregate

The mean of the numbers.

an example, from the specs
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

medianfunc#

func median(_: AggNs): Aggregate

The median of the numbers (the mean of the two middle ones when they are even).

stdfunc#

func std(_: AggNs): Aggregate

The standard deviation of the numbers, of a sample (divided by n - 1, as R's sd and Polars' std).

minfunc#

func min(_: AggNs): Aggregate

The smallest value (of numbers, or of texts).

maxfunc#

func max(_: AggNs): Aggregate

The largest value (of numbers, or of texts).

countfunc#

func count(_: AggNs): Aggregate

How many values are not missing. Shown as an integer, whatever the column's format.

an example, from the specs
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

aggregateproc#

proc aggregate[P: proc](
    fn: P,
    name = ""
): Aggregate

An aggregate of your own, from a proc of the non-missing values to one value: aggregate(proc (vs: seq[Value]): Value = toValue(vs.len * 2)), or a value that converts to one (proc (vs: seq[Value]): float).

an example, from the specs
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

toFormatFnproc#

proc toFormatFn[P: proc](
    fn: P
): FormatFn

A format from a proc of a float ((x: float) => formatNumber(x, 1)), of a value ((v: Value) => $v), both giving plain text, or a FormatFn as it is.

summaryRowsproc#

proc summaryRows(
    t: sink Tabella,
    fns: openArray[(string, Aggregate)],
    groups: openArray[string] = [],
    columns: ColSel = numeric(),
    side = sBottom,
    missingText = "—"
): Tabella
proc summaryRows[P: proc](
    t: sink Tabella,
    fns: openArray[(string, Aggregate)],
    fmt: P,
    groups: openArray[string] = [],
    columns: ColSel = numeric(),
    side = sBottom,
    missingText = "—"
): Tabella

Adds rows that sum up each row group (or the groups listed), one for each aggregate in fns, labelled in the stub: summaryRows(fns = {"total": agg.sum}, columns = "moons"). Inside tabella(data): body, also as a block, one pair per line (see tabella): summaryRows: then total: agg.sum, columns = "moons" and fmtNumber(decimals = 1) (a fmt* line is fmt). The summary rows go under the group, or above it with side = sTop. Each cell is formatted like its column (its last format), agg.count as an integer; a cell with nothing to sum up, and the columns not in columns, show missingText.

an example, from the specs
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

grandSummaryRowsproc#

proc grandSummaryRows(
    t: sink Tabella,
    fns: openArray[(string, Aggregate)],
    columns: ColSel = numeric(),
    side = sBottom,
    missingText = "—"
): Tabella
proc grandSummaryRows[P: proc](
    t: sink Tabella,
    fns: openArray[(string, Aggregate)],
    fmt: P,
    columns: ColSel = numeric(),
    side = sBottom,
    missingText = "—"
): Tabella

Adds rows that sum up the whole table, every row of every group, one for each aggregate in fns: at the bottom of the table, or at the top with side = sTop. Formatted as summaryRows; a block as in summaryRows: grandSummaryRows: then mean: agg.mean.

an example, from the specs
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

Colour from the data

dataColorproc#

proc dataColor(
    t: sink Tabella,
    columns: ColSel = numeric(),
    rows = allRows(),
    palette: seq[string] = palette("blues"),
    domain = (0x7FF7FFFFFFFFFFFF'f64, 0x7FF7FFFFFFFFFFFF'f64),
    reverse = false,
    naColor = "#F0F0F0",
    autoColorText = true,
    apply = "fill"
): Tabella

Colours cells by value, each column on its own: a number column along palette from the low to the high end of domain (by default the range of its selected cells), any other column by category. A domain from high to low runs the palette the other way. apply = "text" colours the text instead of the fill. The stub is left out, as in Great Tables; palette("great-tables") is Great Tables' default palette.

Options

tabOptionsmacro#

macro tabOptions(
    t: Tabella,
    args: varargs[untyped]
): Tabella

Sets any of TabOptions' fields by name, checked when compiling: t.tabOptions(rowStriping = true, headingAlign = "left").

an example, from the specs
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

optRowStripingproc#

proc optRowStriping(
    t: sink Tabella,
    on = true
): Tabella

No doc comment yet.

optAlignTableHeaderproc#

proc optAlignTableHeader(
    t: sink Tabella,
    align = "left"
): Tabella

No doc comment yet.

optAllCapsproc#

proc optAllCaps(
    t: sink Tabella,
    on = true,
    locations: openArray[string] = [ "column_labels", "stub", "row_group"]
): Tabella

Small capitals (upper case, smaller and bolder) in the column labels, the stub and the row group labels, or only in the locations named, as gt's opt_all_caps(locations = ...).

optTableFontproc#

proc optTableFont(
    t: sink Tabella,
    font: string
): Tabella

The table's font, as a CSS font stack: optTableFont(systemFonts("humanist")).

fontStackNamesconst#

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"]

The names systemFonts knows, in Great Tables' order.

systemFontsfunc#

func systemFonts(
    name = "system-ui"
): string

One of Great Tables' fifteen font stacks, fonts that are on most systems, as CSS text: systemFonts("old-style") is "'Iowan Old Style', 'Palatino Linotype', ..., serif". The names are in fontStackNames; another name raises ValueError.

defaultFontsfunc#

func defaultFonts(): string

gt's default font stack, as CSS text (tabelline's default, tableFontNames, is close to it).

CssThemetype#

CssTheme = object
  ink*, paper*, line*, shade*, primary*, font*: string

Where a table takes its colours and font from (optCssTheme): for each, the name of a CSS variable of the page ("--ink") or a CSS value ("#1C1C1C").

cssThemefunc#

func cssTheme(
    ink = "--ink",
    paper = "--paper",
    line = "--line",
    shade = "--shade",
    primary = "--primary",
    font = "--font"
): CssTheme

A theme to keep and reuse with optCssTheme(theme). Each argument starting with -- names the variable to read; anything else is the CSS value itself.

optCssThemeproc#

proc optCssTheme(
    t: sink Tabella,
    theme: CssTheme
): Tabella
proc optCssTheme(
    t: sink Tabella,
    ink = "--ink",
    paper = "--paper",
    line = "--line",
    shade = "--shade",
    primary = "--primary",
    font = "--font"
): Tabella

Every colour of the table, and its font, from theme: see optCssTheme().

optVerticalPaddingproc#

proc optVerticalPadding(
    t: sink Tabella,
    scale = 1.0
): Tabella

Scales the vertical padding of the heading, the column labels and the rows (gt: 0 to 3).

optHorizontalPaddingproc#

proc optHorizontalPadding(
    t: sink Tabella,
    scale = 1.0
): Tabella

Scales the horizontal padding of the heading, the column labels and the rows (gt: 0 to 3).

optTableOutlineproc#

proc optTableOutline(
    t: sink Tabella,
    style = "solid",
    width = "3px",
    color = "#D3D3D3"
): Tabella

A line all around the table.

optStylizeproc#

proc optStylize(
    t: sink Tabella,
    style = 1,
    color = "blue",
    addRowStriping = true
): Tabella

A ready-made look, gt's and Great Tables' opt_stylize(): style 1 to 6, in one of color "blue", "cyan", "pink", "green", "red", "gray", with stripes unless addRowStriping = false. Styles 2, 4 and 5 draw a light outline around the table; a dark stub gets white text.

optTableLinesproc#

proc optTableLines(
    t: sink Tabella,
    extent = "default"
): Tabella

The table's lines: "all" adds vertical lines between cells, "none" takes every line away, "default" brings back the defaults.

optFootnoteMarksproc#

proc optFootnoteMarks(
    t: sink Tabella,
    marks: FootnoteMarks
): Tabella
proc optFootnoteMarks(
    t: sink Tabella,
    marks: string
): Tabella
proc optFootnoteMarks(
    t: sink Tabella,
    marks: openArray[string]
): Tabella

By gt's names: "numbers", "letters", "LETTERS", "standard" (*, †, ‡, §) or "extended" (with ‖, ¶).

an example, from the specs
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.

optFootnoteSpecproc#

proc optFootnoteSpec(
    t: sink Tabella,
    specRef = "^",
    specFtr = "^"
): Tabella

How marks look, in the table (specRef) and in the footer (specFtr): "^" raised, "i" italic, "b" bold, "(" or "[" around the mark: optFootnoteSpec("^i", "(").

an example, from the specs
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.

optFootnoteOrderproc#

proc optFootnoteOrder(
    t: sink Tabella,
    order = "marks_first"
): Tabella

The order of the footnotes: marked ones first (the default), last ("marks_last"), or as they were added ("preserve_order", which also numbers the marks in that order).

an example, from the specs
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.

optCssproc#

proc optCss(
    t: sink Tabella,
    css: string,
    add = true
): Tabella

CSS for the table, scoped to it (rules that start with # are left as they are); add = false replaces what was given before.

Merges

colsMergeproc#

proc colsMerge(
    t: sink Tabella,
    columns: openArray[string],
    rows = allRows(),
    pattern = "",
    autohide = true
): Tabella

Shows the formatted values of columns together, in the first one, with pattern: {1}, {2}, ... are the columns, and a part between << and >> is left out when a value it names is missing: colsMerge(["city", "country"], pattern = "{1}<< ({2})>>"). Without a pattern the values are joined by spaces. The other columns are hidden (unless autohide = false). A pattern reads the fields of a record too: {2.lo} is the field lo of column 2, and {lo} of column 1, formatted as its column is, so a single column of records can be shown in a pattern: colsMerge(["span"], pattern = "{lo}–{hi}").

an example, from the specs
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

colsMergeUncertproc#

proc colsMergeUncert(
    t: sink Tabella,
    colVal, colUncert: string,
    rows = allRows(),
    sep = " ± ",
    autohide = true
): Tabella

A value and its uncertainty in one cell: 12.3 ± 0.4 (just the value when the uncertainty is missing).

colsMergeRangeproc#

proc colsMergeRange(
    t: sink Tabella,
    colBegin, colEnd: string,
    rows = allRows(),
    sep = "–",
    autohide = true
): Tabella

A range in one cell, with an en dash: 1990–2000 (just the start when the end is missing).

an example, from the specs
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

colsMergeNPctproc#

proc colsMergeNPct(
    t: sink Tabella,
    colN, colPct: string,
    rows = allRows(),
    autohide = true
): Tabella

A count and its percentage in one cell: 12 (4.5%); a zero count shows no percentage. Format the percentage column first (fmtPercent).

Adding columns

colsAddproc#

proc colsAdd(
    t: sink Tabella,
    name: string,
    values: seq[Value],
    before = "",
    after = ""
): Tabella
proc colsAdd[T](
    t: sink Tabella,
    name: string,
    values: openArray[T],
    before = "",
    after = ""
): Tabella
proc colsAdd(
    t: sink Tabella,
    name: string,
    fn: proc (r: Row): Value,
    before = "",
    after = ""
): Tabella

Adds a column: at the end, or before or after another one. colsAdd("ratio", ratios).

an example, from the specs
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

summaryColumnsproc#

proc summaryColumns(
    t: sink Tabella,
    fns: openArray[(string, Aggregate)],
    columns: ColSel = numeric(),
    side = sRight,
    missingText = "—"
): Tabella
proc summaryColumns[P: proc](
    t: sink Tabella,
    fns: openArray[(string, Aggregate)],
    fmt: P,
    columns: ColSel = numeric(),
    side = sRight,
    missingText = "—"
): Tabella

Adds a column for each aggregate in fns, summing up columns across each row: summaryColumns(fns = {"total": agg.sum}, columns = ["gold", "silver", "bronze"]), or as a block (summaryColumns: then total: agg.sum, see tabella), at the right of the table (or at the left of the data with side = sLeft). The new column is formatted like the first column it sums up, or by fmt; summary rows sum it up like any other column, so a table of totals gets its grand total.

an example, from the specs
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

Adding rows

rowsAddproc#

proc rowsAdd(
    t: sink Tabella,
    rows: TableData,
    before = -1,
    after = -1
): Tabella
proc rowsAdd[T: object | tuple](
    t: sink Tabella,
    rows: openArray[T],
    before = -1,
    after = -1
): Tabella

Adds rows, given as a table of some of the columns (the others are missing): at the end, or before or after a row (by its index in the data). A value of groupnameCol puts the row in that group (made when new). rowsAdd(tableData(planet = ["Pluto"], moons = [5])).

an example, from the specs
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

rowsHideproc#

proc rowsHide(
    t: sink Tabella,
    rows: RowSel
): Tabella

Hides rows: they are not shown, nor summed up by summary rows, but stay in the data.

an example, from the specs
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

rowsUnhideproc#

proc rowsUnhide(
    t: sink Tabella,
    rows = allRows()
): Tabella

Shows hidden rows again (all of them, by default).

Stub and alignment

tabStubIndentproc#

proc tabStubIndent(
    t: sink Tabella,
    rows: RowSel,
    indent: int
): Tabella
proc tabStubIndent(
    t: sink Tabella,
    rows: RowSel,
    indent = "increase"
): Tabella

Indents the stub cells of rows at a level from 0 (none) to 5.

an example, from the specs
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

colsAlignDecimalproc#

proc colsAlignDecimal(
    t: sink Tabella,
    columns: ColSel = numeric(),
    decMark = "",
    locale = ""
): Tabella

Aligns the numbers of columns on their decimal mark, by padding each formatted cell on the right with figure spaces (a number without decimals gets a space for the mark, too). The columns are aligned right. The mark is decMark, or the locale's ("." by default).

Rotated labels

colsLabelRotateproc#

proc colsLabelRotate(
    t: sink Tabella,
    columns: ColSel = everything(),
    dir = "sideways-lr"
): Tabella

Turns the labels of columns on their side, for narrow columns: read from the bottom up ("sideways-lr") or from the top down ("sideways-rl"), or slanted at 45 degrees ("slanted", not from gt: a longer label, such as a month's name, in a narrow column). HTML only: text and Markdown keep the labels as they are.

Styles from the data

fromColumnfunc#

func fromColumn(
    column: string,
    naValue = ""
): string

A style value taken, for each cell, from column of the same row: tabStyle(style.fill(fromColumn("colour")), loc.body("name")). A missing value is naValue ("" leaves that property out). Works in any style for body and stub cells.

tabStyleBodyproc#

proc tabStyleBody(
    t: sink Tabella,
    style: CellStyle,
    columns: ColSel = everything(),
    rows = allRows(),
    values: openArray[string] = [],
    pattern = "",
    fn: proc (v: Value): bool = nil,
    targets = "cell"
): Tabella

Styles the body cells whose value is one of values (compared as text, or as numbers), contains pattern, or makes fn true; targets = "row" styles their whole row, "column" their whole column: tabStyleBody(style.fill("var(--x-soft)"), values = ["Earth"]).

Preview

initTabellaPreviewproc#

proc initTabellaPreview(
    data: TableData,
    topN = 5,
    bottomN = 1,
    inclRownums = true,
    moreRows: RowSel = toRowSel(newSeq(Natural(0)))
): Tabella

A preview of a big table: its first topN rows, its last bottomN rows and the rows of moreRows (not from gt: indices from 0, a range, a set such as {12, 40..42}, or where(...)), in their order, with a shaded row for each run of rows left out ("6..99"), and the rows numbered from 1 in the stub (inclRownums), as gt's gt_preview(). A run of one row is shown, not left out. Written tabellaPreview(data, topN = 3), with a body if you like.

Building a table

tabelline/build · src/tabelline/build.nim

Building a table for display: the step every renderer shares, after gt's build_data().

namekind
BuiltRowtype
BuiltSummarytype
BuiltGrouptype
Builttype
cellKeyfunc
colKeyfunc
spannerKeyfunc
groupKeyfunc
summaryKeyfunc
grandKeyfunc
renderTextfunc
renderLabelfunc
columnLabelfunc
formatValueproc
formatCellproc
markTextfunc ×2
wrapMarkfunc
markSpanHtmlfunc
keysOfproc
displayOrderproc
fillPatternfunc ×2
shownCellproc
transformCellproc
buildproc
marksHtmlproc
marksTextproc
footMarkHtmlproc
footMarkTextproc
spannerLevelsfunc
spannerAtfunc
×3: three overloads. A name opens its entry below.
30 names, 15 with a doc comment

It runs the formats and substitutions, puts the rows in display order (groups), places the footnote marks and gathers the styles of every location. The renderers (HTML, text, Markdown) only lay out a Built.

BuiltRowtype#

BuiltRow = object
  index*: int                ## row in the data
  stub*: string              ## the stub cell, formatted ("" without a stub)
  indent*: int               ## indent level of the stub cell (0 to 5)
  levels*: seq[string]       ## the stub's higher levels (`stubCols`), formatted
  spans*: seq[int]           ## how many rows each level spans: 0 when the one above covers it
  cells*: seq[string]        ## formatted cells of the visible data columns

No doc comment yet.

BuiltSummarytype#

BuiltSummary = object
  label*: string             ## the label in the stub, rendered
  key*: string               ## the location key of its stub cell (`summaryKey`)
  cells*: seq[string]        ## formatted cells of the visible data columns
  values*: seq[Value]        ## the values behind them (missing where a column is not summed)

No doc comment yet.

BuiltGrouptype#

BuiltGroup = object
  id*: string
  label*: string ## rendered label ("" for rows outside any group, unless
                 ## `rowGroupDefaultLabel` names them)
  rows*: seq[BuiltRow]
  summaryTop*, summaryBottom*: seq[BuiltSummary] ## the group's summary rows

No doc comment yet.

Builttype#

Built = object
  ctx*: RenderContext
  columns*: seq[ColInfo]     ## visible data columns, in order
  groups*: seq[BuiltGroup]
  grandTop*, grandBottom*: seq[BuiltSummary] ## the grand summary rows
  marks*: Table[string, seq[int]] ## location key -> footnote numbers
  notes*: seq[string]        ## rendered footnotes, by number - 1
  plainNotes*: seq[string]   ## footnotes without a mark
  footer*: seq[(int, string)] ## the footnotes in the order shown: (mark number or 0, text)
  styles*: Table[string, string] ## location key -> CSS

No doc comment yet.

cellKeyfunc#

func cellKey(
    row: int,
    col: string
): string

No doc comment yet.

colKeyfunc#

func colKey(col: string): string

No doc comment yet.

spannerKeyfunc#

func spannerKey(label: string): string

No doc comment yet.

groupKeyfunc#

func groupKey(id: string): string

No doc comment yet.

summaryKeyfunc#

func summaryKey(
    group, label: string,
    col = ""
): string

A cell of a group's summary row (the stub cell when col is "").

grandKeyfunc#

func grandKey(
    label: string,
    col = ""
): string

No doc comment yet.

renderTextfunc#

func renderText(
    t: Text,
    ctx: RenderContext
): string

No doc comment yet.

renderLabelfunc#

func renderLabel(
    t: Text,
    ctx: RenderContext
): string

A label (of a column, a spanner, the stubhead): like renderText, and units between {{ and }} are formatted ("Density, {{kg/m^3}}").

columnLabelfunc#

func columnLabel(
    c: ColInfo,
    ctx: RenderContext,
    unitsPattern = "{1}, {2}"
): string

The label of a column, with its units (colsUnits), placed by the column's pattern or else by unitsPattern (the option columnLabelsUnitsPattern).

formatValueproc#

proc formatValue(
    t: Tabella,
    row: int,
    col: string,
    v: Value,
    ctx: RenderContext
): string

v as the cell at row of col would be formatted: the last format that covers the cell. A missing value is "".

formatCellproc#

proc formatCell(
    t: Tabella,
    row: int,
    col: string,
    ctx: RenderContext
): string

The shown text of one cell: the last format that covers it, then any substitution.

markTextfunc#

func markText(
    n: int,
    marks: FootnoteMarks,
    custom: seq[string] = @[]
): string
func markText(
    n: int,
    o: TabOptions
): string

The mark of footnote n (from 1): numbers, letters, capitals, the four standard symbols (*, †, ‡, §) or six extended ones (with ‖, ¶), or marks of your own; symbols repeat (**) when they run out.

wrapMarkfunc#

func wrapMark(s, spec: string): string

s inside the brackets that spec asks for: "(" gives "(1)", "[" gives "[1]".

markSpanHtmlfunc#

func markSpanHtml(
    s, spec: string
): string

A mark (or marks) as HTML: raised with "^", italic with "i", bold with "b".

keysOfproc#

proc keysOf(
    t: Tabella,
    target: Target,
    columns: seq[ColInfo]
): seq[string]

The location keys a target covers, as the renderers name them.

displayOrderproc#

proc displayOrder(t: Tabella): seq[int]

The rows of the data in the order they are shown (before grouping), without hidden rows.

fillPatternfunc#

func fillPattern(pattern: string;
                 lookup: proc (r: PatternRef): (string, bool)
func fillPattern(
    pattern: string,
    texts: seq[string],
    missing: seq[bool]
): string

pattern with each {...} replaced by lookup (its text, and whether the value is missing); a part in <<...>> is dropped when a value it names is missing (as in gt's cols_merge).

shownCellproc#

proc shownCell(
    t: Tabella,
    row: int,
    col: string,
    ctx: RenderContext
): string

The text of a body cell: merged with other columns (colsMerge) or formatted.

transformCellproc#

proc transformCell(
    t: Tabella,
    row: int,
    col: string,
    shown: string
): string

The shown text of a cell after the text transforms that cover it, in the order given.

buildproc#

proc build(
    t: Tabella,
    ctx: RenderContext
): Built

No doc comment yet.

marksHtmlproc#

proc marksHtml(
    b: Built,
    key: string,
    o: TabOptions
): string

No doc comment yet.

marksTextproc#

proc marksText(
    b: Built,
    key: string,
    o: TabOptions
): string

No doc comment yet.

footMarkHtmlproc#

proc footMarkHtml(
    n: int,
    o: TabOptions
): string

No doc comment yet.

footMarkTextproc#

proc footMarkText(
    n: int,
    o: TabOptions
): string

No doc comment yet.

spannerLevelsfunc#

func spannerLevels(
    t: Tabella,
    columns: seq[ColInfo]
): int

How many rows of spanners sit over the visible columns.

spannerAtfunc#

func spannerAt(
    t: Tabella,
    col: string,
    level: int
): int

The index of the spanner over col at level, or -1.

HTML

tabelline/render_html · src/tabelline/render_html.nim

Rendering to HTML: one <div> holding a <table>, styled by tabellaCss, one stylesheet for every table, with the options the table changes as CSS variables on the <div>.

namekind
nanoplotCssconst
tabellaCsslet
tabellaStylelet
styleVarsproc
toHtmlproc
saveproc
×3: three overloads. A name opens its entry below.
6 names, 5 with a doc comment

(gt and Great Tables write a <style> per table, scoped to its id.) The parts follow gt's layout: the heading and the column labels in <thead>, the row groups, stub and body in <tbody>, footnotes and source notes in <tfoot>. Class names start with tb_ (gt uses gt_).

nanoplotCssconst#

nanoplotCss = """[i] .tb_nanoplot text { font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace; stroke-width: 0.15em; paint-order: stroke; stroke-linejoin: round; cursor: default; }
[i] .tb_nanoplot .vert-line:hover rect { fill: var(--tb-guide); fill-opacity: 40%; stroke: #FFFFFF60; }
[i] .tb_nanoplot .vert-line:hover text, [i] .tb_nanoplot .horizontal-line:hover text, [i] .tb_nanoplot .ref-line:hover text, [i] .tb_nanoplot .boxplot-line:hover text { stroke: white; fill: #212427; }
[i] .tb_nanoplot .ref-line:hover rect { stroke: #FFFFFF60; }
[i] .tb_nanoplot .ref-line:hover line { stroke: #FF0000; }
[i] .tb_nanoplot .y-axis-line:hover rect { fill: #EDEDED; fill-opacity: 60%; stroke: #FFFFFF60; }
[i] .tb_nanoplot .y-axis-line:hover text { stroke: white; stroke-width: 0.20em; fill: #1A1C1F; }
[i] .tb_nanoplot_static .vert-line text, [i] .tb_nanoplot_static .horizontal-line text, [i] .tb_nanoplot_static .ref-line text, [i] .tb_nanoplot_static .boxplot-line text { stroke: white; fill: #212427; }
[i] .tb_nanoplot_static .y-axis-line rect { fill: #EDEDED; fill-opacity: 60%; }
[i] .tb_nanoplot_static .y-axis-line text { stroke: white; stroke-width: 0.20em; fill: #1A1C1F; }
"""

No doc comment yet.

tabellaCsslet#

tabellaCss = tabellaCssValue & themeRule()

The CSS of every table, the same for all of them: each value is a CSS variable named after its option (--tb-table-font-size for tableFontSize), falling back to the default. A table sets the variables of the options it changes on its <div> (toHtml); a page can set one for all its tables (.tabella { --tb-table-font-size: 14px }). A table that takes the page's theme (optCssTheme()) gets the class tb_css_theme, whose rule here sets the theme's variables once for all of them.

tabellaStylelet#

tabellaStyle = "<style>\n" & tabellaCss & "</style>"

tabellaCss in a <style> element, as toHtml writes it.

styleVarsproc#

proc styleVars(o: TabOptions): string

The variables of the options o changes, for the style of the table's <div>: changed from the defaults, or from optCssTheme() for a table that takes it (isThemed).

toHtmlproc#

proc toHtml(
    t: Tabella,
    makePage = false,
    withStyle = true
): string

The table as an HTML fragment (a <div> holding the <table>), ready to put in a page. With withStyle = true the fragment starts with tabellaCss in a <style>, so it works alone; with false it leaves it out, for a page that writes tabellaCss once for all its tables (nbTable does). With makePage = true, a whole standalone page holding it, titled after the table, as Great Tables' as_raw_html(make_page = True).

an example, from the specs
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

saveproc#

proc save(t: Tabella; path: string)

Writes the table as a standalone HTML page, as gt's gtsave("x.html").

Text and Markdown

tabelline/render_text · src/tabelline/render_text.nim

Rendering to plain text (box drawing, for terminals and echo) and to Markdown (a GitHub pipe table, for nimib's Markdown backend and READMEs).

namekind
toTextproc
$proc
toMarkdownproc
×3: three overloads. A name opens its entry below.
3 names, 3 with a doc comment

Both use the same built table as HTML, so the formats, groups and footnote marks agree.

toTextproc#

proc toText(t: Tabella): string

The table drawn with box characters, like a dataframe printed at the console, but with the formats, the stub, the groups and the notes.

$proc#

proc `$`(t: Tabella): string

echo t draws the table.

toMarkdownproc#

proc toMarkdown(t: Tabella): string

A GitHub-flavoured Markdown table, with the title above and the notes below. Spanners and group headings, which pipe tables cannot hold, become a line of text.

Reading a table back

tabelline/extract · src/tabelline/extract.nim

The built table as data: what a reader sees, cell by cell, as gt's extract_body(), extract_cells() and extract_summary() give it.

namekind
extractCellsproc
extractBodyproc
extractSummaryproc
×3: three overloads. A name opens its entry below.
3 names, 3 with a doc comment

extractCellsproc#

proc extractCells(
    t: Tabella,
    columns: ColSel,
    rows = allRows(),
    ctx = rcText
): seq[ string]

The shown text of the body cells of columns and rows, column by column, each in the order the table shows its rows: extractCells(t, "mass"). ctx = rcHtml gives HTML.

an example, from the specs
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

extractBodyproc#

proc extractBody(
    t: Tabella,
    ctx = rcText
): TableData

The body as a table of texts, in the order shown: a column group (when the table has row groups), the stub (rowname, when it has one) and every visible column, with the formats, merges and substitutions applied.

extractSummaryproc#

proc extractSummary(
    t: Tabella,
    ctx = rcText,
    values = false
): TableData

The summary rows as a table of texts: group ("" for a grand summary row), label, and a cell for each visible column, as shown; with values = true the values themselves, as gt's extract_summary() gives them (missing where a column is not summed).

an example, from the specs
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

Pictures

tabelline/pictures · src/tabelline/pictures.nim

Pictures in cells: icons and images, drawn without loading anything remote.

namekind
Icons
Icontype
findIconproc
hasIconproc
iconproc
iconSvgproc
fmtIconproc
Images
imageDataUrlproc
fmtImageproc
localImageproc
webImageproc
×3: three overloads. A name opens its entry below.
10 names, 10 with a doc comment

Icons

Icontype#

Icon = object
  name*, style*, label*, path*: string
  width*: int

A Font Awesome icon: its name, style ("solid", "regular" or "brands"), label and drawing (an SVG path on a canvas width wide and 512 high).

findIconproc#

proc findIcon(
    name: string
): (bool, Icon)

The icon for a name: a short name ("star", the regular style when there are two), a full name ("fas fa-star", "fa-solid fa-star") or an older name ("user-large" is "user").

hasIconproc#

proc hasIcon(name: string): bool

Whether name is a Font Awesome Free icon (see findIcon).

an example, from the specs
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

iconproc#

proc icon(name: string): Icon

The icon for a name (see findIcon); raises ValueError for an unknown one.

an example, from the specs
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

iconSvgproc#

proc iconSvg(
    name: string,
    height = "1em",
    fill = "",
    fillAlpha = NaN,
    stroke = "",
    strokeWidth = "",
    strokeAlpha = NaN,
    marginLeft = "",
    marginRight = "",
    verticalAlign = "-0.125em",
    title = "",
    a11y = "semantic"
): string

An icon as inline SVG, height high and as wide as its shape: iconSvg("star"). The fill is the text's colour unless fill is given. With a11y = "semantic" a screen reader reads its label (or title), with "decorative" it skips it, with "none" nothing is added.

fmtIconproc#

proc fmtIcon(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    height = "1em",
    sep = " ",
    strokeColor = "",
    strokeWidth = "",
    strokeAlpha = NaN,
    fillColor = "",
    fillColors: openArray[(string, string)] = [],
    fillAlpha = NaN,
    marginLeft = "",
    marginRight = "",
    a11y = "semantic"
): Tabella

Names of Font Awesome Free icons as icons: "star", or several, in a list or separated by commas ("hard-drive, clock"), joined by sep. fillColor colours them all, fillColors by name ({"circle-check": "green"}); by default they take the colour of the text. In text output the names stay. An unknown name raises ValueError here, not when the table is rendered.

an example, from the specs
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

Images

imageDataUrlproc#

proc imageDataUrl(file: string): string

A file as a data URL, its type from its extension: imageDataUrl("moon.png") is "data:image/png;base64,...". Raises ValueError for a file that is not there.

fmtImageproc#

proc fmtImage(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    height = "",
    width = "",
    sep = " ",
    path = "",
    filePattern = "{x}",
    encode = true,
    alt = ""
): Tabella

File names as images: each cell holds one or more names (a list, or separated by commas), found in path and written with filePattern ("{x}.png" for a cell "moon"). With encode (the default) a local file is read now and inlined as a data URL, so the page needs nothing else; an address (https://...) is left as it is. Without height or width an image is 2em high. alt is the text a screen reader reads ("{x}" is the name); by default the name. In text output the names stay.

an example, from the specs
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

localImageproc#

proc localImage(
    file: string,
    height = "2em",
    alt = ""
): Text

A local image as Text, for a title, a label, a note or a cell of fmtMarkdown: the file is read now and inlined as a data URL, as gt's local_image(). alt (by default the file's name) is what a screen reader reads, and what text output shows.

webImageproc#

proc webImage(
    url: string,
    height = "2em",
    alt = ""
): Text

An image on the web as Text, the address left as it is (the page loads it), as gt's web_image(). alt is by default the last part of the address.

an example, from the specs
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

Nanoplots

tabelline/nanoplots · src/tabelline/nanoplots.nim

Nanoplots: tiny plots in cells, as inline SVG, after Great Tables' fmt_nanoplot() and gt's cols_nanoplot() (ported from Great Tables' _utils_nanoplots.py, MIT, licenses/great-tables-MIT.txt).

namekind
NanoplotOptionstype
atfunc
nanoplotOptionsfunc
The values
nanoplotValuesfunc
nanoplotXValuesproc
plotTypesconst
refKeywordsconst
The labels
nanoplotLabelproc
Shapes
shapeSidefunc
nanoplotSummaryproc
nanoplotSvgproc
In text
nanoplotTextproc
The verbs
fmtNanoplotproc
colsNanoplotproc
×3: three overloads. A name opens its entry below.
14 names, 13 with a doc comment

A cell with several values ("20 23 6.7", or "1, 2, NA") is a line plot, a bar plot or a box plot; a cell with one number is a horizontal bar or line from a zero line shared by all the rows. The values show when the pointer is over the plot (no JavaScript: CSS :hover). In text output a nanoplot is a sparkline ("▁▃▅█").

NanoplotOptionstype#

NanoplotOptions = object
  dataPointRadius*: seq[float] ## one value, or one per point (repeating)
  dataPointStrokeColor*, dataPointFillColor*: seq[string]
  dataPointStrokeWidth*: seq[float]
  dataLineStrokeColor*: string
  dataLineStrokeWidth*: float
  dataLineType*: string
  dataAreaFillColor*: string
  dataBarStrokeColor*, dataBarFillColor*: seq[string] ## one value, or one per bar
  dataBarStrokeWidth*: seq[float]
  dataBarNegativeStrokeColor*, dataBarNegativeFillColor*: string
  dataBarNegativeStrokeWidth*: float
  referenceLineColor*, referenceAreaFillColor*: string
  verticalGuideStrokeColor*: string
  verticalGuideStrokeWidth*: float
  showDataPoints*, showDataLine*, showDataArea*, showReferenceLine*,
  showReferenceArea*, showVerticalGuides*, showYAxisGuide*,
  interactiveDataValues*: bool
  currency*: string
  yValFmtFn*, yAxisFmtFn*, yRefLineFmtFn*: proc (x: float): string

The look of a nanoplot, after Great Tables' nanoplot_options() (see nanoplotOptions).

atfunc#

func at[T](s: seq[T]; i: int): T

The value of a per-point option for point i: the list repeats.

nanoplotOptionsfunc#

func nanoplotOptions(
    dataPointRadius: SomeNumber | seq[float] | seq[int] = 10.0,
    dataPointStrokeColor: string | seq[string] = "#FFFFFF",
    dataPointStrokeWidth: SomeNumber | seq[float] | seq[int] = 4.0,
    dataPointFillColor: string | seq[string] = "#FF0000",
    dataLineType = "curved",
    dataLineStrokeColor = "#4682B4",
    dataLineStrokeWidth = 8.0,
    dataAreaFillColor = "#FF0000",
    dataBarStrokeColor: string | seq[string] = "#3290CC",
    dataBarStrokeWidth: SomeNumber | seq[float] | seq[int] = 4.0,
    dataBarFillColor: string | seq[string] = "#3FB5FF",
    dataBarNegativeStrokeColor = "#CC3243",
    dataBarNegativeStrokeWidth = 4.0,
    dataBarNegativeFillColor = "#D75A68",
    referenceLineColor = "#75A8B0",
    referenceAreaFillColor = "#A6E6F2",
    verticalGuideStrokeColor = "#911EB4",
    verticalGuideStrokeWidth = 12.0,
    showDataPoints = true,
    showDataLine = true,
    showDataArea = true,
    showReferenceLine = true,
    showReferenceArea = true,
    showVerticalGuides = true,
    showYAxisGuide = true,
    interactiveDataValues = true,
    currency = "",
    yValFmtFn: proc (x: float): string = nil,
    yAxisFmtFn: proc (x: float): string = nil,
    yRefLineFmtFn: proc (x: float): string = nil
): NanoplotOptions

No doc comment yet.

an example, from the specs
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

The values

nanoplotValuesfunc#

func nanoplotValues(
    v: Value
): seq[float]

The values of a nanoplot cell: a number, a list of numbers (@[1, 4, 2]), a record with the values in y (and their places in x, see nanoplotXValues), or a text of numbers separated by spaces, commas or semicolons, maybe in brackets ("[1, 2, NA]"); NA (or nan) is a missing value, NaN.

nanoplotXValuesproc#

proc nanoplotXValues(
    v: Value
): seq[float]

The places of the values on the x axis: the field x of a record ((x: @[1, 2, 4], y: @[3, 5, 4]), Great Tables' dict of x and y), numbers or ISO dates and times (@["2026-01-05", "2026-02-11"], placed by time); empty for any other cell, whose values are evenly spaced.

an example, from the specs
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

plotTypesconst#

plotTypes = ["line", "bar", "boxplot", "shape"]

The kinds of nanoplot: "shape" is tabelline's, not Great Tables'.

refKeywordsconst#

refKeywords = ["mean", "median", "min", "max", "q1", "q3", "first", "last"]

The keywords of a reference line or area: a statistic of the values.

The labels

nanoplotLabelproc#

proc nanoplotLabel(
    x: float,
    asInteger = false,
    currency = "",
    fn: proc (x: float): string = nil
): string

A value as a nanoplot writes it, short, as Great Tables does: "0", integers below 100 as they are, 3 significant figures ("2.50", "123"), K, M, B and T from a thousand ("1.23K"), and "1.2E−3" for the tiny and the huge; with a currency, money ("$12.50", "€1.2K").

an example, from the specs
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

Shapes

shapeSidefunc#

func shapeSide(y, x: seq[float]): float

The side of the square a shape fills: its width or its height, the larger.

an example, from the specs
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

nanoplotSummaryproc#

proc nanoplotSummary(
    y: seq[float],
    plotType: string,
    single = false
): string

The values in words, for a screen reader: "Line plot of 8 values from 12 to 47, ending at 30".

nanoplotSvgproc#

proc nanoplotSvg(
    y: seq[float],
    plotType = "line",
    height = "2em",
    missingVals = "gap",
    referenceLine = "",
    referenceArea = ("", ""),
    expandY: seq[float] = @[],
    all: seq[float] = @[],
    single = false,
    options = nanoplotOptions(),
    alt = "",
    x: seq[float] = @[],
    expandX: seq[float] = @[],
    side = 0.0,
    referenceX: seq[(float, string)] = @[],
    sharedCount = 0
): string

One nanoplot as inline SVG: a line, bar or box plot of the values y (NaN for a missing one), or with single a horizontal bar or line for y[0], on the scale of all (the values of every row: single values and box plots share their scale). "" when there is nothing to plot. alt is read by a screen reader ("{x}" is a summary of the values). With x (as many as y) a line plot puts each value at its place on an x axis that also includes expandX; a bar plot and a box plot leave x out. A "shape" joins the points (x, y) in their order and closes them, at the same scale across and up, in a square

In text

nanoplotTextproc#

proc nanoplotText(
    y: seq[float],
    plotType = "line",
    missingVals = "gap",
    all: seq[float] = @[],
    single = false,
    expandY: seq[float] = @[],
    options = nanoplotOptions()
): string

A nanoplot in text: a sparkline of the values ("▁▃▅█ 1–9", on the axis of expandY too), a bar of blocks for a single value, left of a zero line when it is negative ("███│ −4", "│█ 2"), the five numbers of a box plot ("1 ┤2 │3│ 5├ 9").

The verbs

fmtNanoplotproc#

proc fmtNanoplot(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    plotType = "line",
    plotHeight = "2em",
    missingVals = "gap",
    autoscale = false,
    referenceLine = "",
    referenceArea = ("", ""),
    expandY: seq[float] = @[],
    options = nanoplotOptions(),
    alt = "",
    expandX: seq[float] = @[],
    referenceX: seq[string] = @[]
): Tabella

Nanoplots of the values in each cell (see nanoplotValues: a list, a record of x and y, or a text of numbers): a line plot ("line"), a bar plot ("bar") or a box plot ("boxplot"). A numeric column gets one horizontal bar or line per row, from a zero line shared by the rows. referenceLine is a number ("10") or a statistic of the cell's values ("mean", "median", "min", "max", "q1", "q3", "first", "last"), and referenceArea two of them. missingVals says what a missing value does: "gap" breaks the line, "marker" marks it, "zero" counts it as 0, "remove" leaves it out. With autoscale

an example, from the specs
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

colsNanoplotproc#

proc colsNanoplot(
    t: sink Tabella,
    columns: ColSel,
    rows = allRows(),
    plotType = "line",
    plotHeight = "2em",
    missingVals = "gap",
    autoscale = false,
    referenceLine = "",
    referenceArea = ("", ""),
    expandY: seq[float] = @[],
    newColName = "nanoplots",
    newColLabel = "",
    before = "",
    after = "",
    autohide = true,
    options = nanoplotOptions(),
    alt = "",
    xVals: seq[float] = @[],
    referenceX: seq[string] = @[]
): Tabella

A new column of nanoplots, one per row, of the values of several columns (in their order): after gt's cols_nanoplot(). The columns are hidden (autohide); the new one is newColName, labelled newColLabel (its name by default), at the end or before or after a column. xVals (not from gt) places the columns on the x axis, one value each, the same in every row (the years of y2006 ... y2025): then referenceX draws a dashed vertical line at a place of that axis. The other arguments are those of fmtNanoplot.

an example, from the specs
let t = tabella(tavolaPitagorica(4), rownameCol = "×"):
  colsNanoplot ["1", "2", "3", "4"], newColLabel = "the row", autoscale = true
echo t
the row
11611234
21612468
316136912
4161481216

Everything at once

tabelline · src/tabelline.nim · import tabelline brings every module above.

Great tables for Nim.

namekind
tabellamacro
tabellaPreviewmacro
tableDatamacro
×3: three overloads. A name opens its entry below.
3 names, 3 with a doc comment

tabelline: great tables for Nim.

Display tables built from parts (a header, a stub, spanners, column labels, the body, a footer), with formatted values and styles, rendered to HTML (and to text and Markdown). Inspired by R's gt and Python's Great Tables, written in plain Nim.

import tabelline
let t = tabella(planets, rownameCol = "planet", groupnameCol = "type"):
  tabHeader "The planets", "of the Solar System"
  tabSpanner "Size", ["diameter", "mass"]
  fmtNumber "mass", decimals = 3
  dataColor "moons", palette = palette("pastelli")
echo t          # a text table
t.save "planets.html"

Two macros, where plain procs cannot do the job: tabella(data): body, which reads each line of body as a verb applied to the table (no chaining dots needed, and a verb that takes a list of pairs may take them as an indented block, one per line), and tableData:, which reads columns as name: [values], with nil for a missing value.

tabellamacro#

macro tabella(
    args: varargs[untyped]
): untyped

tabella(data, rownameCol = "name") is a table for data (see initTabella), and with a body, tabella(data): body is that table changed by the verbs in body, one per line, without repeating the table: tabHeader "Title" stands for t = t.tabHeader("Title").

A verb in body may end with an indented block. In a verb whose first argument is a list of pairs (colsLabel, colsWidth, colsUnits, textCaseMatch, summaryRows, grandSummaryRows, summaryColumns) a line label: value is a pair; in any verb a line name = value is a named argument; in a summary verb a line fmtNumber(decimals = 1) is fmt = (x: float) => formatNumber(x, decimals = 1); tabOptions: takes name = value:

an example, from the specs
let d = tableData:
  country: ["IT", "JPN", "FR,DE"]
let t = tabella(d):
  fmtFlag "country"
echo t
country
🇮🇹
🇯🇵
🇫🇷 🇩🇪

tabellaPreviewmacro#

macro tabellaPreview(
    args: varargs[untyped]
): untyped

tabellaPreview(data, topN = 5, bottomN = 1) is a preview of a big table (see initTabellaPreview), and with a body it is changed by the verbs in the body, as in tabella:

let t = tabellaPreview(citta(), topN = 3):
  fmtInteger "population"
an example, from the specs
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

tableDatamacro#

macro tableData(
    body: untyped
): TableData

Columns as name: [values] lines, each value converted on its own, so a column can mix numbers with nil (missing). A name can have dots, size.mass: [...], or be quoted. Values can be any list, such as a collect. A for (or if) adds the columns in its body, and their names can be computed: $j: [...], or any expression in parentheses.

let d = tableData:
  planet: ["Mercury", "Venus"]
  moons: [0, nil]
let tavola = tableData:
  `×`: collect(for i in 1 .. 3: i)
an example, from the specs
let d = tableData:
  country: ["IT", "JPN", "FR,DE"]
let t = tabella(d):
  fmtFlag "country"
echo t
country
🇮🇹
🇯🇵
🇫🇷 🇩🇪

Datasets

tabelline/datasets · src/tabelline/datasets.nim · import tabelline/datasets: small tables for examples.

Small datasets for examples and tests, built into the module (no files to find at run time).

namekind
planetsCsvconst
exibbleCsvconst
isoleCsvconst
cittaCsvconst
gtcarsproc
countrypopsproc
illnessproc
metroproc
planetsproc
exibbleproc
isoleproc
cittaproc
tavolaPitagoricaproc
×3: three overloads. A name opens its entry below.
13 names, 8 with a doc comment

The data of isole and citta is in data/ (CSV, with its source in a # line), read when compiling; docs/devlog/data/datasets/ has the programs that wrote it.

planetsCsvconst#

planetsCsv = """planet,type,mass,diameter,density,gravity,day_length,distance,orbital_period,mean_temp,moons,rings
Mercury,Terrestrial,0.330,4879,5429,3.7,4222.6,57.9,88.0,167,0,false
Venus,Terrestrial,4.87,12104,5243,8.9,2802.0,108.2,224.7,464,0,false
Earth,Terrestrial,5.97,12756,5514,9.8,24.0,149.6,365.2,15,1,false
Mars,Terrestrial,0.642,6792,3934,3.7,24.7,228.0,687.0,-65,2,false
Jupiter,Gas giant,1898,142984,1326,23.1,9.9,778.5,4331,-110,95,true
Saturn,Gas giant,568,120536,687,9.0,10.7,1432.0,10747,-140,146,true
Uranus,Ice giant,86.8,51118,1270,8.7,17.2,2867.0,30589,-195,28,true
Neptune,Ice giant,102,49528,1638,11.0,16.1,4515.0,59800,-200,16,true
"""

Units: mass 10^24 kg, diameter km, density kg/m³, gravity m/s², day length hours, distance from the Sun 10^6 km, orbital period days, mean temperature °C. Known moons as

exibbleCsvconst#

exibbleCsv = """num,char,fctr,date,time,datetime,currency,row,group
0.1111,apricot,one,2015-01-15,13:35,2018-01-01 02:22,49.95,row_1,grp_a
2.222,banana,two,2015-02-15,14:40,2018-02-02 14:33,17.95,row_2,grp_a
33.33,coconut,three,2015-03-15,15:45,2018-03-03 03:44,1.39,row_3,grp_a
444.4,durian,four,2015-04-15,16:50,2018-04-04 15:55,65100,row_4,grp_a
5550,,five,2015-05-15,17:55,2018-05-05 04:00,1325.81,row_5,grp_b
,fig,six,2015-06-15,,2018-06-06 16:11,13.255,row_6,grp_b
777000,grapefruit,seven,,19:10,2018-07-07 05:22,,row_7,grp_b
8880000,honeydew,eight,2015-08-15,20:20,,0.44,row_8,grp_b
"""

No doc comment yet.

isoleCsvconst#

isoleCsv = "# Islands of the Mediterranean by area: Wikipedia, List of islands in the Mediterranean, read 8 Nov 2026 by isole.nim\nisland,country,area,population,city\nSicily,Italy,25834,5010001,Palermo\nSardinia,Italy,24100,1656000,Cagliari\nCyprus,Cyprus,9251,,Nicosia\nCorsica,France,8681,322000,Ajaccio\nCrete,Greece,8312,622871,Heraklion\nEuboea,Greece,3655,191206,Chalcis\nMallorca,Spain,3640,846000,Palma\nLesbos,Greece,1630,86436,Mytilene\nRhodes,Greece,1398,115490,Rhodes\nChios,Greece,842,51390,Chios\nCephalonia,Greece,781,35801,Argostoli\nMenorca,Spain,694,87000,Mahón\nCorfu,Greece,592,100853,Corfu\nIbiza,Spain,577,111000,Ibiza Town\nDjerba,Tunisia,523,139544,Houmt Souk\nLemnos,Greece,476,16992,Myrina\nSamos,Greece,476,32973,Vathy\nNaxos,Greece,428,17970,Naxos\nZakynthos,Greece,406,40758,Zakynthos\nCres,Croatia,405.78,3079,Cres\nKrk,Croatia,405.78,19383,Krk\nBrač,Croatia,394.57,13956,Supetar\nAndros,Greece,380,9221,Andros\nThasos,Greece,379,13765,Thasos\nLefkada,Greece,303,22076,Lefkada\nKarpathos,Greece,301,6181,Pigadia\nHvar,Croatia,299.66,11077,Hvar\nKos,Greece,290,33388,Kos\nPag,Croatia,284.56,9059,Pag\nGökçeada,Turkey,279,8894,Çınarlı\nKythira,Greece,278,3973,Kythira\nKorčula,Croatia,276.03,15522,Korčula\nIcaria,Greece,255,8423,Agios Kirykos\nMalta,Malta,246,409259,Valletta\nElba,Italy,224,31572,Portoferraio\nSkyros,Greece,209,2994,Skyros\nParos,Greece,196,13715,Parikia\nTinos,Greece,194,8636,Tinos\nSamothrace,Greece,178,2859,Samothrace\nMilos,Greece,160,4977,Plaka\nKea,Greece,129,2446,Ioulis\nAmorgos,Greece,121,1971,Amorgos\nMarmara,Turkey,117,,\nDugi Otok,Croatia,114.44,1655,Sali\nKalymnos,Greece,111,16001,Pothia\nChergui,Tunisia,110,,\nSant\'Antioco,Italy,109,11730,Sant\'Antioco\nIos,Greece,109,2024,Ios\nMljet,Croatia,100.41,1088,Babino Polje\nKythnos,Greece,100,1456,Kythnos\nAstypalaia,Greece,97,1334,Astypalaia\nIthaca,Greece,96,3231,Vathy\nSkopelos,Greece,95.5,4960,Skopelos\nSalamis,Greece,95,39283,Salamina\nRab,Croatia,90.84,9328,Rab\nVis,Croatia,90.26,3445,Vis\nMykonos,Greece,86,10120,Mykonos\nSyros,Greece,84,21505,Ermoupoli\nAegina,Greece,83,13056,Aegina\nFormentera,Spain,83,7461,Sant Francesc Xavier\nPantelleria,Italy,83,7729,Pantelleria\nSantorini,Greece,76,15230,Fira\nLošinj,Croatia,74.68,7587,Mali Lošinj\nSerifos,Greece,73,1420,Serifos\nSifnos,Greece,73,2625,Apollonia\nGharbi,Tunisia,69,,\nGozo,Malta,67,37288,Victoria\nKasos,Greece,66,1084,Fry\nAlonissos,Greece,64,2712,Patitiri\nTilos,Greece,63,780,Megálo Chorió\nPašman,Croatia,63.34,2845,Pašman\nŠolta,Croatia,58.98,1700,Grohote\nSymi,Greece,58,2590,Symi\nLeros,Greece,53,7907,Agia Marina\nSan Pietro,Italy,51,6444,Carloforte\nAsinara,Italy,51,1,Cala d\'Oliva\nHydra,Greece,50,1948,Hydra\nUgljan,Croatia,50.21,6049,Preko\nSkiathos,Greece,48,6088,Skiathos\nLastovo,Croatia,46.87,792,Lastovo\nIschia,Italy,46,60335,Ischia\nAgios Efstratios,Greece,43,270,Agios Efstratios\nNisyros,Greece,41,987,Mandraki\nSikinos,Greece,41,273,Sikinos\nPsara,Greece,40,454,Psara\nAnafi,Greece,38,271,Anafi\nLipari,Italy,37,10763,Lipari\nBozcaada,Turkey,36,2427,Bozcaada\nKimolos,Greece,36,908,Kimolos\nAntiparos,Greece,35,1211,Antiparos\nPatmos,Greece,35,2998,Patmos\nKornat,Croatia,32.30,19,\nFolegandros,Greece,32,765,Folegandros\nFourni,Greece,30,1313,Fourni\nGavdos,Greece,29.6,152,Kastri\nČiovo,Croatia,28.80,5908,Okrug Gornji\nHalki,Greece,28.1,478,Halki\nSalina,Italy,26.8,2300,Malfa\nOlib,Croatia,26.09,140,Olib\nUzunada,Turkey,25.4,,\nPaxi,Greece,25.3,2280,Gaios\nKalamos,Greece,25,496,Kalamos\nKyra Panagia,Greece,25,2,\nGiglio,Italy,23.8,1458,\nCunda (Alibey),Turkey,23.4,,\nPoros,Greece,22.9,3993,Poros\nMolat,Croatia,22.82,197,Molat\nVir,Croatia,22.38,3000,Vir\nSpetses,Greece,22.2,4027,Spetses\nPaşalimanı,Turkey,21.4,,\nSaria,Greece,21.1,45,\nVulcano,Italy,20.9,715,Vulcano\nAvsa,Turkey,20.6,,\nAntikythera,Greece,20.4,68,Potamós\nLampedusa,Italy,20.2,4500,Lampedusa e Linosa\nLa Maddalena,Italy,20.1,11902,La Maddalena\nMeganisi,Greece,20,1040,Katomeri\nFavignana,Italy,19,4383,Favignana\nCapraia,Italy,19,410,Capraia\nElafonisos,Greece,19,1024,Elafonisos\nMurter,Croatia,18.60,4895,Murter\nMakronisos,Greece,18.3,9,\nIrakleia,Greece,17.6,141,Irakleia\nIž,Croatia,17.59,615,Iž Veli\nGyaros,Greece,17.3,0,\nMegalonisos Petalion,Greece,17.2,0,\nPolyaigos,Greece,17.2,2,\nUnije,Croatia,16.92,88,Unije\nLeipsoi,Greece,16,790,Leipsoi\nŠipan,Croatia,15.81,419,Šipanska Luka\nCaprera,Italy,15.7,0,\nCabrera,Spain,15.7,0,\nKeros,Greece,15.2,0,\nŽirje,Croatia,15.06,103,Žirje\nSestrunj,Croatia,15.03,48,Sestrunj\nSilba,Croatia,14.98,292,Silba\nŽut,Croatia,14.82,0,\nPserimos,Greece,14.8,80,Pserimos\nOinousses,Greece,14.4,826,Oinousses\nPeristera,Greece,14.2,30,\nRineia,Greece,13.7,0,\nAgathonisi,Greece,13.6,185,Megálo Chorió\nDonoussa,Greece,13.6,167,Donoussa (Stavros)\nPrvic (Krk),Croatia,13.5,0,\nStromboli,Italy,12.6,572,San Vincenzo\nDokos,Greece,12.5,18,Dokos\nPorquerolles,France,12.5,200,\nSchiza,Greece,12.3,0,\nDrvenik Veliki,Croatia,12.1,168,Drvenik Veliki\nMarettimo,Italy,12,819,Marettimo\nAgistri,Greece,12,1142,Milos (Megalohori)\nDia,Greece,11.8,0,\nGioura,Greece,11.1,0,\nCapri,Italy,10.4,12200,Capri\nMontecristo,Italy,10.4,2,\nPianosa,Italy,10.3,10,\nOthonoi,Greece,10.1,392,Othonoi\nThymaina,Greece,10.1,143,Thymaina\nImrali,Turkey,10,,\nIst,Croatia,9.65,202,\nFilicudi,Italy,9.5,235,\nTherasia,Greece,9.3,319,\nKastellorizo,Greece,9.1,492,\nLevitha,Greece,9.1,0,\nSapientza,Greece,9.1,2,\nKara Ada,Turkey,9,,\nPremuda,Croatia,8.7,58,\nUstica,Italy,8.7,1302,\nPlavnik,Croatia,8.6,0,\nMaun,Croatia,8.5,0,\nŠćedro,Croatia,8.4,0,\nZlarin,Croatia,8.1,276,\nSchoinousa,Greece,8.1,227,\nAntimilos,Greece,8,0,\nSyrna,Greece,7.9,0,\nDespotiko,Greece,7.8,0,\nAmmouliani,Greece,7.7,541,\nPonza,Italy,7.5,3107,\nAlimia,Greece,7.4,0,\nLa Galite,,7.3,,0\nKaprije,Croatia,7.1,143,\nPort-Cros,France,7,30,\nArkoi,Greece,6.7,44,\nSveti Grgur,Croatia,6.4,0,\nSkantzoura,Greece,6.2,0,\nBiševo,Croatia,5.9,15,\nKastos,Greece,5.9,80,\nTavolara,Italy,5.9,0,\nLevanzo,Italy,5.8,208,\nPano Koufonisi,Greece,5.8,399,\nSazan Island,Albania,5.7,0,\nVeliki Brijun,Croatia,5.7,0,\nIlovik,Croatia,5.5,85,\nPetalas,Greece,5.5,0,\n"

island, country, area (km²), population, city (the largest). Wikipedia, "List of islands in the Mediterranean", read 8 Nov 2026.

cittaCsvconst#

cittaCsv = "# EU cities by population within city limits: Wikipedia, read 8 Nov 2026 by citta.nim\ncity,state,population,counted\nBerlin,GER,3913644,2025-12-31\nMadrid,ESP,3506730,2025-01-01\nRome,ITA,2745062,2026-01-01\nParis,FRA,2047602,2026-01-01\nVienna,AUT,2044366,2026-04-01\nHamburg,GER,1869786,2026-03-31\nWarsaw,POL,1866729,2025-12-31\nBarcelona,ESP,1731649,2025-01-01\nBucharest,ROU,1709458,2025-01-01\nBudapest,HUN,1675777,2026-01-01\nMunich,GER,1505036,2025-12-31\nPrague,CZE,1405551,2026-03-31\nMilan,ITA,1362863,2026-01-01\nSofia,BUL,1303813,2025-12-31\nCologne,GER,1025523,2025-12-31\nStockholm,SWE,1000962,2026-06-30\nAmsterdam,NLD,945870,2026-06-30\nNaples,ITA,905050,2026-01-01\nMarseille,FRA,890707,2024-01-01\nTurin,ITA,855654,2026-01-01\nValencia,ESP,840792,2025-01-01\nKraków,POL,816614,2025-12-31\nZagreb,CRO,777359,2024-12-31\nFrankfurt,GER,756021,2024-12-31\nHelsinki,FIN,699637,2026-07-01\nZaragoza,ESP,693091,2025-01-01\nSeville,ESP,689423,2025-01-01\nRotterdam,NLD,673966,2026-06-30\nWrocław,POL,672601,2025-12-31\nCopenhagen,DEN,671714,2026-01-01\nLisbon,POR,658236,2025-12-31\nAthens,GRC,643450,2024-01-01\nŁódź,POL,639890,2025-12-31\nPalermo,ITA,626273,2026-01-01\nDüsseldorf,GER,619444,2025-12-31\nVilnius,LTU,619405,2026-07-01\nGothenburg,SWE,614165,2026-06-30\nStuttgart,GER,612663,2024-12-31\nLeipzig,GER,611850,2024-12-31\nDortmund,GER,600880,2025-12-31\nMálaga,ESP,599063,2025-01-01\nDublin,IRL,592713,2022-04-03\nRiga,LVA,588911,2026-01-01\nBremen,GER,586271,2024-12-31\nEssen,GER,573618,2025-12-31\nAntwerp,BEL,572365,2026-07-01\nThe Hague,NLD,569293,2026-06-30\nGenoa,ITA,566247,2026-01-01\nDresden,GER,564904,2024-12-31\nPoznań,POL,534239,2025-12-31\nNuremberg,GER,531159,2025-12-31\nLyon,FRA,527236,2024-01-01\nToulouse,FRA,522662,2024-01-01\nHanover,GER,522131,2024-12-31\nDuisburg,GER,500810,2025-12-31\nGdańsk,POL,489328,2025-12-31\nBratislava,SVK,480947,2026-01-01\nMurcia,ESP,479405,2025-01-01\nTallinn,EST,452563,2026-01-01\nSintra,POR,449956,2025-12-31\nPalma de Mallorca,ESP,434786,2025-01-01\nBrno,CZE,404296,2026-01-01\nBologna,ITA,391473,2026-01-01\nSzczecin,POL,383786,2025-12-31\nLas Palmas,ESP,381868,2025-01-01\nUtrecht,NLD,378444,2026-06-30\nAarhus,DEN,378361,2026-01-01\nMalmö,SWE,368660,2026-06-30\nAlicante,ESP,366221,2025-01-01\nFlorence,ITA,361625,2026-01-01\nBochum,GER,358880,2025-12-31\nNice,FRA,358527,2024-01-01\nWuppertal,GER,357243,2025-12-31\nBilbao,ESP,351124,2025-01-01\nPlovdiv,BUL,333994,2025-12-31\nNantes,FRA,332411,2024-01-01\nBielefeld,GER,331419,2025-12-31\nVarna,BUL,331260,2025-12-31\nEspoo,FIN,328502,2026-07-01\nLublin,POL,326685,2025-12-31\nBonn,GER,323587,2025-12-31\nCórdoba,ESP,323262,2025-01-01\nVila Nova de Gaia,POR,323202,2025-12-31\nBydgoszcz,POL,321100,2025-12-31\nMannheim,GER,318035,2024-12-31\nBari,ITA,316248,2026-01-01\nMontpellier,FRA,312537,2024-01-01\nKarlsruhe,GER,309050,2024-12-31\nThessaloniki,GRC,307920,2024-01-01\nMünster,GER,306368,2025-12-31\nGraz,AUT,305314,2025-01-01\nKaunas,LTU,303613,2026-07-01\nLjubljana,SVN,302826,2026-01-01\nValladolid,ESP,302614,2025-01-01\nAugsburg,GER,301105,2024-12-31\n"

city, state (three-letter code), population within city limits, counted (the date of the count). Wikipedia, "List of cities in the European Union by population within city limits", read 8 Nov 2026.

gtcarsproc#

proc gtcars(): TableData

47 deluxe automobiles from the 2014-2017 model years, with their performance and price (gt's gtcars).

countrypopsproc#

proc countrypops(): TableData

The population of every country, every year from 1960 to 2022 (World Bank; gt's countrypops).

illnessproc#

proc illness(): TableData

Daily tests of a patient with yellow fever, days 3 to 9, with their normal ranges (gt's illness).

metroproc#

proc metro(): TableData

The stations of the Paris Metro, with their lines and passengers in 2021 (gt's metro).

planetsproc#

proc planets(): TableData

No doc comment yet.

an example, from the specs
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

exibbleproc#

proc exibble(): TableData

No doc comment yet.

isoleproc#

proc isole(): TableData

No doc comment yet.

an example, from the specs
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

cittaproc#

proc citta(): TableData

No doc comment yet.

an example, from the specs
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

tavolaPitagoricaproc#

proc tavolaPitagorica(n = 10): TableData

An n×n times table: a column × with 1..n, then one column per factor ("1" .. "n").

an example, from the specs
let t = tabella(tavolaPitagorica(2), rownameCol = "×"):
  colsLabelWith proc (s: string): string = "×" & s
echo t
×1×2
112
224

In nimib

tabelline/nimib · src/tabelline/nimib.nim · import tabelline/nimib: tables in a nimib notebook.

tabelline in nimib notebooks: nbTable t shows a table as a block of the page.

namekind
NbTabletype
newNbTableproc
nbtableToHtmlproc
dumpmethod
nbTableToMdfunc
tableHtmlproc
tableproc
nbTablemacro
×3: three overloads. A name opens its entry below.
8 names, 2 with a doc comment
import nimib, tabelline, tabelline/nimib
nbInit
nbCode:
  let t = tabella(planets()):
    tabHeader "The planets"
nbTable t
nbTable planets():          # or in one step, when the code need not be shown
  tabHeader "The planets"
nbSave

The block keeps the HTML and the Markdown of the table, so it renders with both of nimib's backends (nbInit for HTML, nbInitMd for Markdown, as in a README). The first table of a page carries tabellaCss, the stylesheet of every table; the others leave it out.

NbTabletype#

NbTable = ref object of NbBlock
  html*: string
  markdown*: string

No doc comment yet.

newNbTableproc#

proc newNbTable(
    html: string = default(typedesc[string]),
    markdown: string = default(typedesc[string])
): NbTable

No doc comment yet.

nbtableToHtmlproc#

proc nbtableToHtml(
    blk: NbBlock,
    nb: Nb
): string

No doc comment yet.

dumpmethod#

method dump(n`gensym5: NbTable): string

No doc comment yet.

nbTableToMdfunc#

func nbTableToMd(
    blk: NbBlock,
    nb: Nb
): string

No doc comment yet.

tableHtmlproc#

proc tableHtml(
    nb: var Nb,
    t: Tabella
): string

The HTML of t for this page: with tabellaCss the first time on the page, without it afterwards. For a block that puts a table inside its own HTML.

tableproc#

proc table(nb: var Nb; t: Tabella)

No doc comment yet.

an example, from the specs
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

nbTablemacro#

macro nbTable(
    args: varargs[untyped]
): untyped

Adds a table to the page: nbTable t for a table t, and nbTable data for a table of data as it is. With a body, nbTable data: body adds tabella(data): body, in one step, without naming the table (the other arguments of tabella, such as rownameCol, go too):

nbTable planets(), rownameCol = "planet":
  tabHeader "Planets"
  fmtNumber "mass", decimals = 1

A body works on a table too: nbTable t: tabHeader "Again" adds t with a heading. (A macro: written as a template, Nim would give the body to nbTable, not to tabella.)

From nanuq

tabelline/nanuq · src/tabelline/nanuq.nim · import tabelline/nanuq: a table from a nanuq (Polars) DataFrame.

tabelline/nanuq: a table straight from a nanuq <https://github.com/pietroppeter/nanuq>_ DataFrame (Polars for Nim).

namekind
toTableDataproc
initTabellaproc
×3: three overloads. A name opens its entry below.
2 names, 2 with a doc comment

The data steps (group, summarise, pivot) happen in nanuq; tabelline makes the table:

import nanuq, nanuq/datasets
import tabelline, tabelline/nanuq
let byIsland = penguins().groupBy("island").agg(len().alias("n"))
let t = tabella(byIsland):
  tabHeader "Penguins by island"

nanuq is an optional dependency: only this module needs it (the docs feature of tabelline.nimble brings it, with its prebuilt Polars library), and the core of tabelline still needs only Nim's standard library. The data is copied, as Polars' to_pandas does.

toTableDataproc#

proc toTableData(
    df: nq.DataFrame
): TableData

Copies every column of df, in order: integers become ints, floats floats, booleans bools, strings strings, a list of numbers, booleans or strings a list (a nanoplot's values), and any other type (dates, durations, categories, structs) the text Polars writes for it. A null becomes a missing value.

initTabellaproc#

proc initTabella(
    df: nq.DataFrame,
    rownameCol = "",
    groupnameCol = "",
    id = "",
    locale = "",
    autoAlign = true
): Tabella

A display table for a nanuq DataFrame, so that tabella(df): body works as for any data.

How it is built

The page is a nimib notebook, docs/api.nim, like every page of the site. Its data comes from four places:

  1. nim jsondoc, run on each module by tools/apidoc.nim: every exported name, its kind, its signature as Nim prints it (here without the effects Nim inferred, raises and tags), and its line. The JSON is kept in nimcache/apidoc/ until a source file changes.
  2. The source: each name's doc comment, as written (Markdown), and its section, the # ---- name line above it. jsondoc has the doc comments too, but rendered as reStructuredText, which reads *, | and backticks its own way.
  3. The specs: the shortest example that uses a name, run while the page builds (tools/specexamples.nim).
  4. gt's and Great Tables' reference indexes, read from their repositories by tools/references.nim into docs/coverage/references.json: tabHeader is tab_header() in gt and GT.tab_header() in Great Tables, loc.body() is cells_body() and loc.body(), and a name links to a page only when the index has it.

Each entry is one block, nbApi (in docs/blocks.nim), so the page has no HTML of its own. nim r tools/apidoc.nim prints the same data as JSON, for an agent or another page.