640 functions

Markdown72

String52

Collections86

Math & Statistics70

Types & Logic46

Date & Time12

Regex & Encoding36

Files & I/O35

Utilities19

Other6

cbor2

csv12

fuzzy8

gron2

json15

md40

section35

semver16

table35

test17

toml6

toon3

xml9

yaml6

434 functions

Markdown72

attr(markdown: markdown, attribute: string) function

Retrieves the value of the specified attribute from a markdown node.

demote_heading(node): markdown function

Demotes a markdown heading by increasing its depth (numeric level) by one (e.g. h1 -> h2), up to a maximum of 6.

Example
demote_heading(to_h("t", 1))
Result
## t
embed_images(base_dir: string): markdown functionrequires file-io

Inlines an .image node's local file into its url as a base64 data: URI, resolving the path relative to the given base directory (default ".") and inferring the MIME type from the file extension. URLs that are already data: URIs or contain a :// scheme (e.g. https://), and non-image nodes, are left unchanged. Requires the --allow-read CLI flag; otherwise returns a runtime error.

extract_images(dir: string): markdown functionrequires file-io

Decodes an .image node's base64 data: URI and writes the bytes to a file under the given directory, named by the content's MD5 hash with an extension inferred from the MIME type, then replaces url with that file's path. Nodes whose url is not a base64 data: URI, including non-image nodes, are left unchanged. Requires the --allow-write CLI flag; otherwise returns a runtime error.

extract_urls(text): array function

Extracts http(s):// and mailto: URLs from plain text (not Markdown links or HTML) as {url, start_byte, end_byte, kind} records, trimming trailing prose punctuation off each match. Does not detect bare domains without a scheme.

Example
extract_urls("see https://example.com.")
Result
[{"url": "https://example.com", "start_byte": 4, "end_byte": 23, "kind": "http"}]
from_html(html: string): array function

Converts the given HTML string to Markdown.

get_location(node: markdown): dict function

Returns the source position of a markdown node as a dict with start_line, start_column, end_line, and end_column, or None if the node has no position info.

get_title(node: markdown): string function

Returns the title of a markdown node.

get_url(node: markdown): string function

Returns the url of a markdown node.

Example
get_url(to_link("https://example.com", "Example", ""))
Result
https://example.com
is_callout(md): bool function

Checks if markdown is a callout block

Example
is_callout(to_callout("Note", "note", ""))
Result
true
is_code(md): bool function

Checks if markdown is code block

Example
is_code(to_code("x", "python"))
Result
true
is_em(md): bool function

Checks if markdown is emphasis

Example
is_em(to_em("hi"))
Result
true
is_h(md): bool function

Checks if markdown is heading

Example
is_h(to_h("t", 2))
Result
true
is_h1(md): bool function

Checks if markdown is h1 heading

Example
is_h1(to_h("t", 1))
Result
true
is_h2(md): bool function

Checks if markdown is h2 heading

Example
is_h2(to_h("t", 2))
Result
true
is_h3(md): bool function

Checks if markdown is h3 heading

Example
is_h3(to_h("t", 3))
Result
true
is_h4(md): bool function

Checks if markdown is h4 heading

Example
is_h4(to_h("t", 4))
Result
true
is_h5(md): bool function

Checks if markdown is h5 heading

Example
is_h5(to_h("t", 5))
Result
true
is_h6(md): bool function

Checks if markdown is h6 heading

Example
is_h6(to_h("t", 6))
Result
true
is_h_level(md, level): bool function

Checks if markdown is a heading of the specified level (1-6)

Example
is_h_level(to_h("t", 2), 2)
Result
true
is_html(md): bool function

Checks if markdown is html

is_list(list): bool function

Checks if markdown is list

Example
is_list(to_md_list("Item", 0))
Result
true
is_mdx(mdx): bool function

Checks if markdown is MDX

is_mdx_flow_expression(mdx): bool function

Checks if markdown is MDX Flow Expression

is_mdx_js_esm(mdx): bool function

Checks if markdown is MDX Js Esm

is_mdx_jsx_flow_element(mdx): bool function

Checks if markdown is MDX Jsx Flow Element

is_mdx_jsx_text_element(mdx): bool function

Checks if markdown is MDX Jsx Text Element

is_mdx_text_expression(mdx): bool function

Checks if markdown is MDX Text Expression

is_table_align(md): bool function

Checks if markdown is table align

Example
is_table_align(to_md_table_align(["left"]))
Result
true
is_table_cell(md): bool function

Checks if markdown is table cell

Example
is_table_cell(to_md_table_cell("A1", 0, 0))
Result
true
is_text(text): bool function

Checks if markdown is text

Example
is_text(to_md_text("hi"))
Result
true
is_toml(md): bool function

Checks if markdown is toml

is_yaml(md): bool function

Checks if markdown is yaml

promote_heading(node): markdown function

Promotes a markdown heading by decreasing its depth (numeric level) by one (e.g. h2 -> h1), down to a minimum of 1.

Example
promote_heading(to_h("t", 2))
Result
# t
sanitize_html(html: string): string function

Sanitizes the given HTML string using an allowlist of safe tags and attributes, removing scripts and other XSS vectors.

set_attr(markdown: markdown, attribute: string, value): markdown function

Sets the value of the specified attribute on a markdown node.

set_check(list: markdown, checked: bool): markdown function

Creates a markdown list node with the given checked state.

Example
set_check(to_md_list("Item", 0), true)
Result
- [x] Item
set_children(markdown: markdown, children: array): markdown function

Sets the children nodes of a markdown node. Nodes without children (e.g. text, code) are left unchanged.

set_code_block_lang(code_block: markdown, language: string): markdown function

Sets the language of a markdown code block node.

Example
set_code_block_lang(to_code("x", "python"), "rust")
Result
```rust
x
```
set_list_ordered(list: markdown, ordered: bool): markdown function

Sets the ordered property of a markdown list node.

Example
set_list_ordered(to_md_list("Item", 0), true)
Result
1. Item
set_ref(node: markdown, reference_id: string): markdown function

Sets the reference identifier for markdown nodes that support references (e.g., Definition, LinkRef, ImageRef, Footnote, FootnoteRef).

strip_tags(string: string): string function

Removes HTML tags from the given string, keeping the surrounding text content.

Example
strip_tags("<b>hi</b>")
Result
hi
to_blockquote(value): markdown function

Creates a markdown blockquote node with the given value.

Example
to_blockquote("Quote")
Result
> Quote
to_break(): markdown function

Creates a markdown hard line break node.

Example
to_break()
Result
\
to_callout(value, kind: string, title: string): markdown function

Creates a markdown callout node with the given value, kind, and title.

Example
to_callout("Note text", "note", "")
Result
> [!NOTE]
> Note text
to_code(value, language: string): markdown function

Creates a markdown code block with the given value and language.

Example
to_code("x = 1", "python")
Result
```python
x = 1
```
to_code_inline(value): markdown function

Creates an inline markdown code node with the given value.

Example
to_code_inline("x")
Result
`x`
to_definition(url: string, ident: string, title: string): markdown function

Creates a markdown link reference definition node with the given url, identifier, and title.

Example
to_definition("https://example.com", "ex", "")
Result
[ex]: https://example.com
to_delete(value): markdown function

Creates a markdown delete (strikethrough) node with the given value.

Example
to_delete("Old")
Result
~~Old~~
to_em(value): markdown function

Creates a markdown emphasis (italic) node with the given value.

Example
to_em("Italic")
Result
*Italic*
to_footnote(value, ident: string): markdown function

Creates a markdown footnote definition node with the given value and identifier.

Example
to_footnote("Footnote text", "1")
Result
[^1]: Footnote text
to_footnote_ref(ident: string): markdown function

Creates a markdown footnote reference node with the given identifier.

Example
to_footnote_ref("1")
Result
[^1]
to_h(value, depth: number): markdown function

Creates a markdown heading node with the given value and depth. A depth outside of 1 to 6 becomes the nearest of them.

Example
to_h("Title", 1)
Result
# Title
to_hr(): markdown function

Creates a markdown horizontal rule node.

Example
to_hr()
Result
***
to_html(markdown: string): string function

Converts the given markdown string to HTML.

to_image(url: string, alt: string, title: string): markdown function

Creates a markdown image node with the given URL, alt text, and title.

Example
to_image("https://example.com/a.png", "Alt", "")
Result
![Alt](https://example.com/a.png "")
to_link(url: string, value, title: string): markdown function

Creates a markdown link node with the given url and title.

Example
to_link("https://example.com", "Example", "")
Result
[Example](https://example.com)
to_markdown(markdown_string: string): array function

Parses a markdown string and returns an array of markdown nodes.

Example
to_markdown("# Hi")
Result
[# Hi]
to_markdown_string(value): string function

Converts the given value(s) to a markdown string representation.

to_math(value): markdown function

Creates a markdown math block with the given value.

Example
to_math("x^2")
Result
$$
x^2
$$
to_math_inline(value): markdown function

Creates an inline markdown math node with the given value.

Example
to_math_inline("x^2")
Result
$x^2$
to_md_fragment(values: array): markdown function

Creates a markdown fragment node that groups an array of markdown nodes into a single value.

to_md_html(value): markdown function

Creates a raw markdown HTML node with the given value.

Example
to_md_html("<br>")
Result
<br>
to_md_list(value, indent: number): markdown function

Creates a markdown list node with the given value and indent level.

Example
to_md_list("Item", 0)
Result
- Item
to_md_name(markdown: markdown): string function

Returns the name of the given markdown node.

Example
to_md_name(to_h("t", 1))
Result
h1
to_md_table_align(aligns: array): markdown function

Creates a markdown table alignment row node from an array of alignments ("left", "right", "center", "none").

Example
to_md_table_align(["left", "right"])
Result
|:---|---:|
to_md_table_cell(value, row: number, column: number): markdown function

Creates a markdown table cell node with the given value at the specified row and column.

Example
to_md_table_cell("A1", 0, 0)
Result
A1
to_md_table_row(cells: array): markdown function

Creates a markdown table row node with the given values.

to_md_text(value): markdown function

Creates a markdown text node with the given value.

Example
to_md_text("hi")
Result
hi
to_mdx(mdx_string: string): array function

Parses an MDX string and returns an array of MDX nodes.

to_strong(value): markdown function

Creates a markdown strong (bold) node with the given value.

Example
to_strong("Bold")
Result
**Bold**
to_text(markdown: markdown): string function

Converts the given markdown node to plain text.

Example
to_text(to_strong("hi"))
Result
hi

String52

ascii_downcase(input: string): string function

Converts ASCII uppercase letters (A-Z) in the given string to lowercase, leaving all other characters unchanged.

Example
ascii_downcase("ABC")
Result
abc
ascii_upcase(input: string): string function

Converts ASCII lowercase letters (a-z) in the given string to uppercase, leaving all other characters unchanged.

Example
ascii_upcase("abc")
Result
ABC
casefold(input: string): string function

Applies full Unicode case folding, for locale-independent case-insensitive comparison (e.g. German "ß" folds to "ss").

Example
casefold("Straße")
Result
strasse
center(s, width, pad_str): string function

Centers a string within a given width using a padding string.

Example
center("ab", 6, "*")
Result
**ab**
chars(s): array function

Splits a string into an array of characters (Unicode code points).

Example
chars("abc")
Result
["a", "b", "c"]
chomp(s): string function

Removes one trailing newline (\n or \r\n) from a string.

Example
chomp("line\n")
Result
line
common_indent(s): string function

Returns the longest run of leading spaces/tabs shared by every non-blank line of a string. Blank (empty or whitespace-only) lines are ignored when computing the margin. Lines indented with a mix of tabs and spaces that don't agree on the same prefix yield no common indent.

Example
common_indent("  a\n    b\n  c") == "  "
Result
true
contains(haystack, needle): bool function

Checks if a string, byte array, array, or dict contains a substring, byte subsequence, element, or key.

Example
contains("hello world", "world")
Result
true
count_substr(s, sub): number function

Returns the number of non-overlapping occurrences of a substring.

Example
count_substr("banana", "an")
Result
2
dedent(s): string function

Removes the common leading whitespace (see common_indent) from every line of a string. Blank lines are normalized to empty; the string is returned unchanged when there is no common indent to strip.

Example
dedent("  a\n  b") == "a\nb"
Result
true
downcase(input: string): string function

Converts the given string to lowercase.

Example
downcase("ABC")
Result
abc
ends_with(value, suffix): bool function

Checks if the given string or byte array ends with the specified suffix.

Example
ends_with("hello", "lo")
Result
true
explode(string: string): array function

Splits the given string into an array of characters.

Example
explode("ab")
Result
[97, 98]
grapheme_len(input: string): number function

Returns the number of extended grapheme clusters (user-perceived characters) in the string.

Example
grapheme_len("👨‍👩‍👧")
Result
1
graphemes(input: string): array function

Splits the string into extended grapheme clusters (user-perceived characters), keeping combining marks and multi-codepoint emoji together.

Example
graphemes("👨‍👩‍👧")
Result
["👨‍👩‍👧"]
indent(s, prefix): string function

Prepends the given prefix to every line of a string.

Example
indent("a\nb", "  ") == "  a\n  b"
Result
true
is_alnum(s): bool function

Returns true if the string is non-empty and consists only of letters and digits.

is_alpha(s): bool function

Returns true if the string is non-empty and consists only of letters.

is_ascii(s): bool function

Returns true if the string contains only ASCII characters.

is_digit(s): bool function

Returns true if the string is non-empty and consists only of ASCII digits.

is_lower(s): bool function

Returns true if the string has cased letters and all of them are lowercase.

is_space(s): bool function

Returns true if the string is non-empty and consists only of whitespace.

is_upper(s): bool function

Returns true if the string has cased letters and all of them are uppercase.

lines(s): array function

Returns the lines of a string as an array by splitting on newline characters.

Example
lines("a\nb\nc")
Result
["a", "b", "c"]
lpad(s, length, pad_str): string function

Left-pads a string to a specified length using a given padding string.

Example
lpad("7", 3, "0")
Result
007
ltrim(input) function

Trims whitespace from the left end of the given string or byte array.

Example
ltrim("  hi  ")
Result
hi  
ltrimstr(s, left): string function

Removes prefix string from input if it exists

Example
ltrimstr("prefix_value", "prefix_")
Result
value
normalize_newlines(text, mode): string function

Normalizes line endings in a string to either "\n" ("lf") or "\r\n" ("crlf"). Any mix of "\r\n", "\r", and "\n" in the input is treated as a line break.

Example
normalize_newlines("a\r\nb\rc", "lf")
Result
a
b
c
remove_chars(s, set): string function

Removes every character that appears in the given set.

Example
remove_chars("hello world", "lo")
Result
he wrd
repeat(string: string, count: number): string function

Repeats the given string a specified number of times.

Example
repeat("ab", 3)
Result
ababab
replace(from, pattern, to) function

Replaces all occurrences of a substring or byte subsequence with another one.

Example
replace("aXbXc", "X", "-")
Result
a-b-c
rpad(s, length, pad_str): string function

Right-pads a string to a specified length using a given padding string.

Example
rpad("7", 3, "0")
Result
700
rsplit_once(s, sep): array function

Splits a string at the last occurrence of a separator. Returns [s, None] if not found.

Example
rsplit_once("a.b.c", ".")
Result
["a.b", "c"]
rtrim(input) function

Trims whitespace from the right end of the given string or byte array.

Example
rtrim("  hi  ")
Result
  hi
rtrimstr(s, right): string function

Removes suffix string from input if it exists

Example
rtrimstr("value_suffix", "_suffix")
Result
value
slice(string: string, start: number, end: number): string function

Extracts a substring from the given string.

Example
slice("hello", 1, 3)
Result
el
slugify(s, separator): string function

Converts a string into a URL-friendly slug by lowercasing, replacing runs of characters that are not Unicode letters, marks or digits with the separator, and trimming hyphens from the ends. Non-ASCII letters are kept as is, not transliterated.

Example
slugify("Hello, World!")
Result
hello-world
split(value, separator): array function

Splits the given string (as a regular expression) or byte array (literal separator) by the specified separator.

Example
split("a,b,c", ",")
Result
["a", "b", "c"]
split_once(s, sep): array function

Splits a string at the first occurrence of a separator. Returns [s, None] if not found.

Example
split_once("key=a=b", "=")
Result
["key", "a=b"]
squeeze_whitespace(s): string function

Collapses every run of whitespace (spaces, tabs, newlines) into a single space and trims the result, e.g. after joining text from multiple sources.

Example
squeeze_whitespace("  a   b\n\tc  ")
Result
a b c
starts_with(value, prefix): bool function

Checks if the given string or byte array starts with the specified prefix.

Example
starts_with("hello", "he")
Result
true
strip_ansi(s): string function

Removes ANSI escape sequences (e.g. color codes) from a string

Example
strip_ansi("\x1b[31mred\x1b[0m")
Result
red
token_count(text: string, model?: string): number function

Estimates how many LLM tokens the given text would consume, for context-window budgeting. Uses a lightweight chars-per-token heuristic by default; built with the tiktoken Cargo feature, counts exactly via tiktoken-rs instead when model (e.g. "gpt-5") is given. model is optional; without it, the heuristic estimate is always used.

Example
token_count("Hello, world!")
Result
4
translate(s, from, to): string function

Replaces each character of from with the character at the same position in to (like tr).

Example
translate("hello", "el", "ip")
Result
hippo
trim(input) function

Trims whitespace from both ends of the given string or byte array.

Example
trim("  hi  ")
Result
hi
truncate(string: string, width: number, ellipsis: string): string function

Truncates the given string to the specified display width, appending the ellipsis string when truncated (CJK and other wide characters count as two columns).

Example
truncate("hello world", 5, "...")
Result
he...
unicode_normalize(input: string, form: string): string function

Normalizes the string to a Unicode normalization form: "nfc", "nfd", "nfkc", or "nfkd".

Example
unicode_normalize("e\u{0301}", "nfc")
Result
é
unlines(arr): string function

Joins an array of strings into a single string with newline characters between them.

Example
unlines(["a", "b", "c"]) == "a\nb\nc"
Result
true
upcase(input: string): string function

Converts the given string to uppercase.

Example
upcase("abc")
Result
ABC
word_wrap(string: string, width: number): string function

Wraps the given string into lines no wider than the specified display width, breaking on word boundaries (CJK and other wide characters count as two columns).

Example
word_wrap("hello world", 5)
Result
hello
world
words(s): array function

Splits a string into words, breaking on non-alphanumeric characters and on camelCase boundaries. Boundary detection uses ASCII letters.

Example
words("fooBar_baz-QUX")
Result
["foo", "Bar", "baz", "QUX"]
zfill(s, width): string function

Left-pads a number or string with zeros to a given width, keeping a leading sign in front.

Example
zfill(-42, 5)
Result
-0042

Collections86

all(v, f): bool function

Returns true if all elements in the array or coroutine satisfy the provided function.

Example
all([1, 2, 3], fn(x): x > 0;)
Result
true
any(v, f): bool function

Returns true if any element in the array or coroutine satisfies the provided function.

Example
any([1, 2, 3], fn(x): x > 2;)
Result
true
chunk_by(v, f): array function

Splits an array into chunks based on the result of applying a function to each element, grouping consecutive elements with the same key together.

Example
chunk_by([1, 1, 2, 2, 3], identity)
Result
[[1, 1], [2, 2], [3]]
chunks(v, size): array function

Splits an array into chunks of a specified size, returning an array of arrays.

Example
chunks([1, 2, 3, 4, 5], 2)
Result
[[1, 2], [3, 4], [5]]
collect(stream) function

Consumes a coroutine to completion and returns its yielded values as an array. Non-coroutine values are returned unchanged, making this safe as an output boundary when a query may produce either eager or lazy values.

Example
def range(n): var i = 0 | while (i < n): yield: i | i += 1;;
| range(3) | collect()
Result
[0, 1, 2]
combinations(arrays): array function

Returns the Cartesian product of the given array of arrays, combining one element from each array.

Example
combinations([[1, 2], [3, 4]])
Result
[[1, 3], [1, 4], [2, 3], [2, 4]]
compact(array: array): array function

Removes None values from the given array.

Example
compact([1, None, 2])
Result
[1, 2]
compact_map(arr, f): array function

Maps over an array and removes None values from the result. A coroutine input returns a coroutine and performs both operations lazily.

Example
compact_map([1, 2, 3], fn(x): if (x > 1): x;)
Result
[2, 3]
del(array_or_string, index: number) function

Deletes the element at the specified index in the array or string.

Example
del([1, 2, 3], 1)
Result
[1, 3]
del_path(value, path) function

Deletes the value at a nested path, following an array of keys/indices, e.g. del_path(d, ["a", "b", 0]). An empty path deletes the whole value, mirroring jq's delpaths([[]]). A path through a missing intermediate container, or ending in a missing key/out-of-range index, leaves value unchanged.

Example
del_path({"a": {"b": 1, "c": 2}}, ["a", "b"])
Result
{"a": {"c": 2}}
del_paths(value, paths) function

Deletes the values at multiple nested paths, e.g. del_paths(d, [["a"], ["b", 0]]). Paths are applied deepest-first (via sort/reverse) so that deleting one array element doesn't shift the indices used by the remaining paths, mirroring jq's delpaths.

Example
del_paths({"a": 1, "b": 2, "c": 3}, [["a"], ["c"]])
Result
{"b": 2}
difference(arr1, arr2): array function

Returns the difference of two arrays: the distinct elements of the first array that do not appear in the second.

Example
difference([1, 2, 3], [2, 3, 4])
Result
[1]
each(v, f) function

Executes a provided function once for each element in an array, each key-value pair in a dictionary, or each value yielded by a coroutine (consumed to completion).

entries(dict: dict): array function

Returns an array of key-value pairs from the dict as arrays.

fill(value, n): array function

Returns an array of length n filled with the given value.

Example
fill("x", 3)
Result
["x", "x", "x"]
filter(v, f): array function

Filters the elements of an array based on a provided callback function. A coroutine input is filtered lazily and returns a coroutine.

Example
filter([1, 2, 3, 4], fn(x): x > 2;)
Result
[3, 4]
find(arr, f) function

Returns the first element in an array or coroutine that satisfies the provided function, or None if no element matches. Stops at the first match instead of scanning the whole input.

Example
find([1, 2, 3], fn(x): x == 2;)
Result
2
find_index(arr, f): number function

Returns the index of the first element in an array or coroutine that satisfies the provided function.

Example
find_index([1, 2, 3], fn(x): x == 2;)
Result
1
first(arr) function

Returns the first element of an array, or consumes one value from a coroutine.

Example
first([1, 2, 3])
Result
1
flat_map(v, f): array function

Applies a function to each element and flattens the result into a single array. A coroutine input is flattened lazily and returns a coroutine.

Example
flat_map([1, 2], fn(x): [x, x];)
Result
[1, 1, 2, 2]
flatten(array: array): array function

Flattens a nested array into a single level array.

Example
flatten([[1, 2], [3]])
Result
[1, 2, 3]
fold(arr, init, f) function

Reduces an array to a single value by applying a function, starting from an initial value.

Example
fold([1, 2, 3], 0, fn(acc, x): acc + x;)
Result
6
fold_while(arr, init, f) function

Folds an array until the function signals to stop. The function returns [continue, acc]; the fold ends after the first [false, acc] and returns that acc.

Example
fold_while([1, 2, 3, 4], 0, fn(acc, x): [acc + x < 5, acc + x];)
Result
6
frequencies_by(arr, f): dict function

Counts occurrences of each key extracted from the elements of an array, returning a dict of {key: count}.

Example
frequencies_by(["a", "b", "a"], identity)
Result
{"a": 2, "b": 1}
from_entries(arr): dict function

Builds a dict from an array of [key, value] pairs, as produced by entries. If the same key appears more than once, the last occurrence wins.

Example
from_entries([["a", 1], ["b", 2]])
Result
{"a": 1, "b": 2}
frontmatter(v) function

Parses frontmatter from a markdown node, supporting both YAML and TOML formats.

get(obj: dict, key) function

Retrieves a value from a dict by its key. Returns None if the key is not found.

get_or(dict, key, default) function

Safely gets a value from a dict with a default if the key doesn't exist.

Example
get_or({"a": 1}, "b", 0)
Result
0
get_path(value, path) function

Retrieves a nested value by following an array of keys/indices, e.g. get_path(d, ["a", "b", 0]). Returns None as soon as any intermediate step is missing.

Example
get_path({"a": {"b": 1}}, ["a", "b"])
Result
1
group_by(arr, f): dict function

Groups elements of an array by the result of applying a function to each element

Example
group_by([1, 2, 3, 4], fn(x): mod(x, 2);)
Result
{"1": [1, 3], "0": [2, 4]}
has(value, key): bool function

Checks if a dict has the given key, or an array has an element at the given index.

Example
has({"a": 1}, "a")
Result
true
implode(array: array): string function

Joins an array of code points into a string. Values that are not Unicode scalar values become U+FFFD; non-integers and non-numbers are errors.

Example
implode(explode("ab"))
Result
ab
index(value, needle): number function

Finds the first occurrence of a substring or byte subsequence. Returns -1 if not found. String offsets count Unicode scalar values, like slice and len; byte offsets apply only to bytes.

Example
index("hello", "ll")
Result
2
index_by(arr, f): dict function

Creates a dictionary indexed by a key extracted from each element.

Example
index_by([1, 2, 3], to_string)
Result
{"1": 1, "2": 2, "3": 3}
indices(value, needle): array function

Finds all occurrences of a substring, byte subsequence, or array element. Returns an array of positions, or an empty array if not found. String positions count Unicode scalar values, like slice and len.

Example
indices("hello world hello", "hello")
Result
[0, 12]
insert(target, index_or_key, value) function

Inserts a value into an array or string at the specified index, or into a dict with the specified key.

Example
insert([1, 2, 3], 1, "x")
Result
[1, "x", 2, 3]
interleave(arr1, arr2): array function

Interleaves two arrays, stopping at the shorter one.

Example
interleave([1, 2, 3], ["a", "b", "c"])
Result
[1, "a", 2, "b", 3, "c"]
interpose(arr, sep): array function

Inserts a separator between the elements of an array.

Example
interpose([1, 2, 3], 0)
Result
[1, 0, 2, 0, 3]
intersection(arr1, arr2): array function

Returns the intersection of two arrays: the distinct elements of the first array that also appear in the second.

Example
intersection([1, 2, 3], [2, 3, 4])
Result
[2, 3]
invert(d): dict function

Returns a new dict with keys and values swapped. If multiple keys map to the same value (after conversion to string), the last one wins.

Example
invert({"a": 1, "b": 2})
Result
{"1": "a", "2": "b"}
join(array: array, separator) function

Joins the elements of an array into a string with the given separator. An array of byte arrays with a byte array separator is joined into a byte array instead.

Example
join([1, 2, 3], ",")
Result
1,2,3
join_by(left, right, left_key, right_key, kind): array function

Joins two arrays of dict records on left_key/right_key, similar to a SQL join. Matching records are merged with + (right's fields win on collision). kind is one of "inner" (default), "left", "right", or "full"; unmatched records in outer joins are filled with None for the other side's fields (inferred from that side's full key set). Records with a missing or None join key never match, and duplicate keys on either side expand as a cross product. kind can also be "semi" or "anti" (filtering joins). "semi" returns only the left records whose key exists on the right, and "anti" returns only those whose key does not. Left records are returned unchanged, in their original order, without being duplicated by repeated right keys, and no right fields are merged in. A left record with a missing or None key never matches, so "semi" drops it and "anti" keeps it.

Example 1
join_by([{"id": 2, "name": "bob"}], [{"uid": 2, "age": 30}], "id", "uid")
Result
[{"id": 2, "name": "bob", "uid": 2, "age": 30}]
Example 2
join_by([{"id": 1}, {"id": 2}], [{"uid": 2}, {"uid": 2}], "id", "uid", "semi")
Result
[{"id": 2}]
Example 3
join_by([{"id": 1}, {"id": 2}], [{"uid": 2}, {"uid": 2}], "id", "uid", "anti")
Result
[{"id": 1}]
keys(dict: dict): array function

Returns an array of keys from the dict.

last(arr) function

Returns the last element of an array, or consumes a coroutine to its last value.

Example
last([1, 2, 3])
Result
3
leaf_entries(value): array function

Returns an array of {path, value, type, depth} records, one per leaf value in a nested dict/array, e.g. leaf_entries({"a": {"b": 1}}) returns [{"path": ["a", "b"], "value": 1, "type": "number", "depth": 2}]. depth is len(path). Like paths, containers with no leaves (e.g. {}, []) contribute no entries.

Example
leaf_entries({"a": {"b": 1}})
Result
[{"path": ["a", "b"], "value": 1, "type": "number", "depth": 2}]
len(value): number function

Returns the length of the given string or array.

Example
len("hello")
Result
5
map(v, f): array function

Applies a given function to each element of the provided array and returns a new array with the results. A coroutine input instead returns a coroutine and applies the function only as its values are requested.

Example
map([1, 2, 3], fn(x): mul(x, 2);)
Result
[2, 4, 6]
map_values(d, f): dict function

Applies a function to each value of a dict, keeping the keys.

Example
map_values({"a": 1, "b": 2}, fn(v): v * 10;)
Result
{"a": 10, "b": 20}
map_while(arr, f): array function

Maps elements with a function until it returns None, collecting the results before that point.

Example
map_while([1, 2, 3, 4], fn(x): if (x < 3): x * 10 else: None;)
Result
[10, 20]
merge_defaults(d, defaults) function

Deep merges d over defaults, similar to Jsonnet's object inheritance: values present in d win (recursively for nested dicts), while keys missing from d fall back to the corresponding value in defaults. Arrays and scalar conflicts are resolved by letting d replace defaults. Neither input is mutated.

Example
merge_defaults({"a": {"x": 1}}, {"a": {"x": 0, "y": 2}, "b": 3})
Result
{"a": {"x": 1, "y": 2}, "b": 3}
merge_with(a, b, policy) function

Deep merges two values, recursing into dicts key by key. Neither input is mutated. When both sides provide a leaf/array value for the same key, the conflict is resolved according to policy, one of: - "replace": the second value (b) wins. - "append": arrays are concatenated; other conflicting values are collected into [a, b]. - "error": raises an error describing the conflict.

Example
merge_with({"a": 1, "b": {"x": 1}}, {"b": {"y": 2}, "c": 3}, "replace")
Result
{"a": 1, "b": {"x": 1, "y": 2}, "c": 3}
ngram(s, n): array function

Returns the n-grams of an array or string, which are overlapping contiguous subarrays (or substrings) of length n, sliding one element at a time.

Example
ngram("abcd", 2)
Result
["ab", "bc", "cd"]
omit(d, keys): dict function

Returns a new dictionary excluding the specified keys from the original dictionary.

Example
omit({"a": 1, "b": 2}, ["a"])
Result
{"b": 2}
partition(arr, f): array function

Splits an array into two arrays: [matching, not_matching] based on a condition. A coroutine input is consumed in a single pass.

Example
partition([1, 2, 3, 4], fn(x): x > 2;)
Result
[[3, 4], [1, 2]]
paths(value): array function

Returns an array of leaf-path arrays for a value, e.g. paths({"a": {"b": 1}}) returns [["a", "b"]]. Each returned path can be passed to get_path/set_path. Containers with no leaves (e.g. {}, []) contribute no paths.

Example
paths({"a": {"b": 1}})
Result
[["a", "b"]]
pick(d, keys): dict function

Returns a new dictionary containing only the specified keys from the original dictionary, if they exist.

Example
pick({"a": 1, "b": 2}, ["a"])
Result
{"a": 1}
pluck(pluck_obj, selector) function

Extracts values from an array of objects based on a specified selector.

range(start: number, end: number, step: number): array function

Creates an array from start to end with an optional step.

Example
range(0, 5, 1)
Result
[0, 1, 2, 3, 4, 5]
reject(arr, f): array function

Filters out elements that match the condition (opposite of filter). Coroutine inputs return a lazily filtered coroutine.

Example
reject([1, 2, 3, 4], fn(x): x > 2;)
Result
[1, 2]
reverse(value) function

Reverses the given string or array.

Example
reverse("abc")
Result
cba
rindex(value, needle): number function

Finds the last occurrence of a substring or byte subsequence. Returns -1 if not found. String offsets count Unicode scalar values, like slice and len; byte offsets apply only to bytes.

Example
rindex("hello", "l")
Result
3
second(arr) function

Returns the second element of an array

Example
second([1, 2, 3])
Result
2
select(v, f) function

Returns value if condition is true, None otherwise

Example
select(5, true)
Result
5
set(obj: dict, key, value): dict function

Sets a key-value pair in a dict. If the key exists, its value is updated. Returns the modified map.

set_path(value, path, new_value) function

Sets a nested value by following an array of keys/indices, e.g. set_path(d, ["a", "b", 0], 1). Missing intermediate dicts/arrays are created automatically, choosing an array when the corresponding path element is a number and a dict otherwise.

Example
set_path({"a": {"b": 1}}, ["a", "b"], 2)
Result
{"a": {"b": 2}}
skip_while(arr, f): array function

Skips elements from the beginning of an array while the provided function returns true. A coroutine input performs the same operation lazily.

Example
skip_while([1, 2, 3, 4], fn(x): x < 3;)
Result
[3, 4]
sort(array: array): array function

Sorts the elements of the given array. Mixed types are ordered by type: none, bool, number, string, symbol, markdown, bytes, array, dict.

Example
sort([3, 1, 2])
Result
[1, 2, 3]
sort_by(arr, f): array function

Sorts an array using a key function that extracts a comparable value for each element.

Example
sort_by([3, 1, 2], identity)
Result
[1, 2, 3]
sort_natural(arr): array function

Sorts an array in natural order (numeric-aware), so runs of digits embedded in a string are compared as numbers rather than character-by-character, e.g. "file2" sorts before "file10" (unlike a plain lexicographic sort).

Example
sort_natural(["file10", "file2"])
Result
["file2", "file10"]
split_records(value, separator: string): array function

Splits a string by a regular expression separator into {text, index, start_byte, end_byte, terminator} records, keeping each piece's byte range and the separator that followed it (terminator is None for the last piece). Errors if the separator matches an empty string.

Example
split_records("a,b,c", ",")
Result
[{"text": "a", "index": 0, "start_byte": 0, "end_byte": 1, "terminator": ","}, {"text": "b", "index": 1, "start_byte": 2, "end_byte": 3, "terminator": ","}, {"text": "c", "index": 2, "start_byte": 4, "end_byte": 5, "terminator": }]
take(arr, n): array function

Takes the first n elements of an array. A coroutine input returns a coroutine that yields at most n values and does not pull an additional value upstream.

Example
take([1, 2, 3, 4], 2)
Result
[1, 2]
take_while(arr, f): array function

Takes elements from the beginning of an array while the provided function returns true. A coroutine input performs the same operation lazily.

Example
take_while([1, 2, 3, 4], fn(x): x < 3;)
Result
[1, 2]
tally(arr): dict function

Counts occurrences of each element in an array, returning a dict of {value: count}.

Example
tally(["a", "b", "a"])
Result
{"a": 2, "b": 1}
token_compress(nodes: array, budget: number, model?: string): array function

Reduces an array of Markdown nodes to fit within budget LLM tokens, preserving structure as much as possible: paragraphs are cut to their first sentence, then lists/tables/code blocks are collapsed to a summary, and only as a last resort is the remaining text hard-truncated. Uses a lightweight chars-per-token heuristic by default; built with the tiktoken Cargo feature, counts exactly via tiktoken-rs instead when model (e.g. "gpt-5") is given. model is optional; without it, the heuristic estimate is always used.

transpose(matrix): array function

Transposes a 2D array (matrix), swapping rows and columns.

Example
transpose([[1, 2], [3, 4]])
Result
[[1, 3], [2, 4]]
union(arr1, arr2): array function

Returns the union of two arrays: every distinct element from either array, in first-seen order.

Example
union([1, 2, 3], [2, 3, 4])
Result
[1, 2, 3, 4]
uniq(arr): array function

Removes duplicate elements from the given array, keeping the first occurrence.

Example
uniq([1, 1, 2])
Result
[1, 2]
unique_by(arr, f): array function

Returns a new array with duplicate elements removed, comparing by the result of the provided function.

Example
unique_by([1, 2, 1, 3], identity)
Result
[1, 2, 3]
unzip(pairs): array function

Splits an array of pairs into an array of two arrays: one with the first elements of each pair and one with the second elements. This is the inverse of zip.

Example
unzip([[1, "a"], [2, "b"]])
Result
[[1, 2], ["a", "b"]]
update(target_value, source_value) function

Update the value with specified value.

update_path(value, path, f) function

Updates the value at a nested path using a function.

Example
update_path({"a": {"b": 1}}, ["a", "b"], fn(x): x + 1;)
Result
{"a": {"b": 2}}
values(dict: dict): array function

Returns an array of values from the dict.

walk(v, f) function

Walks through a value (which can be a markdown node, array, or dict) and applies a function to each element, returning a new structure with the results.

Example
walk([1, [2, 3]], fn(x): if (is_number(x)): x * 2 else: x;)
Result
[2, [4, 6]]
with_entries(d, f): dict function

Transforms each [key, value] pair of a dict by applying the given function, then rebuilds a dict from the resulting pairs.

Example
with_entries({"a": 1}, fn(e): [e[0], e[1] + 1];)
Result
{"a": 2}
zip(arr1, arr2): array function

Combines two arrays into an array of pairs, where each pair contains elements from the same index in both arrays.

Example
zip([1, 2], ["a", "b"])
Result
[[1, "a"], [2, "b"]]

Math & Statistics70

abs(number: number): number function

Returns the absolute value of the given number.

Example
abs(-10)
Result
10
accumulate(arr, init, f): array function

Like fold, but returns every intermediate accumulator value (excluding init).

Example
accumulate([1, 2, 3], 0, fn(acc, x): acc + x;)
Result
[1, 3, 6]
acos(number: number): number function

Returns the arc cosine of the given number (in radians).

Example
acos(1)
Result
0
add(value1, value2) function

Adds two values.

Example
add(1, 2)
Result
3
asin(number: number): number function

Returns the arc sine of the given number (in radians).

Example
asin(0)
Result
0
atan(number: number): number function

Returns the arc tangent of the given number (in radians).

Example
atan(0)
Result
0
atan2(y: number, x: number): number function

Returns the arc tangent of y/x (in radians), using the signs of both to determine the quadrant.

Example
atan2(0, 1)
Result
0
band(a: number | bytes, b: number | bytes): number | bytes function

Computes the bitwise AND: of two byte arrays of equal length, or of two integers from 0 to 2^53 - 1.

Example
band(12, 10)
Result
8
bnot(bytes: bytes): bytes function

Computes the bitwise NOT (complement) of a byte array. For integers, use xor(n, mask) with an explicit width.

bor(a: number | bytes, b: number | bytes): number | bytes function

Computes the bitwise OR: of two byte arrays of equal length, or of two integers from 0 to 2^53 - 1.

Example
bor(12, 10)
Result
14
bsearch(arr, target): number function

Performs a binary search on a sorted array to find the index of the target value.

Example
bsearch([1, 3, 5, 7, 9], 5)
Result
2
cbrt(number: number): number function

Returns the cube root of the given number.

Example
cbrt(27)
Result
3
ceil(number: number): number function

Rounds the given number up to the nearest integer.

Example
ceil(3.2)
Result
4
clamp(x, lo, hi): number function

Clamps a number between a minimum and maximum value.

Example
clamp(15, 0, 10)
Result
10
cos(number: number): number function

Returns the cosine of the given number (in radians).

Example
cos(0)
Result
1
cosh(number: number): number function

Returns the hyperbolic cosine of the given number.

Example
cosh(0)
Result
1
count_by(arr, f): number function

Returns the count of elements in the array that satisfy the provided function.

Example
count_by([1, 2, 3, 4], fn(x): x > 2;)
Result
2
cumavg(arr): array function

Returns an array of running (cumulative) averages of the given array of numbers.

Example
cumavg([1, 2, 3, 4])
Result
[1, 1.5, 2, 2.5]
cumsum(arr): array function

Returns an array of running (cumulative) sums of the given array of numbers.

Example
cumsum([1, 2, 3, 4])
Result
[1, 3, 6, 10]
describe(arr): dict function

Returns a dict of summary statistics for an array of numbers: {min, max, mean, median, stddev, variance, count}. Returns None if the array is empty.

Example
describe([1, 2, 3, 4, 5])
Result
{"count": 5, "min": 1, "max": 5, "median": 3, "mean": 3, "variance": 2, "stddev": 1.4142135623730951}
div(value1, value2) function

Divides the first value by the second value.

Example
div(6, 2)
Result
3
exp(number: number): number function

Returns the exponential (e^x) of the given number.

Example
exp(0)
Result
1
floor(number: number): number function

Rounds the given number down to the nearest integer.

Example
floor(3.8)
Result
3
gcd(a, b): number function

Returns the greatest common divisor of two integers. Raises an error if an argument is not a finite integer.

Example
gcd(12, 18)
Result
6
geomean(arr): number function

Returns the geometric mean of an array of numbers, or None if the array is empty.

Example
geomean([1, 4])
Result
2
histogram(arr, buckets): array function

Buckets a numeric array into buckets equal-width bins between its min and max, returning an array of {range, count, bar}; bar is a block-character bar scaled so the tallest bucket is 40 characters wide, handy for a quick terminal or Markdown look at a distribution.

Example
get(histogram([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)[0], "range")
Result
1-2.8
human_bytes(n): string function

Formats a byte count as a human-readable decimal (SI, 1000-based) string, e.g. human_bytes(1500) => "1.5KB". Negative numbers keep their sign.

Example
human_bytes(1500)
Result
1.5KB
human_size(n): string function

Formats a byte count as a human-readable binary (IEC, 1024-based) string without the "i" suffix, matching numfmt --to=iec, e.g. human_size(1536) => "1.5K". Negative numbers keep their sign.

Example
human_size(1536)
Result
1.5K
hypot(x: number, y: number): number function

Returns the length of the hypotenuse, sqrt(x^2 + y^2).

Example
hypot(3, 4)
Result
5
infinite(): number function

Returns an infinite number value.

is_integer(n): bool function

Returns true if the number is an integer.

is_nan(value: number): boolean function

Returns true if the given number is NaN.

Example
is_nan(nan())
Result
true
lcm(a, b): number function

Returns the least common multiple of two integers. Raises an error if an argument is not a finite integer.

Example
lcm(4, 6)
Result
12
ln(number: number): number function

Returns the natural logarithm (base e) of the given number.

Example
ln(1)
Result
0
log(number: number): number function

Returns the natural logarithm (base e) of the given number.

Example
log(1)
Result
0
log10(number: number): number function

Returns the base-10 logarithm of the given number.

Example
log10(100)
Result
2
log2(number: number): number function

Returns the base-2 logarithm of the given number.

Example
log2(8)
Result
3
max(value1, value2) function

Returns the maximum of two values.

Example
max(1, 2)
Result
2
max_by(arr, f) function

Returns the maximum element in an array based on a provided function that extracts a comparable value from each element.

Example
max_by([3, 1, 2], identity)
Result
3
mean(arr): number function

Returns the average (mean) of an array of numbers, or None if the array is empty.

Example
mean([1, 2, 3])
Result
2
median(arr): number function

Returns the median of an array of numbers, or None if the array is empty.

Example
median([1, 2, 3, 4])
Result
2.5
min(value1, value2) function

Returns the minimum of two values.

Example
min(1, 2)
Result
1
min_by(arr, f) function

Returns the minimum element in an array based on a provided function that extracts a comparable value from each element.

Example
min_by([3, 1, 2], identity)
Result
1
mod(value1, value2) function

Calculates the remainder of the division of the first value by the second value.

Example
mod(7, 3)
Result
1
mode(arr): array function

Returns the mode(s) of an array, i.e. the most frequently occurring value(s). Multiple values are returned if there is a tie for the highest frequency. Returns None if the array is empty.

Example
mode([1, 2, 2, 3])
Result
[2]
mul(value1, value2) function

Multiplies two values.

Example
mul(2, 3)
Result
6
nan(): number function

Returns a Not-a-Number (NaN) value.

negate(number: number): number function

Returns the negation of the given number.

Example
negate(5)
Result
-5
percentile(arr, p): number function

Calculates the p-th percentile of an array of numbers using linear interpolation between closest ranks.

Example
percentile([1, 2, 3, 4, 5], 0.5)
Result
3
pow(base: number, exponent: number): number function

Raises the base to the power of the exponent.

Example
pow(2, 10)
Result
1024
product(arr): number function

Returns the product of the numbers in an array.

Example
product([1, 2, 3, 4])
Result
24
rand(seed?: number): number function

Generates a pseudo-random number in the range [0, 1). Not cryptographically secure. seed is optional; when given, the result is a deterministic function of it instead of OS entropy.

rand_int(min: number, max: number, seed?: number): number function

Generates a pseudo-random integer uniformly distributed in [min, max] (inclusive). Not cryptographically secure. seed is optional; when given, the result is a deterministic function of it instead of OS entropy.

round(number: number): number function

Rounds the given number to the nearest integer.

Example
round(3.5)
Result
4
shift_left(value, shift_amount: number) function

Performs a left shift operation on the given value: for numbers, this is a bitwise left shift by the specified number of positions; for strings, this removes characters from the start; for Markdown headings, this increases the heading level accordingly.

Example
shift_left(1, 2)
Result
4
shift_right(value, shift_amount: number) function

Performs a bitwise right shift on numbers, slices characters from the end of strings, and adjusts Markdown heading levels when applied to headings, using the given shift amount.

Example
shift_right(8, 2)
Result
2
sin(number: number): number function

Returns the sine of the given number (in radians).

Example
sin(0)
Result
0
sinh(number: number): number function

Returns the hyperbolic sine of the given number.

Example
sinh(0)
Result
0
sqrt(number: number): number function

Returns the square root of the given number.

Example
sqrt(9)
Result
3
stats_by(arr, group_f, value_f, aggs): array function

Groups arr by group_f and computes summary statistics over value_f(x) for each group, returning an array of dicts {group, count, ...aggs} ready to pipe into -F table or -F csv. group and count are always included; aggs picks which of sum, mean, min, max, stddev, median, variance to compute.

Example
stats_by([{"g": "a", "v": 1}, {"g": "a", "v": 3}, {"g": "b", "v": 2}], fn(x): get(x, "g");, fn(x): get(x, "v");)
Result
[{"count": 2, "min": 1, "max": 3, "group": "a", "sum": 4, "mean": 2, "stddev": 1}, {"count": 1, "min": 2, "max": 2, "group": "b", "sum": 2, "mean": 2, "stddev": 0}]
stddev(arr): number function

Returns the population standard deviation of an array of numbers, or None if the array is empty.

Example
stddev([2, 4, 4, 4, 5, 5, 7, 9])
Result
2
sub(value1, value2) function

Subtracts the second value from the first value.

Example
sub(5, 2)
Result
3
sum(arr): number function

Returns the sum of the elements in an array after applying a transformation function to each element.

Example
sum([1, 2, 3])
Result
6
sum_by(arr, f): number function

Sums elements of an array after applying a transformation function.

Example
sum_by([1, 2, 3], fn(x): mul(x, 2);)
Result
12
tan(number: number): number function

Returns the tangent of the given number (in radians).

Example
tan(0)
Result
0
tanh(number: number): number function

Returns the hyperbolic tangent of the given number.

Example
tanh(0)
Result
0
top_by(arr, f, n, group_f) function

Returns the top n elements of an array, ranked by descending value of a key function. Pass group_f to rank independently within each group (grouped the same way as group_by), which returns a dict of {group: [top elements]} instead of a flat array.

Example
top_by([3, 1, 4, 1, 5, 9, 2], identity, 3)
Result
[9, 5, 4]
trunc(number: number): number function

Truncates the given number to an integer by removing the fractional part.

Example
trunc(3.9)
Result
3
variance(arr): number function

Returns the population variance of an array of numbers, or None if the array is empty.

Example
variance([2, 4, 4, 4, 5, 5, 7, 9])
Result
4
xor(a: number | bytes, b: number | bytes): number | bytes function

Computes the bitwise XOR: of two byte arrays of equal length, or of two integers from 0 to 2^53 - 1.

Example
xor(12, 10)
Result
6

Types & Logic46

and(value1: bool, value2: bool): bool function

Performs a logical AND operation on two boolean values.

Example
and(true, false)
Result
false
array(args): array function

Creates an array from the given values

Example
array(1, 2, 3)
Result
[1, 2, 3]
arrays(a) function

Returns array if input is array, None otherwise

Example
arrays([1, 2])
Result
[1, 2]
between(value, min, max): bool function

Checks if a value is between min and max (inclusive).

Example
between(5, 1, 10)
Result
true
booleans(b) function

Returns boolean if input is boolean, None otherwise

Example
booleans(true)
Result
true
bytes(b) function

Returns bytes if input is bytes, None otherwise

Example
bytes(to_bytes("hi"))
Result
6869
coalesce(value1, value2) function

Returns the first non-None value from the two provided arguments.

Example
coalesce(None, 5)
Result
5
complement(f): bool function

Returns a new predicate function that negates the result of the given function.

Example
let f = complement(is_none) | f(1)
Result
true
convert(input, format: string) function

Converts the input value to the specified format. Supported formats: base64, html, text, uri, heading (#, ##, etc.), blockquote (>), list item (-), or link (URL).

dict(): dict function

Creates a new, empty dict.

Example
dict()
Result
{}
dicts(d) function

Returns dict if input is dict, None otherwise

Example
dicts({"a": 1})
Result
{"a": 1}
eq(a, b): bool function

Checks if two values are equal

Example
eq(1, 1)
Result
true
gt(a, b): bool function

Checks if the first value is greater than the second

Example
gt(2, 1)
Result
true
gte(a, b): bool function

Checks if the first value is greater than or equal to the second

Example
gte(1, 1)
Result
true
identity(x) function

Returns the input value unchanged.

Example
identity(1)
Result
1
in(v, elem): bool function

Returns true if the element is in the array.

Example
in([1, 2, 3], 2)
Result
true
is_array(a): bool function

Checks if input is an array

Example
is_array([1, 2])
Result
true
is_blank(s): bool function

Returns true if the string is empty or contains only Unicode whitespace.

Example
is_blank("   ")
Result
true
is_bool(b): bool function

Checks if input is a boolean

Example
is_bool(true)
Result
true
is_bytes(b): bool function

Checks if input is bytes

Example
is_bytes(to_bytes("hi"))
Result
true
is_coroutine(c): bool function

Checks if input is a generator function's coroutine

Example
def g(): yield: 1; | is_coroutine(g())
Result
true
is_dict(d): bool function

Checks if input is a dictionary

Example
is_dict({"a": 1})
Result
true
is_empty(s): bool function

Checks if string, array or dict is empty

Example
is_empty([])
Result
true
is_markdown(m): bool function

Checks if input is markdown

Example
is_markdown(to_h("t", 1))
Result
true
is_none(n): bool function

Checks if input is None

Example
is_none(None)
Result
true
is_number(n): bool function

Checks if input is a number

Example
is_number(1)
Result
true
is_string(s): bool function

Checks if input is a string

Example
is_string("hi")
Result
true
iterables(v) function

Returns the value if it is an array or dict (i.e. a container that can be iterated over), None otherwise

Example
iterables([1, 2])
Result
[1, 2]
lt(a, b): bool function

Checks if the first value is less than the second

Example
lt(1, 2)
Result
true
lte(a, b): bool function

Checks if the first value is less than or equal to the second

Example
lte(1, 1)
Result
true
markdowns(m) function

Returns markdown if input is markdown, None otherwise

Example
markdowns(to_h("t", 1))
Result
# t
ne(a, b): bool function

Checks if two values are not equal

Example
ne(1, 2)
Result
true
nones(n) function

Returns the value if it is None, None otherwise

Example
nones(None)
Result
not(value: bool): bool function

Performs a logical NOT operation on a boolean value.

Example
not(true)
Result
false
numbers(n) function

Returns number if input is number, None otherwise

Example
numbers(1)
Result
1
or(value1: bool, value2: bool): bool function

Performs a logical OR operation on two boolean values.

Example
or(true, false)
Result
true
scalars(v) function

Returns the value if it is not an array or dict (i.e. a leaf/scalar value), None otherwise

Example
scalars(1)
Result
1
strings(s) function

Returns string if input is string, None otherwise

Example
strings("hi")
Result
hi
to_array(value): array function

Converts the given value to an array.

Example
to_array(1)
Result
[1]
to_boolean(value): bool function

Converts the given value to a boolean. Booleans are returned unchanged, the strings "true" and "false" are converted to their boolean equivalent, and all other input results in an error.

Example
to_boolean("true")
Result
true
to_bytes(value): bytes function

Converts a string (UTF-8), array of numbers, or bytes to raw bytes.

to_coroutine(v) function

Converts an array or dictionary into a coroutine that lazily yields its elements. A coroutine input is returned unchanged. A dictionary yields its [key, value] entry pairs (matching entries()).

Example
to_coroutine([1, 2, 3]) | collect()
Result
[1, 2, 3]
to_number(value): number function

Converts the given value to a number. Strings must be a plain decimal literal (sign and exponent allowed, no surrounding whitespace or separators); inf, nan and out-of-range values are errors. true/false become 1/0, and other non-string values become 0.

Example
to_number("42")
Result
42
to_number_or(value, default): number function

Converts a value to a number, returning a default instead of raising if it can't be parsed.

Example 1
to_number_or("42", 0)
Result
42
Example 2
to_number_or("not a number", 0)
Result
0
to_string(value): string function

Converts the given value to a string.

Example
to_string(1)
Result
1
type(value): string function

Returns the type of the given value.

Example
type(1)
Result
number

Date & Time12

date_add(array: array, n: number, unit: string): array function

Adds n units to a broken-down time array and returns a new array. Units: "seconds", "minutes", "hours", "days", "weeks", "months", "years". Month/year arithmetic is calendar-aware.

date_diff(array1: array, array2: array, unit: string): number function

Returns the difference (array2 - array1) in the given unit. Units: "seconds", "minutes", "hours", "days", "weeks".

Example
date_diff(gmtime(0), gmtime(86400), "days")
Result
1
date_relative(base_timestamp: number, date_str: string): number function

Parses a natural-language relative date expression (e.g. "3 days ago", "yesterday", "tomorrow", "next monday", "in 2 weeks") relative to a base Unix timestamp and returns the resulting Unix timestamp (seconds, UTC).

from_date(date_str: string): number function

Converts a date string to a timestamp.

Example
from_date("1970-01-01T00:00:00Z")
Result
0
gmtime(timestamp: number): array function

Converts Unix timestamp (seconds since epoch) to broken-down UTC time array [year, mon (0-11), mday, hour, min, sec, wday (0=Sun), yday (0-365)].

Example
gmtime(0)
Result
[1970, 0, 1, 0, 0, 0, 4, 0]
localtime(timestamp: number): array function

Converts Unix timestamp (seconds since epoch) to broken-down local time array [year, mon (0-11), mday, hour, min, sec, wday (0=Sun), yday (0-365)].

mktime(time_array: array): number function

Converts broken-down UTC time array [year, mon (0-11), mday, hour, min, sec, wday, yday] to Unix timestamp (seconds since epoch).

Example
mktime(gmtime(0))
Result
0
now(): number function

Returns the current timestamp.

strftime(timestamp: number, format: string): string function

Formats a Unix timestamp (seconds) as a date string using the given strftime format (e.g. "%Y-%m-%d").

Example
strftime(0, "%Y-%m-%d")
Result
1970-01-01
strptime(date_str: string, format: string): number function

Parses a date string using the given strptime format (e.g. "%Y-%m-%d") and returns a Unix timestamp (seconds, UTC).

Example
strptime("1970-01-01", "%Y-%m-%d")
Result
0
to_date(timestamp: number, format: string): string function

Converts a timestamp to a date string with the given format.

Example
to_date(0, "%Y-%m-%d")
Result
1970-01-01
to_date_iso8601(d): string function

Formats a date to ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ)

Example
to_date_iso8601(0)
Result
1970-01-01T00:00:00Z

Regex & Encoding36

base64(input: string): string function

Encodes the given string to base64.

Example
base64("hi")
Result
aGk=
base64d(input: string): string function

Decodes the given base64 string.

Example
base64d("aGk=")
Result
hi
base64d_bytes(input: string): bytes function

Decodes the given base64 string to raw bytes. Unlike base64d, this does not assume the decoded data is UTF-8 text, so arbitrary binary data round-trips losslessly.

base64url(input: string): string function

Encodes the given string to URL-safe base64.

Example
base64url("hi")
Result
aGk
base64urld(input: string): string function

Decodes the given URL-safe base64 string.

Example
base64urld(base64url("hi"))
Result
hi
base64urld_bytes(input: string): bytes function

Decodes the given URL-safe base64 string to raw bytes. Unlike base64urld, this does not assume the decoded data is UTF-8 text, so arbitrary binary data round-trips losslessly.

capture(string: string, pattern: string): dict function

Captures named groups from the given string based on the specified regular expression pattern and returns them as a dictionary keyed by group names.

Example
capture("v1.2.3", "(?P<major>[0-9]+)")
Result
{"major": "1"}
decode(bytes: bytes, label: string): string function

Decodes bytes as text using a WHATWG encoding label (e.g. "shift_jis", "utf-16le", "euc-jp"; case-insensitive, and common aliases such as "latin1" or "ascii" are accepted). Supported encodings: UTF-8, UTF-16BE, UTF-16LE, IBM866, ISO-2022-JP, ISO-8859-2 through ISO-8859-8 (and ISO-8859-8-I), ISO-8859-10, ISO-8859-13 through ISO-8859-16, KOI8-R, KOI8-U, Shift_JIS, EUC-JP, EUC-KR, Big5, GBK, gb18030, macintosh, x-mac-cyrillic, x-user-defined, windows-874, windows-1250 through windows-1258 (see https://encoding.spec.whatwg.org/#names-and-labels for the full label list, including aliases). Returns an error if the label is unrecognized or the bytes contain a sequence invalid for that encoding, rather than silently substituting replacement characters.

Example
decode(encode("hi", "shift_jis"), "shift_jis")
Result
hi
encode(text: string, label: string): bytes function

Encodes text as bytes using a WHATWG encoding label (e.g. "shift_jis", "utf-16le", "euc-jp"; case-insensitive, and common aliases such as "latin1" or "ascii" are accepted). Supported encodings: UTF-8, UTF-16BE, UTF-16LE, IBM866, ISO-2022-JP, ISO-8859-2 through ISO-8859-8 (and ISO-8859-8-I), ISO-8859-10, ISO-8859-13 through ISO-8859-16, KOI8-R, KOI8-U, Shift_JIS, EUC-JP, EUC-KR, Big5, GBK, gb18030, macintosh, x-mac-cyrillic, x-user-defined, windows-874, windows-1250 through windows-1258 (see https://encoding.spec.whatwg.org/#names-and-labels for the full label list, including aliases). Returns an error if the label is unrecognized or the text contains a character unmappable in that encoding, rather than silently substituting a replacement byte.

from_hex(hex_string: string): bytes function

Parses a hex string into raw bytes.

glob_match(pattern: string, path: string): bool function

Checks whether the given path matches the glob pattern (e.g. "*.md", "docs/**/*.rs"), commonly used to filter file lists.

Example
glob_match("*.md", "readme.md")
Result
true
gsub(from: string, pattern: string, to: string): string function

Replaces all occurrences matching a regular expression pattern with the replacement string.

Example
gsub("a1b2", "[0-9]", "#")
Result
a#b#
hexdump(bytes: bytes): string function

Renders bytes as a hexdump (offset, hex bytes, ASCII gutter), like xxd/hexdump -C.

Example
hexdump(to_bytes("hi"))
Result
00000000  68 69                                             |hi|
html_escape(string: string): string function

Escapes &, <, >, ", and ' in the given string as HTML entities.

Example
html_escape("<a>")
Result
&lt;a&gt;
html_unescape(string: string): string function

Decodes named and numeric HTML entities in the given string into their corresponding characters.

Example
html_unescape("&lt;a&gt;")
Result
<a>
is_not_regex_match(string: string, pattern: string): bool function

Checks if the given pattern does not match the string.

Example
is_not_regex_match("abc", "x")
Result
true
is_regex_match(string: string, pattern: string): bool function

Checks if the given pattern matches the string.

Example
is_regex_match("abc", "a.c")
Result
true
markdown_escape(string: string, context: string): string function

Escapes the given string so it renders as literal text at the given output position ("text", "heading", "link_label", "table_cell", or "code"), without introducing unintended Markdown structure. Not for HTML sanitization or URL-encoding; use html_escape, sanitize_html, or url_encode for those.

Example 1
markdown_escape("**bold**", "text")
Result
\*\*bold\*\*
Example 2
markdown_escape("a | b", "table_cell")
Result
a \| b
md5(input): string function

Computes the MD5 hash of a string or bytes and returns a lowercase hex string.

pack(format: string, value: number): bytes function

Packs a number into bytes using the given format. Supported formats: u8, i8, u16be/le, i16be/le, u32be/le, i32be/le, u64be/le, i64be/le, f32be/le, f64be/le.

redact(value, rules) function

Recursively masks matching values in a dict/array/string/markdown node, given rules: an array of {type: "key", pattern, replacement = "[REDACTED]", case_insensitive = true} (masks a dict value outright when its key matches pattern, without looking at the value) or {type: "value", pattern, replacement = "[REDACTED]", case_insensitive = true} (replaces matches of pattern inside string or markdown node text via gsub, leaving the rest of the text intact). pattern is matched case-sensitively against the (optionally downcased) subject unless pattern itself starts with (?i). Numbers, booleans and None pass through unchanged. A markdown node with children (e.g. a heading, list, or link) is walked by redacting each child; a leaf node (e.g. text, code, code_inline, html, yaml, toml, image, definition) has value-type rules applied directly to its own text, so key-type rules only ever apply to dict keys, never to markdown structure.

Example
redact({"user": "alice", "password": "hunter2"}, [{type: "key", pattern: "password"}])
Result
{"user": "alice", "password": "[REDACTED]"}
regex_escape(string: string): string function

Escapes regular expression metacharacters in the given string so it can be used literally in a regex pattern (e.g. with regex_match, is_regex_match, capture, scan, gsub, or split). This is for building patterns from dynamic input, not for escaping replacement strings.

Example
regex_escape("a.b*c?")
Result
a\.b\*c\?
regex_match(string: string, pattern: string): array function

Finds all matches of the given pattern in the string.

Example
regex_match("abc123", "[0-9]+")
Result
["123"]
regex_replace(text, pattern, f): string function

Replaces matches of pattern in text, calling f for each match instead of using a fixed replacement string (unlike gsub). f receives a dict with match (the matched text), captures (a dict of capture groups, keyed by number, e.g. "1", and by name for named groups) and the match's start/end UTF-8 byte offsets. f must return a string.

Example
regex_replace("a1b2", "[0-9]", fn(m): "[" + m["match"] + "]";)
Result
a[1]b[2]
replace_prose(value, pattern, replacement) function

Replaces matches of pattern with replacement (via gsub) inside a string or markdown node's prose text only. Only text nodes are substituted, so code, html, front matter, math, and link destinations are left untouched.

Example
replace_prose("Use foo to call foo.", "foo", "bar")
Result
Use bar to call bar.
scan(string: string, pattern: string): array function

Finds all matches of a regular expression pattern in the string. For each match, returns the captured groups as an array if the pattern has capture groups, otherwise returns the whole match as a string.

Example
scan("a1b2", "[0-9]")
Result
["1", "2"]
sha256(input): string function

Computes the SHA-256 hash of a string or bytes and returns a lowercase hex string.

sha512(input): string function

Computes the SHA-512 hash of a string or bytes and returns a lowercase hex string.

shell_quote(s): string function

Quotes a string for safe use as a POSIX shell argument (like jq's @sh format).

Example
shell_quote("it's a test")
Result
'it'"'"'s a test'
test(s, pattern): bool function

Tests if string matches a pattern

Example
test("abc", "a.c")
Result
true
to_hex(bytes: bytes): string function

Encodes raw bytes as a lowercase hex string.

Example
to_hex(from_hex("6869"))
Result
6869
unpack(format: string, bytes: bytes): number function

Unpacks a number from bytes using the given format. Supported formats: u8, i8, u16be/le, i16be/le, u32be/le, i32be/le, u64be/le, i64be/le, f32be/le, f64be/le.

url_decode(input: string): string function

URL-decodes the given string.

Example
url_decode("a%20b")
Result
a b
url_encode(input: string): string function

URL-encodes the given string.

Example
url_encode("a b")
Result
a%20b
utf8(bytes: bytes): string function

Decodes bytes as a UTF-8 string, returning an error if the bytes are not valid UTF-8.

Example
utf8(to_bytes("hi"))
Result
hi
utf8bytelen(string: string): number function

Returns the number of bytes of the given string when encoded as UTF-8.

Example
utf8bytelen("héllo")
Result
6

Files & I/O35

basename(path: string): string function

Returns the final component of a path string (e.g. "file.txt" from "/a/b/file.txt").

Example
basename("/a/b/file.txt")
Result
file.txt
close(stream) function

Forces a generator coroutine to completion, releasing its suspended frames early instead of waiting for it to be dropped.

Example
def g(): yield: 1; | let stream = g() | close(stream) | next(stream)
Result
{"value": , "done": true}
collection(dir: string, respect_gitignore?: boolean): array functionrequires file-io

Recursively reads every Markdown file in the given directory (including subdirectories and symlinked files/directories) and returns an array of {path, title, frontmatter, content} dicts, sorted by path, so they can be filtered, sorted, or aggregated as a single dataset. content holds the file's Markdown nodes with frontmatter stripped. Symlink cycles are detected and only visited once. respect_gitignore is optional (default false); when true, dotfiles/dot-directories and any path matched by a .gitignore in dir or a subdirectory are skipped, with closer .gitignore files taking precedence, same as git. Requires the --allow-read CLI flag; otherwise returns a runtime error.

dirname(path: string): string function

Returns the parent directory of a path string (e.g. "/a/b" from "/a/b/file.txt"). Returns "." if the path has no parent.

Example
dirname("/a/b/file.txt")
Result
/a/b
env(): dict function

Returns all --allow-env-permitted env vars as a dict; env(name) returns one value, or None if unset.

extname(path: string): string function

Returns the extension of a file path including the leading dot (e.g. ".txt" from "file.txt"). Returns an empty string if there is no extension.

Example
extname("file.txt")
Result
.txt
file_exists(path: string): bool functionrequires file-io

Checks if a file exists at the given path. Requires the --allow-read CLI flag; otherwise returns a runtime error.

file_info(path: string): dict functionrequires file-io

Returns {path, kind, size, modified} for the entry at the given path: kind is "file", "dir", "symlink", or "other"; size is in bytes; modified is a unix timestamp in seconds, or None if unavailable. A symlink is reported as "symlink" and never followed. Requires the --allow-read CLI flag; otherwise returns a runtime error.

file_size(path: string): number functionrequires file-io

Returns the size, in bytes, of the file at the given path. Requires the --allow-read CLI flag; otherwise returns a runtime error.

http(method: string, url: string, body: string, headers: dict): string functionrequires http

Performs an HTTPS request with the given method (a string or symbol, e.g. "post" or :post; get, post, put, delete, patch, head, ... are all supported) and returns the response body as a string. An optional body argument (string) sends a request body regardless of method, and an optional headers argument (a dict of string to string, e.g. {"Content-Type": "application/json"}) is applied to the request. Requires the --allow-net CLI flag; otherwise returns a runtime error. Only https:// URLs are allowed.

http_all(requests: array): array functionrequires http

Performs a batch of HTTPS requests and returns the response bodies as an array of strings in request order. Each request is a dict with a url string and optional method (string or symbol, default GET), body (string) and headers (dict of string to string). Requires the --allow-net CLI flag; otherwise returns a runtime error. Only https:// URLs are allowed.

http_lines(method, url, body, headers) function

Lazily yields each line of the response body for an HTTPS request with the given method, without its line terminator, instead of waiting for the whole response. body, when given, is sent regardless of method; headers is a dict of string to string. The connection is opened immediately, and closed when the stream finishes or is passed to close(). Requires the http feature.

input(): string function

Reads a line from standard input and returns it as a string.

load_markdown(path): array function

Loads a markdown file from the specified path

open_file(path: string): file functionrequires file-io

Opens the file at the given path for incremental reading and returns a file handle. Read from it with read_line or read_bytes. The file is closed by close(handle), or automatically when the handle (or a coroutine holding it) is closed, finishes, or is dropped. Requires the --allow-read CLI flag; otherwise returns a runtime error.

open_http(method: string, url: string, body: string, headers: dict): http functionrequires http

Opens an HTTPS request with the given method (a string or symbol, same as http()) and returns the response body as a streaming reader handle instead of buffering it, so it can be read incrementally with read_line/read_bytes rather than waiting for the whole response. body/headers behave the same as http(). The connection is closed by close(handle), or automatically when the handle (or a coroutine holding it) is closed, finishes, or is dropped. Requires the --allow-net CLI flag; otherwise returns a runtime error. Only https:// URLs are allowed.

path_join(base: string, component: string): string function

Joins a base path with a component path and returns the resulting path string (e.g. path_join("/a/b", "c.txt") → "/a/b/c.txt").

Example
path_join("/a/b", "c.txt")
Result
/a/b/c.txt
print(message: string) function

Prints a message to standard output and returns the current value.

read_bytes(handle, size: number): bytes functionrequires file-io or http

Reads up to size bytes from a reader handle (fewer only at end of file), or returns None at end of file. size must be a positive integer. Errors if the handle is closed.

read_file(path: string): string functionrequires file-io

Reads the contents of a file at the given path and returns it as a string. Requires the --allow-read CLI flag; otherwise returns a runtime error.

read_file_bytes(path: string): bytes functionrequires file-io

Reads the contents of a file at the given path and returns it as raw bytes. Requires the --allow-read CLI flag; otherwise returns a runtime error.

read_line(handle): string functionrequires file-io or http

Reads the next line from a reader handle without its \n/\r\n terminator, or returns None at end of file. Errors if the handle is closed or the line is not valid UTF-8.

safe_filename(name, max_length): string function

Converts a string into a filesystem-safe filename by replacing characters that are invalid or reserved on common filesystems (control characters and <>:"/\|?*), trimming trailing dots and spaces, renaming Windows reserved device names (e.g. CON), and truncating to max_length characters while preserving the file extension.

Example
safe_filename("My: Report? <2024>.pdf")
Result
My_ Report_ _2024_.pdf
send(stream, value): dict function

Resumes a generator coroutine like next, but resumes its suspended yield expression to value instead of None.

Example
def g(): let a = yield: 1 | yield: a; | let stream = g() | next(stream) | send(stream, 2)
Result
{"value": 2, "done": false}
status(stream): symbol function

Returns a generator coroutine's lifecycle state as a symbol: :created, :suspended, :running, :completed, or :failed.

Example
def g(): yield: 1; | status(g())
Result
:created
stderr(message: string) function

Prints a message to standard error and returns the current value.

stem(path: string): string function

Returns the file name without the extension (e.g. "file" from "/a/b/file.txt").

Example
stem("/a/b/file.txt")
Result
file
stream_bytes(path) function

Lazily yields each byte of the file at path as a number from 0 to 255. The file is opened immediately, and closed when the stream finishes or is passed to close(). Requires the file-io feature.

stream_chunks(path, size) function

Lazily yields the file at path as chunks of up to size bytes. The file is opened immediately, and closed when the stream finishes or is passed to close(). Requires the file-io feature.

stream_lines(path) function

Lazily yields each line of the file at path without its line terminator. The file is opened immediately, and closed when the stream finishes or is passed to close(). Requires the file-io feature.

stream_range(start, stop, step) function

Lazily yields numbers from start to stop (inclusive), like range but without building an array. step defaults to 1, or -1 when start > stop. A stop of None yields numbers without bound. String arguments behave like range: single characters are yielded lazily, longer strings (e.g. "aa" to "zz") are generated eagerly.

system(command: string, args: array): string functionrequires process-io

Runs command as a child process, optionally passing an array of string args, and returns its captured stdout as a string. The command is never run through a shell, so shell metacharacters in args are never interpreted. A non-zero exit status is a runtime error that includes the process's stderr. Requires the --allow-run CLI flag; otherwise returns a runtime error.

walk_files(root: string, pattern?: string, options?: dict): array functionrequires file-io

Recursively enumerates filesystem entries under root whose root-relative path (using / as the separator regardless of platform) matches the glob pattern (default "**", i.e. every file), returning a stable-sorted array of those relative path strings. Unlike collection, this reads neither file contents nor Markdown. An optional third argument is a dict of options: respect_gitignore (default false, same semantics as collection) and follow_symlinks (default false; a symlinked file is always included if it matches, only directory traversal is affected). Requires the --allow-read CLI flag; otherwise returns a runtime error.

write_file(path: string, content) functionrequires file-io

Writes content (string or bytes) to the file at the given path, creating or truncating it. Requires the --allow-write CLI flag; otherwise returns a runtime error.

Utilities19

all_symbols(): array function

Returns an array of all interned symbols.

breakpoint() function

Sets a breakpoint for debugging; execution will pause at this point if a debugger is attached.

comp(fns) function

Composes functions into one function, applying them right-to-left. comp(f, g, h)(x) is equivalent to f(g(h(x))).

Example
let f = comp(fn(x): x + 1;, fn(x): x * 2;) | f(3)
Result
7
debug(args) function

Prints the debug information of the given value(s).

error(message: string) function

Raises a user-defined error with the specified message.

flip(f, a, b) function

Returns a new function that takes the same arguments as the original function but with the first two arguments flipped.

Example
flip(sub, 2, 10)
Result
8
halt(exit_code: number) function

Terminates the program with the given exit code.

halt_error() function

Halts execution with error code 5

inspect(value) function

Inspects a value by printing its string representation and returning the value.

intern(string: string): string function

Interns the given string, returning a canonical reference for efficient comparison.

Example
intern("hi")
Result
hi
juxt(fns): array function

Returns a function that applies each given function to its argument and collects the results into an array. juxt(f, g, h)(x) is equivalent to [f(x), g(x), h(x)].

Example
let f = juxt(first, last) | f([1, 2, 3])
Result
[1, 3]
partial(function: function, arg1, arg2, ...): function function

Creates a new function by partially applying the given arguments to the specified function.

random_string(len: number, charset: string, seed?: number): string function

Generates a random string of len characters, each independently chosen (with replacement) from charset. Not cryptographically secure. seed is optional; when given, the result is a deterministic function of it instead of OS entropy.

sample(array: array, n: number, seed?: number): array function

Returns n elements sampled from the array without replacement, in random order. Errors if n exceeds the array length. seed is optional; when given, the sample is a deterministic function of it instead of OS entropy.

shuffle(array: array, seed?: number): array function

Returns a new array containing the same elements as the input, in a uniformly random order. seed is optional; when given, the permutation is a deterministic function of it instead of OS entropy.

tap(value, expr) function

Applies a function to a value and returns the value (useful for debugging or side effects).

Example
tap(1, 2)
Result
1
uuid(): string function

Generates a random (version 4, RFC 4122) UUID string.

uuid_v4(): string function

Generates a random (version 4, RFC 4122) UUID string. Alias of uuid.

uuid_v7(): string function

Generates a time-ordered (version 7, RFC 9562) UUID string: a millisecond Unix timestamp followed by random bits, so values sort by creation time. The timestamp is plaintext, so prefer uuid/uuid_v4 for unguessable IDs.

Other6

bit_length(n: number): number function

Returns the number of bits needed to write a non-negative integer in binary, 0 for 0.

Example 1
bit_length(255)
Result
8
Example 2
bit_length(256)
Result
9
hash(string: string, seed?: number): number function

Hashes a string to an integer below 2^53, which a number holds exactly. seed is optional; each seed gives an independent hash of the same string. The result is the same on every run and platform, so it can be stored. It is not a cryptographic hash.

Example 1
hash("hello")
Result
4952387935952618
Example 2
hash("hello", 1) != hash("hello", 2)
Result
true
hmac_sha256(key, message): string function

Computes the HMAC-SHA-256 of a message with a key (each a string or bytes) and returns a lowercase hex string.

hmac_sha512(key, message): string function

Computes the HMAC-SHA-512 of a message with a key (each a string or bytes) and returns a lowercase hex string.

mkdir(path: string): none functionrequires file-io

Creates the directory at the given path along with any missing parents, like mkdir -p. Succeeds if it already exists. Requires the --allow-write CLI flag; otherwise returns a runtime error.

regex_match_info(string: string, pattern: string): array function

Finds all matches of the given pattern in the string and describes each one: match (the matched text), start/end (UTF-8 byte offsets), char_start/char_end (code point offsets) and groups. groups holds one dict per capture group in order, with the same fields plus the group's name (None if unnamed). A group that did not take part in the match has None for match and all offsets.

Example
let m = regex_match_info("aé12", "(?P<n>[0-9])([0-9])")[0] | [m["match"], m["char_start"], m["start"], m["groups"][0]["name"]]
Result
["12", 2, 3, "n"]

CBOR Implementation in mq.

Source: cbor.mq

2 functions

cbor_parse(input) function

Parses a base64-encoded CBOR string (or raw bytes) and returns the corresponding data structure.

Module: import "cbor" | cbor::cbor_parse(...)

Example
import "cbor" | cbor::cbor_parse(cbor::cbor_stringify({"a": 1}))
Result
{"a": 1}
cbor_stringify(data): bytes function

Serializes a value to CBOR bytes.

Module: import "cbor" | cbor::cbor_stringify(...)

Example
import "cbor" | cbor::cbor_stringify(1)
Result
f93c00

CSV/TSV Implementation in mq. Based on RFC 4180 for CSV format.

Source: csv.mq

12 functions

backward_fill(rows, cols, group_by, missing, max_gap): array function

Fills missing cells in the given columns with the next non-missing value below. Takes the same arguments as forward_fill. With max_gap, the cells nearest to the value are filled.

Module: import "csv" | csv::backward_fill(...)

Example
import "csv" | csv::backward_fill([{"a": ""}, {"a": "x"}], ["a"])
Result
[{"a": "x"}, {"a": "x"}]
constant_fill(rows, defaults, missing): array function

Fills missing cells with a constant per column. defaults maps column names to values. Array rows use header names as keys. Values are inserted as given, without type conversion.

Module: import "csv" | csv::constant_fill(...)

Example
import "csv" | csv::constant_fill([{"a": ""}, {"a": "x"}], {"a": "N/A"})
Result
[{"a": "N/A"}, {"a": "x"}]
csv_needs_quote(field, delimiter): bool function

Checks whether a field's string form needs quoting for the given delimiter (RFC 4180): it contains a quote, newline, carriage return, the delimiter itself, or leading/trailing whitespace.

Module: import "csv" | csv::csv_needs_quote(...)

Example
import "csv" | csv::csv_needs_quote("a,b", ",")
Result
true
csv_parse(input, has_header): array function

Parses CSV content using a comma as the delimiter.

Module: import "csv" | csv::csv_parse(...)

Example
import "csv" | csv::csv_parse("name,age\nAlice,30", true)
Result
[{"name": "Alice", "age": "30"}]
csv_parse_with_delimiter(input, delimiter, has_header): array function

Parses CSV content with a specified delimiter and optional header row.

Module: import "csv" | csv::csv_parse_with_delimiter(...)

Example
import "csv" | csv::csv_parse_with_delimiter("a;b\n1;2", ";", true)
Result
[{"a": "1", "b": "2"}]
csv_stringify(data, delimiter): string function

Converts data to a CSV string with a specified delimiter. A row whose only field is empty is written as "", so it is not read back as a blank line.

Module: import "csv" | csv::csv_stringify(...)

Example
import "csv" | csv::csv_stringify([{"name": "Alice", "age": 30}], ",")
Result
name,age
Alice,30
csv_to_json(data): string function

Converts CSV data to a JSON string.

Module: import "csv" | csv::csv_to_json(...)

Example 1
import "csv" | csv::csv_to_json([{"name": "Alice", "age": 30}])
Result
[{"name":"Alice","age":30}]
Example 2
import "csv" | csv::csv_to_json([{"name": "back\\slash"}])
Result
[{"name":"back\\slash"}]
csv_to_markdown_table(data): string function

Converts CSV data to a Markdown table format.

Module: import "csv" | csv::csv_to_markdown_table(...)

Example
import "csv" | csv::csv_to_markdown_table([{"name": "Alice", "age": 30}])
Result
| name | age |
| --- | --- |
| Alice | 30 |
forward_fill(rows, cols, group_by, missing, max_gap): array function

Fills missing cells in the given columns with the last non-missing value above. Rows are dicts or arrays (the first array row is the header and is left as is). cols are column names, or indexes for array rows. group_by columns keep a separate carried value per group. missing is "empty", "none" or "both". max_gap limits how many consecutive missing cells are filled. Cells with no value above stay missing.

Module: import "csv" | csv::forward_fill(...)

Example
import "csv" | csv::forward_fill([{"a": "x"}, {"a": ""}], ["a"])
Result
[{"a": "x"}, {"a": "x"}]
psv_parse(input, has_header): array function

Parses PSV (Pipe-Separated Values) content.

Module: import "csv" | csv::psv_parse(...)

Example
import "csv" | csv::psv_parse("name|age\nAlice|30", true)
Result
[{"name": "Alice", "age": "30"}]
sort_rows(rows, cols, desc): array function

Sorts rows by one or more columns, keeping the header row first for array rows. cols is a column name, an array of names (indexes for array rows), or a dict of column name to "asc" or "desc" to order each column separately, in key order. Later columns break ties. desc sets the order for a name or an array and is ignored for a dict. Numeric cells sort by value, other cells as text, and empty cells last (first when descending). The sort is stable.

Module: import "csv" | csv::sort_rows(...)

Example 1
import "csv" | csv::sort_rows([{"n": "10"}, {"n": "9"}], "n")
Result
[{"n": "9"}, {"n": "10"}]
Example 2
import "csv" | csv::sort_rows([{"c": "a", "n": "1"}, {"c": "a", "n": "2"}], {"c": "asc", "n": "desc"})
Result
[{"c": "a", "n": "2"}, {"c": "a", "n": "1"}]
tsv_parse(input, has_header): array function

Parses TSV (Tab-Separated Values) content.

Module: import "csv" | csv::tsv_parse(...)

Example
import "csv" | csv::tsv_parse("name\tage\nAlice\t30", true)
Result
[{"name": "Alice", "age": "30"}]

Fuzzy Match Implementation in mq Distance calculations (Levenshtein, Jaro, Jaro-Winkler) are implemented natively in Rust for performance; this module wraps them with matching, filtering, and sorting utilities.

Source: fuzzy.mq

8 functions

fuzzy_best_match(candidates, query): dict function

Finds the best fuzzy match from candidates.

Module: import "fuzzy" | fuzzy::fuzzy_best_match(...)

Example
import "fuzzy" | fuzzy::fuzzy_best_match(["apple", "aple", "banana"], "aple")
Result
{"text": "aple", "score": 1}
fuzzy_filter(candidates, query, threshold): array function

Filters candidates by minimum fuzzy match score using Jaro-Winkler.

Module: import "fuzzy" | fuzzy::fuzzy_filter(...)

Example
import "fuzzy" | fuzzy::fuzzy_filter(["apple", "aple", "banana"], "aple", 0.8)
Result
[{"text": "aple", "score": 1}, {"text": "apple", "score": 0.9466666666666665}]
fuzzy_match(candidates, query): array function

Performs fuzzy matching on an array of strings using Jaro-Winkler distance.

Module: import "fuzzy" | fuzzy::fuzzy_match(...)

Example
import "fuzzy" | fuzzy::fuzzy_match(["apple", "aple", "banana"], "aple")
Result
[{"text": "aple", "score": 1}, {"text": "apple", "score": 0.9466666666666665}, {"text": "banana", "score": 0.47222222222222215}]
fuzzy_match_jaro(candidates, query): array function

Performs fuzzy matching using Jaro distance.

Module: import "fuzzy" | fuzzy::fuzzy_match_jaro(...)

Example
import "fuzzy" | fuzzy::fuzzy_match_jaro(["apple", "aple", "banana"], "aple")
Result
[{"text": "aple", "score": 1}, {"text": "apple", "score": 0.9333333333333332}, {"text": "banana", "score": 0.47222222222222215}]
fuzzy_match_levenshtein(candidates, query): array function

Performs fuzzy matching using Levenshtein distance.

Module: import "fuzzy" | fuzzy::fuzzy_match_levenshtein(...)

Example
import "fuzzy" | fuzzy::fuzzy_match_levenshtein(["apple", "aple", "banana"], "aple")
Result
[{"text": "aple", "score": 0}, {"text": "apple", "score": 1}, {"text": "banana", "score": 5}]
jaro(s1, s2): number function

Calculates the Jaro distance between two strings (0.0 to 1.0, where 1.0 is exact match).

Module: import "fuzzy" | fuzzy::jaro(...)

Example
import "fuzzy" | fuzzy::jaro("martha", "marhta")
Result
0.9444444444444445
jaro_winkler(s1, s2): number function

Calculates the Jaro-Winkler distance between two strings.

Module: import "fuzzy" | fuzzy::jaro_winkler(...)

Example
import "fuzzy" | fuzzy::jaro_winkler("martha", "marhta")
Result
0.9611111111111111
levenshtein(s1, s2): number function

Calculates the Levenshtein distance between two strings.

Module: import "fuzzy" | fuzzy::levenshtein(...)

Example
import "fuzzy" | fuzzy::levenshtein("kitten", "sitting")
Result
3

gron Implementation in mq.

Source: gron.mq

2 functions

gron_parse(input) function

Parses gron-style path = value; assignment statements (as produced by mq -F gron) and returns the corresponding data structure.

Module: import "gron" | gron::gron_parse(...)

Example
import "gron" | gron::gron_parse("json.a = 1;\njson.b = 2;")
Result
{"a": 1, "b": 2}
gron_stringify(data): string function

Converts a data structure into gron-style path = value; assignment statements (the inverse of gron_parse, and matching mq -F gron's output), so a value can be flattened, grepped, and reconstructed without leaving a single query. Paths are rooted at json, following the gron tool's own convention.

Module: import "gron" | gron::gron_stringify(...)

Example
import "gron" | gron::gron_stringify({"a": 1, "b": 2})
Result
json = {};
json.a = 1;
json.b = 2;

JSON Implementation in mq

Source: json.mq

15 functions

json_diff(a, b, options): array function

Returns the JSON Patch (RFC 6902) that turns a into b. Dicts are compared by key and arrays by index. A key removed in one place and added elsewhere with an equal value becomes a move; pass {moves: false} to disable that.

Module: import "json" | json::json_diff(...)

Example
import "json" | json::json_diff({"a": 1, "b": 2}, {"a": 1, "b": 3})
Result
[{"op": "replace", "path": "/b", "value": 3}]
json_merge_patch(doc, patch) function

Applies a JSON Merge Patch (RFC 7396) to doc and returns the result. Unlike json_patch, a merge patch is itself a JSON value: a null member removes the matching key, an object member merges recursively, and any other value (including an array) replaces it wholesale. If patch is not a dict, it replaces doc entirely (this is how a merge patch clears or replaces a non-dict value).

Module: import "json" | json::json_merge_patch(...)

Example
import "json" | json::json_merge_patch({"a": 1, "b": {"c": 2, "d": 3}}, {"a": None, "b": {"c": 9}})
Result
{"b": {"c": 9, "d": 3}}
json_parse(input) function

Parses a JSON string and returns the corresponding data structure.

Module: import "json" | json::json_parse(...)

Example
import "json" | json::json_parse("{\"a\": 1}")
Result
{"a": 1}
json_patch(doc, ops) function

Applies a JSON Patch (RFC 6902: add, remove, replace, move, copy, test) to doc and returns the result. Raises an error, leaving doc untouched, if an operation cannot be applied.

Module: import "json" | json::json_patch(...)

Example
import "json" | json::json_patch({"a": [1, 3]}, [{"op": "add", "path": "/a/1", "value": 2}])
Result
{"a": [1, 2, 3]}
json_pointer_del(data, pointer) function

Deletes the value at a JSON Pointer (RFC 6901). A pointer to a missing value leaves data unchanged.

Module: import "json" | json::json_pointer_del(...)

Example
import "json" | json::json_pointer_del({"a": 1, "b": 2}, "/a")
Result
{"b": 2}
json_pointer_from_path(path): string function

Converts a path array (e.g. from paths) into a JSON Pointer (RFC 6901), escaping ~ and /.

Module: import "json" | json::json_pointer_from_path(...)

Example
import "json" | json::json_pointer_from_path(["a/b", 0])
Result
/a~1b/0
json_pointer_get(data, pointer) function

Returns the value a JSON Pointer (RFC 6901) refers to, or None if it does not exist.

Module: import "json" | json::json_pointer_get(...)

Example
import "json" | json::json_pointer_get({"a": [1, 2]}, "/a/1")
Result
2
json_pointer_has(data, pointer): bool function

Returns true if a JSON Pointer (RFC 6901) refers to an existing value, even if that value is None.

Module: import "json" | json::json_pointer_has(...)

Example
import "json" | json::json_pointer_has({"a": None}, "/a")
Result
true
json_pointer_set(data, pointer, value) function

Sets the value at a JSON Pointer (RFC 6901). Missing intermediate containers are created as dicts, and - appends to an array.

Module: import "json" | json::json_pointer_set(...)

Example
import "json" | json::json_pointer_set({"a": [1]}, "/a/-", 2)
Result
{"a": [1, 2]}
json_pointer_to_path(data, pointer): array function

Converts a JSON Pointer (RFC 6901) into a path array usable with get_path/set_path/del_path. data is needed because a token like "0" is an index for an array but a key for a dict. Tokens under a missing value stay strings, and - on an array is the index one past the end. Raises an error for a pointer that does not start with / or an array token that is not an index.

Module: import "json" | json::json_pointer_to_path(...)

Example
import "json" | json::json_pointer_to_path({"a": [1, 2]}, "/a/1")
Result
["a", 1]
json_stringify(data, options): string function

Serializes a value to a JSON string. options.indent is the number of spaces per nesting level; the default 0 keeps everything on one line.

Module: import "json" | json::json_stringify(...)

Example 1
import "json" | json::json_stringify({"a": 1})
Result
{"a": 1}
Example 2
import "json" | json::json_stringify({"a": "he said \"hi\"\nbye"})
Result
{"a": "he said \"hi\"\nbye"}
json_to_markdown_table(data): string function

Converts a JSON data structure to a Markdown table.

Module: import "json" | json::json_to_markdown_table(...)

Example
import "json" | json::json_to_markdown_table([{"a": 1, "b": 2}])
Result
| a | b |
| --- | --- |
| 1 | 2 |
json_try_parse(input): dict function

Parses a JSON string without raising on invalid input.

Module: import "json" | json::json_try_parse(...)

Example 1
import "json" | json::json_try_parse("{\"a\": 1}")["ok"]
Result
true
Example 2
import "json" | json::json_try_parse("{bad")["ok"]
Result
false
merge3(base, ours, theirs): dict function

3-way merges ours and theirs against their common base. Returns {value, conflicts}: value is the merged result (favoring ours at any conflicting leaf or deletion-vs-edit clash), and conflicts lists every path where both sides changed the same leaf to different values, as {path, base, ours, theirs} (a JSON Pointer path; ours/theirs is None when that side deleted the key, which is indistinguishable from a genuine null value there). Two sides editing the same nested dict key-by-key merges recursively; anything else (arrays, scalars, one side turning a dict into something else) is compared as a whole leaf.

Module: import "json" | json::merge3(...)

Example
import "json" | json::merge3({"a": 1, "b": 1}, {"a": 2, "b": 1}, {"a": 1, "b": 3})
Result
{"value": {"a": 2, "b": 3}, "conflicts": []}
to_frontmatter(data): string function

Converts a data structure to a JSON front matter string, delimited with ;;; (the convention used by e.g. Hexo). Unlike YAML (---) and TOML (+++) front matter, mq's Markdown parser does not recognize ;;; blocks as a distinct front matter node, so this output won't round-trip through frontmatter/is_yaml/is_toml-style selectors: it's meant for generating files for tools that do support this convention.

Module: import "json" | json::to_frontmatter(...)

Example
import "json" | json::to_frontmatter({"key": 1})
Result
;;;
{"key": 1}
;;;

Builder functions for constructing markdown nodes from scratch, plus utilities for indexing and resolving reference-style links, images, and footnotes. This module is under development. APIs and behavior may change without notice. `md::reference_index` and `md::resolve_references` need every document node at once; pass `-A` on the CLI, or pipe through `nodes` in an inline query/script; a single node instead prints a stderr warning and is treated as a one-element array.

Source: md.mq

40 functions

blockquote(value): markdown function

Wraps value in a blockquote node.

Module: import "md" | md::blockquote(...)

Example
import "md" | md::blockquote("Quote")
Result
> Quote
br(): markdown function

Creates a blank line between the surrounding elements in a doc()/to_md_fragment() call.

Module: import "md" | md::br(...)

callout(value, kind, title): markdown function

Wraps value in a callout node of the given kind (e.g. "note", "warning"), with an optional custom title.

Module: import "md" | md::callout(...)

Example
import "md" | md::callout("Note text", "note", "")
Result
> [!NOTE]
> Note text
code(value, lang): markdown function

Wraps value in a fenced code block with the given lang.

Module: import "md" | md::code(...)

code_inline(value): markdown function

Wraps value in an inline code span.

Module: import "md" | md::code_inline(...)

Example
import "md" | md::code_inline("x")
Result
`x`
comment(value): markdown function

Wraps value in an HTML comment.

Module: import "md" | md::comment(...)

Example
import "md" | md::comment("todo")
Result
<!-- todo -->
definition(url, ident, title): markdown function

Creates a link reference definition node ([ident]: url "title") for ident, with an optional title.

Module: import "md" | md::definition(...)

Example
import "md" | md::definition("https://example.com", "ex", "")
Result
[ex]: https://example.com
delete(value): markdown function

Wraps value in a delete (strikethrough) node.

Module: import "md" | md::delete(...)

Example
import "md" | md::delete("Old")
Result
~~Old~~
doc(values): markdown function

Combines markdown nodes into a single markdown value. Accepts either a variable number of arguments (doc(a, b, c)) or a single array (doc([a, b, c])). Nested arrays (e.g. from map()) are flattened automatically, so components can return plain arrays of nodes and be spliced in as children.

Module: import "md" | md::doc(...)

Example
import "md" | md::doc(md::h("T", 1), md::text("hi"))
Result
# T
hi
em(value): markdown function

Wraps value in an emphasis (italic) node.

Module: import "md" | md::em(...)

Example
import "md" | md::em("Italic")
Result
*Italic*
embed(target, display): markdown function

Creates an embed of target (![[target]]), with optional display text.

Module: import "md" | md::embed(...)

Example
import "md" | md::embed("image.png")
Result
![[image.png]]
escape(value): markdown function

Escapes Markdown syntax in value so it renders literally, including a line that would otherwise start a list or a setext heading.

Module: import "md" | md::escape(...)

Example
import "md" | md::escape("a*b")
Result
a\*b
footnote(value, ident): markdown function

Wraps value in a footnote definition node identified by ident.

Module: import "md" | md::footnote(...)

Example
import "md" | md::footnote("Footnote text", "1")
Result
[^1]: Footnote text
footnote_ref(ident): markdown function

Creates a footnote reference node pointing at ident.

Module: import "md" | md::footnote_ref(...)

Example
import "md" | md::footnote_ref("1")
Result
[^1]
h(value, depth): markdown function

Wraps value in a heading node at the given depth (1-6).

Module: import "md" | md::h(...)

Example
import "md" | md::h("Title", 1)
Result
# Title
h1(value): markdown function

Shorthands for h(value, 1) through h(value, 6).

Module: import "md" | md::h1(...)

Example
import "md" | md::h2("Title")
Result
## Title
h2(value) function

Module: import "md" | md::h2(...)

h3(value) function

Module: import "md" | md::h3(...)

h4(value) function

Module: import "md" | md::h4(...)

h5(value) function

Module: import "md" | md::h5(...)

h6(value) function

Module: import "md" | md::h6(...)

hard_break(value): markdown function

Turns single newlines in value into hard line breaks; blank lines are kept.

Module: import "md" | md::hard_break(...)

Example
import "md" | split(md::hard_break("a\nb"), "\n")
Result
["a  ", "b"]
highlight(value): markdown function

Wraps value in highlight markers.

Module: import "md" | md::highlight(...)

Example
import "md" | md::highlight("key")
Result
==key==
hr(): markdown function

Creates a horizontal rule node.

Module: import "md" | md::hr(...)

Example
import "md" | md::hr()
Result
***
html(value): markdown function

Wraps value in a raw HTML node, emitted as-is.

Module: import "md" | md::html(...)

Example
import "md" | md::html("<br>")
Result
<br>
image(url, alt, title): markdown function

Creates an image node pointing to url with alt text and an optional title.

Module: import "md" | md::image(...)

Example
import "md" | md::image("https://example.com/a.png", "Alt", "")
Result
![Alt](https://example.com/a.png "")
linebreak(): markdown function

Creates a hard line break node.

Module: import "md" | md::linebreak(...)

link(url, value, title): markdown function

Creates a link node pointing to url with link text value (a string or a node, taken as its Markdown text) and an optional title.

Module: import "md" | md::link(...)

Example
import "md" | md::link("https://example.com", "Example", "")
Result
[Example](https://example.com)
list(value, level, ordered, checked): markdown function

Wraps value in a list item node at the given level (0-indexed nesting), optionally ordered (numbered) and/or checked (checkbox); pass checked = None for a plain item.

Module: import "md" | md::list(...)

Example
import "md" | md::list("Item", 0)
Result
- Item
math(value): markdown function

Wraps value in a math block node.

Module: import "md" | md::math(...)

Example
import "md" | md::math("x^2")
Result
$$
x^2
$$
math_inline(value): markdown function

Wraps value in an inline math node.

Module: import "md" | md::math_inline(...)

Example
import "md" | md::math_inline("x^2")
Result
$x^2$
reference_index(md_nodes): dict function

Scans md_nodes for link reference definitions ([ident]: url "title") and footnote definitions ([^ident]: ...), and indexes them by identifier. Each identifier maps to an array of every definition found for it, in document order, so a duplicate definition (multiple [ident]: lines for the same ident) shows up as an array with more than one entry; CommonMark resolves such a duplicate to the first one, which md::resolve_references picks. Each entry carries its location (from get_location) for building diagnostics like linkcheck output.

Module: import "md" | md::reference_index(...)

Example 1
import "md" | len(md::reference_index(to_markdown("[a][b]\n\n[b]: https://example.com \"B\""))[:links]["b"])
Result
1
Example 2
import "md" | len(md::reference_index(to_markdown("[a][b]\n\n[b]: https://x.com\n[b]: https://y.com"))[:links]["b"])
Result
2
resolve_references(md_nodes, index): array function

Resolves every reference-style link ([text][ident], including the shortcut form [ident]), reference image (![alt][ident]), and footnote reference ([^ident]) found in md_nodes against a reference index, returning one dict per reference with its type, ident, label, location, whether it resolved to a definition, whether that definition is duplicate (more than one [ident]: for the same identifier), the definition picked (CommonMark's first-match-wins, or None if unresolved), and every candidate definitions. index defaults to md::reference_index(md_nodes), resolving references against their own document. Pass an explicit index (e.g. built from a different set of nodes) to resolve references that got separated from their definitions, for example when a document is split or a section is moved into another file, which is exactly the case where a reference legitimately comes back unresolved.

Module: import "md" | md::resolve_references(...)

Example 1
import "md" | first(md::resolve_references(to_markdown("[a][b]\n\n[b]: https://example.com")))[:resolved]
Result
true
Example 2
import "md" | first(md::resolve_references(to_markdown("[a][b]\n\n[b]: https://example.com"), dict()))[:resolved]
Result
false
strong(value): markdown function

Wraps value in a strong (bold) node.

Module: import "md" | md::strong(...)

Example
import "md" | md::strong("Bold")
Result
**Bold**
table(header, rows, aligns): array function

Builds a full table from a header array of cell values and a rows array of row arrays. aligns is an array of alignment strings (e.g. ["left", "right", "center"]) matching header's length; defaults to no alignment. Returns an array of row/align nodes ready to splice into doc().

Module: import "md" | md::table(...)

Example
import "md" | md::doc(md::table(["A", "B"], [["1", "2"], ["3", "4"]]))
Result
|A|B|
|---|---|
|1|2|
|3|4|
table_align(aligns): markdown function

Creates a table alignment (header separator) row node from an array of alignments (e.g. ["left", "right", "center"]).

Module: import "md" | md::table_align(...)

Example
import "md" | md::table_align(["left", "right"])
Result
|:---|---:|
table_cell(value, row, column): markdown function

Creates a single table cell node at the given row/column.

Module: import "md" | md::table_cell(...)

Example
import "md" | md::table_cell("A1", 0, 0)
Result
A1
table_row(cells): markdown function

Creates a table row node from an array of cell values.

Module: import "md" | md::table_row(...)

Example
import "md" | md::table_row(["a", "b"])
Result
|a|b|
text(value): markdown function

Creates a plain text node from value.

Module: import "md" | md::text(...)

Example
import "md" | md::text("hi")
Result
hi
wikilink(target, text): markdown function

Creates a wikilink to target, with optional display text.

Module: import "md" | md::wikilink(...)

Example
import "md" | md::wikilink("Page", "alias")
Result
[[Page|alias]]

The section module splits and filters Markdown documents by heading section. Call it via `import "section"` then `section::fn()` (recommended, namespaced), `include "section"` then `fn()` (no namespace prefix), or `mq -A 'section::fn()'` on the command line. Section functions need every document node at once; pass `-A` on the CLI, or pipe through `nodes` in an inline query/script; a single node instead prints a stderr warning and is treated as a one-element array.

Source: section.mq

Example
import "section" | len(section::section(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), "A"))
Result
2

35 functions

all_nodes(section): array function

Returns all nodes of a section, including both the header and content.

Module: import "section" | section::all_nodes(...)

Example
import "section" | len(section::all_nodes(first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))))
Result
2
bodies(sections): array function

Extracts body from all sections.

Module: import "section" | section::bodies(...)

Example
import "section" | len(section::bodies(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"))))
Result
3
body(section): array function

Returns the body of a section (all nodes except the header).

Module: import "section" | section::body(...)

Example
import "section" | len(section::body(first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))))
Result
1
by_level(sections, l): array function

Filters sections by heading level. l can be a number (exact level) or a range array (e.g. 1..2).

Module: import "section" | section::by_level(...)

Example
import "section" | len(section::by_level(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")), 1))
Result
2
by_title(md_nodes, text, depth): array function

Returns sections whose title matches exactly (see section::title_is), unlike section::section/section::find, which match substrings via section::title_contains.

Module: import "section" | section::by_title(...)

Example
import "section" | len(section::by_title(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), "A"))
Result
1
collect(sections): array function

Flattens sections back to markdown nodes for output. This converts section objects back to their original markdown node arrays.

Module: import "section" | section::collect(...)

Example
import "section" | len(section::collect(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"))))
Result
6
containing(md_nodes, node, depth) function

Returns the section from md_nodes that contains node (matched against the section's header or membership in its children), or None if no section contains it. The reverse of picking a section apart: useful when you already have a single node in hand, e.g. from filter/is_h1 or a plain selector, and want to know which section it belongs to. Note: nodes are matched by structural equality, so a document with duplicate content (e.g. two identical headings) resolves to the first matching section.

Module: import "section" | section::containing(...)

Example
import "section" | let md = to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B") | let h = first(filter(md, is_h2)) | section::title(section::containing(md, h))
Result
A1
filter_sections(md_nodes, predicate): array function

Filters sections based on a given predicate function.

Module: import "section" | section::filter_sections(...)

Example
import "section" | len(section::filter_sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), fn(s): true;))
Result
3
find(md_nodes, pattern, depth) function

Returns the first section whose title contains the specified pattern, or None if no section matches. Shorthand for first(section::section(md_nodes, pattern, depth)), for the common case of wanting exactly one section rather than an array of matches.

Module: import "section" | section::find(...)

Example
import "section" | section::title(section::find(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), "A1"))
Result
A1
has_body(section): bool function

Checks if a section has any content beyond the header.

Module: import "section" | section::has_body(...)

Example
import "section" | section::has_body(first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"))))
Result
true
level(section): number function

Returns the header level (1-6) of a section.

Module: import "section" | section::level(...)

Example
import "section" | section::level(first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"))))
Result
1
map_sections(md_nodes, mapper): array function

Maps sections using a given mapper function.

Module: import "section" | section::map_sections(...)

Example
import "section" | section::map_sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), fn(header, children): to_text(header);)
Result
["A", "A1", "B"]
nth(sections, n) function

Returns the nth section from an array of sections (0-indexed).

Module: import "section" | section::nth(...)

Example
import "section" | section::title(section::nth(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")), 0))
Result
A
section(md_nodes, pattern, depth): array function

Returns sections whose title contains the specified pattern. If depth is true, each section spans until the next header at the same or higher level (delegates to section::sections(md_nodes, depth), see its doc for details).

Module: import "section" | section::section(...)

Example
import "section" | len(section::section(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), "A"))
Result
2
sections(md_nodes, depth): array function

Splits markdown nodes into sections based on headers. If depth is true, each section's body extends to the next heading at the same or higher level as that section's own heading, so nested subheadings' content is included in their parent's body. If depth is false (default), every heading of any level is a boundary, so a heading's body only extends to the very next heading regardless of level.

Module: import "section" | section::sections(...)

Example 1
import "section" | len(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
Result
3
Example 2
import "section" | len(section::body(first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), true))))
Result
3
shift_level(section, delta): dict function

Shifts the heading level of a section and all of its descendant headings by delta (positive demotes, e.g. h1 -> h2; negative promotes), keeping their relative depths intact. Depth is clamped to the valid 1-6 range.

Module: import "section" | section::shift_level(...)

Example
import "section" | let s = first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A"), true)) | section::level(section::shift_level(s, 1))
Result
2
split(md_nodes, level): array function

Returns an array of sections, each section is an array of markdown nodes between the specified header and the next header of the same level.

Module: import "section" | section::split(...)

Example
import "section" | len(section::split(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), 1))
Result
2
subsections(section): array function

Returns the direct child sections of a section built by section::tree (an empty array for a leaf section, or for a section not built by tree).

Module: import "section" | section::subsections(...)

Example
import "section" | len(section::subsections(first(section::tree(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))))
Result
1
title(section): string function

Returns the title text of a section (header text without the # symbols).

Module: import "section" | section::title(...)

Example
import "section" | section::title(first(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"))))
Result
A
title_contains(sections, text): array function

Filters the given list of sections, returning only those whose title contains the specified text.

Module: import "section" | section::title_contains(...)

Example
import "section" | len(section::title_contains(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")), "A"))
Result
2
title_is(sections, text): array function

Filters the given list of sections, returning only those whose title is exactly the specified text (unlike title_contains, which matches substrings).

Module: import "section" | section::title_is(...)

Example
import "section" | len(section::title_is(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")), "A"))
Result
1
title_match(sections, pattern): array function

Filters sections by a pattern match in the title text.

Module: import "section" | section::title_match(...)

Example
import "section" | len(section::title_match(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")), "^A"))
Result
2
titles(sections): array function

Extracts titles from all sections.

Module: import "section" | section::titles(...)

Example
import "section" | section::titles(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
Result
["A", "A1", "B"]
toc(sections): array function

Generates a table of contents from sections.

Module: import "section" | section::toc(...)

Example
import "section" | section::toc(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
Result
["  - A", "    - A1", "  - B"]
toc_markdown(sections): array function

Generates a Markdown table-of-contents with links to each section's heading anchor ([title](#slug)), indented by heading level. Anchors come from slugify; a repeated anchor gets a numeric suffix (-1, -2, ...) the same way GitHub disambiguates duplicate headings. Note the slug is only an approximation of GitHub's own anchor algorithm.

Module: import "section" | section::toc_markdown(...)

Example
import "section" | section::toc_markdown(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
Result
["  - [A](#a)", "    - [A1](#a1)", "  - [B](#b)"]
tree(md_nodes): array function

Groups sections into a nested tree by heading level: each section dict gets a subsections field holding the sections whose heading sits directly beneath it (recursively nested the same way). A section's own children stays exactly what section::sections would give it: the section's own body up to its next heading of any level, not including the content of its subsections. Each section also has a path (index path) used by section::tree::* to navigate.

Module: import "section" | section::tree(...)

Example
import "section" | len(section::subsections(first(section::tree(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))))
Result
1
tree::ancestors(roots, node): array function

Returns the ancestors of a section, top-level first.

Module: import "section" | section::tree::ancestors(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n### A1a\n\n# B")) | section::titles(section::tree::ancestors(roots, section::tree::at(roots, [0, 0, 0])))
Result
["A", "A1"]
tree::at(roots, idx_path) function

Returns the section at idx_path, or None.

Module: import "section" | section::tree::at(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n## A2\n\n# B")) | section::title(section::tree::at(roots, [0, 1]))
Result
A2
tree::breadcrumb(roots, node): array function

Returns the heading titles from the top level down to node.

Module: import "section" | section::tree::breadcrumb(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n### A1a")) | section::tree::breadcrumb(roots, section::tree::at(roots, [0, 0, 0]))
Result
["A", "A1", "A1a"]
tree::flatten(roots): array function

Flattens the tree into one array of sections in document order.

Module: import "section" | section::tree::flatten(...)

Example
import "section" | section::titles(section::tree::flatten(section::tree(to_markdown("# A\n\n## A1\n\n### A1a\n\n## A2\n\n# B"))))
Result
["A", "A1", "A1a", "A2", "B"]
tree::next_sibling(roots, node) function

Returns the next sibling, or None.

Module: import "section" | section::tree::next_sibling(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n## A2")) | section::title(section::tree::next_sibling(roots, section::tree::at(roots, [0, 0])))
Result
A2
tree::parent(roots, node) function

Returns the parent section, or None at the top level.

Module: import "section" | section::tree::parent(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n# B")) | section::title(section::tree::parent(roots, section::tree::at(roots, [0, 0])))
Result
A
tree::path(node): array function

Returns a section's index path in the tree ([] if not built by section::tree).

Module: import "section" | section::tree::path(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n## A2\n\n# B")) | section::tree::path(section::tree::at(roots, [0, 1]))
Result
[0, 1]
tree::prev_sibling(roots, node) function

Returns the previous sibling, or None.

Module: import "section" | section::tree::prev_sibling(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n## A2")) | section::title(section::tree::prev_sibling(roots, section::tree::at(roots, [0, 1])))
Result
A1
tree::siblings(roots, node): array function

Returns the other sections under the same parent, in document order.

Module: import "section" | section::tree::siblings(...)

Example
import "section" | let roots = section::tree(to_markdown("# A\n\n## A1\n\n## A2\n\n## A3")) | section::titles(section::tree::siblings(roots, section::tree::at(roots, [0, 1])))
Result
["A1", "A3"]

Semantic Versioning (SemVer) Implementation in mq Based on the Semantic Versioning 2.0.0 specification: https://semver.org/

Source: semver.mq

16 functions

semver_bump_major(v): dict function

Increments the major version and resets minor, patch, and pre-release.

Module: import "semver" | semver::semver_bump_major(...)

Example
import "semver" | semver::semver_to_string(semver::semver_bump_major(semver::semver_parse("1.2.3")))
Result
2.0.0
semver_bump_minor(v): dict function

Increments the minor version and resets patch and pre-release.

Module: import "semver" | semver::semver_bump_minor(...)

Example
import "semver" | semver::semver_to_string(semver::semver_bump_minor(semver::semver_parse("1.2.3")))
Result
1.3.0
semver_bump_patch(v): dict function

Increments the patch version and clears pre-release.

Module: import "semver" | semver::semver_bump_patch(...)

Example
import "semver" | semver::semver_to_string(semver::semver_bump_patch(semver::semver_parse("1.2.3")))
Result
1.2.4
semver_compare(a, b): number function

Compares two parsed SemVer dicts. Returns -1 if a < b, 0 if a == b, 1 if a > b.

Module: import "semver" | semver::semver_compare(...)

Example
import "semver" | semver::semver_compare(semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0"))
Result
-1
semver_eq(a, b): bool function

Returns true if version a equals version b (ignoring build metadata).

Module: import "semver" | semver::semver_eq(...)

Example
import "semver" | semver::semver_eq(semver::semver_parse("1.0.0"), semver::semver_parse("1.0.0"))
Result
true
semver_gt(a, b): bool function

Returns true if version a is greater than version b.

Module: import "semver" | semver::semver_gt(...)

Example
import "semver" | semver::semver_gt(semver::semver_parse("2.0.0"), semver::semver_parse("1.0.0"))
Result
true
semver_gte(a, b): bool function

Returns true if version a is greater than or equal to version b.

Module: import "semver" | semver::semver_gte(...)

Example
import "semver" | semver::semver_gte(semver::semver_parse("1.0.0"), semver::semver_parse("1.0.0"))
Result
true
semver_lt(a, b): bool function

Returns true if version a is less than version b.

Module: import "semver" | semver::semver_lt(...)

Example
import "semver" | semver::semver_lt(semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0"))
Result
true
semver_lte(a, b): bool function

Returns true if version a is less than or equal to version b.

Module: import "semver" | semver::semver_lte(...)

Example
import "semver" | semver::semver_lte(semver::semver_parse("1.0.0"), semver::semver_parse("1.0.0"))
Result
true
semver_max(versions): dict function

Returns the maximum version from an array of parsed SemVer dicts.

Module: import "semver" | semver::semver_max(...)

Example
import "semver" | semver::semver_to_string(semver::semver_max([semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0")]))
Result
2.0.0
semver_max_satisfying(versions, range): string | None function

Returns the highest version string from versions that satisfies range, or None if no version matches. See semver_satisfies for supported range syntax.

Module: import "semver" | semver::semver_max_satisfying(...)

Example
import "semver" | semver::semver_max_satisfying(["1.0.0", "1.5.0", "2.0.0"], "^1.0.0")
Result
1.5.0
semver_min(versions): dict function

Returns the minimum version from an array of parsed SemVer dicts.

Module: import "semver" | semver::semver_min(...)

Example
import "semver" | semver::semver_to_string(semver::semver_min([semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0")]))
Result
1.0.0
semver_parse(s): dict function

Parses a SemVer string into a dict with major, minor, patch, pre, and build fields.

Module: import "semver" | semver::semver_parse(...)

Example
import "semver" | semver::semver_to_string(semver::semver_parse("1.2.3-beta.1"))
Result
1.2.3-beta.1
semver_satisfies(version, range): bool function

Returns true if the given version string satisfies range. Supported terms: - Comparators: "=", "==", "!=", ">", ">=", "<", "<=". A bare version (no operator) requires an exact match. - Caret ranges: "^1.2.3" allows changes that do not modify the leftmost non-zero component (>=1.2.3,<2.0.0; ^0.2.3 -> >=0.2.3,<0.3.0; ^0.0.3 -> >=0.0.3,<0.0.4). - Tilde ranges: "~1.2.3" allows patch-level changes only (>=1.2.3,<1.3.0). - Hyphen ranges: "1.2.3 - 2.3.4" is an inclusive range (>=1.2.3,<=2.3.4). Both sides must be full major.minor.patch versions, and the hyphen must be surrounded by spaces so it isn't confused with a pre-release tag. Comma-separated terms within a group are combined with AND; || separates groups that are combined with OR (e.g. "1.0.0 - 1.2.0||>=2.0.0" matches either the hyphen range or ">=2.0.0"). Pre-release versions (e.g. "1.0.0-alpha") are ordered using the same precedence rules as semver_compare and are matched like any other version; there is no npm-style restriction that hides pre-releases from ranges that don't mention one. Example: semver_satisfies("1.5.0", ">=1.0.0,<2.0.0") == true

Module: import "semver" | semver::semver_satisfies(...)

Example 1
import "semver" | semver::semver_satisfies("1.5.0", "^1.0.0")
Result
true
Example 2
import "semver" | semver::semver_satisfies("1.1.0", "1.0.0 - 1.2.0")
Result
true
Example 3
import "semver" | semver::semver_satisfies("2.5.0", "1.0.0 - 1.2.0||>=2.0.0")
Result
true
semver_sort(versions): array function

Sorts an array of parsed SemVer dicts in ascending order.

Module: import "semver" | semver::semver_sort(...)

Example
import "semver" | map(semver::semver_sort([semver::semver_parse("2.0.0"), semver::semver_parse("1.0.0")]), semver::semver_to_string)
Result
["1.0.0", "2.0.0"]
semver_to_string(v): string function

Converts a parsed SemVer dict back to a version string.

Module: import "semver" | semver::semver_to_string(...)

Example
import "semver" | semver::semver_to_string(semver::semver_parse("1.2.3-beta"))
Result
1.2.3-beta

The table module extracts and transforms Markdown tables. This module is under development; APIs and behavior may change without notice. Call it via `import "table"` then `table::fn()`, from an inline query, a script, or `mq -A 'import "table" | table::fn()'` on the command line. Unlike `section`, `import` must always be written explicitly (no `include` shortcut). Table functions need every document node at once: pass `-A` on the CLI, or pipe through `nodes` inline.

Source: table.mq

Example
import "table" | len(table::tables(to_markdown("| a | b |\n| - | - |\n| 1 | 2 |")))
Result
1

35 functions

add_column(table, col): dict function

Add a new column to a table.

Module: import "table" | table::add_column(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::add_column(self, ["c", "9", "10"]) | table::to_csv(self)
Result
a,b,c
1,2,9
3,4,10
add_row(table, row): dict function

Add a new row to a table.

Module: import "table" | table::add_row(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::add_row(self, ["5", "6"]) | table::to_csv(self)
Result
a,b
1,2
3,4
5,6
backward_fill(table, cols, group_by, missing, max_gap): dict function

Fills empty cells in the given columns with the next non-empty value below. Takes the same arguments as table::forward_fill. With max_gap, the cells nearest to the value are filled.

Module: import "table" | table::backward_fill(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n|  | 1 |\n| x | 2 |")) | first(self) | table::backward_fill(self, ["a"]) | table::to_csv(self)
Result
a,b
x,1
x,2
column_index(table, name): number function

Returns the index of the column whose header matches name (compared as text), or -1 if no column has that header.

Module: import "table" | table::column_index(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |")) | first(self) | table::column_index(self, "b")
Result
1
column_values(table, col): array function

Returns the data values (as strings) of column col (a header name or 0-based index), one per row.

Module: import "table" | table::column_values(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::column_values(self, 1)
Result
["2", "4"]
constant_fill(table, defaults, missing): dict function

Fills empty cells with a constant per column. defaults maps header names to values, which are converted to strings. missing is "empty", "none" or "both".

Module: import "table" | table::constant_fill(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| x | 1 |\n|  | 2 |")) | first(self) | table::constant_fill(self, {"a": "N/A"}) | table::to_csv(self)
Result
a,b
x,1
N/A,2
dedupe_rows(table): dict function

Removes data rows that are exact duplicates of an earlier row (compared by cell text), keeping the first occurrence. Row numbers are renumbered so they stay consistent.

Module: import "table" | table::dedupe_rows(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::dedupe_rows(self) | table::to_csv(self)
Result
a,b
1,2
3,4
filter_rows(table, f): dict function

Filter rows in the table based on a predicate function.

Module: import "table" | table::filter_rows(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::filter_rows(self, fn(row): true;) | table::to_csv(self)
Result
a,b
1,2
3,4
filter_tables(tables, f): array function

Filter tables from markdown nodes based on a predicate function.

Module: import "table" | table::filter_tables(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | table::filter_tables(self, fn(h, r): true;) | len(self)
Result
1
forward_fill(table, cols, group_by, missing, max_gap): dict function

Fills empty cells in the given columns with the last non-empty value above. Takes the same arguments as csv::forward_fill: cols are header names or column indexes (use an index when header names repeat), group_by keeps a separate carried value per group, missing is "empty", "none" or "both", and max_gap limits consecutive fills. The header, alignment and row/column numbers are preserved.

Module: import "table" | table::forward_fill(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| x | 1 |\n|  | 2 |")) | first(self) | table::forward_fill(self, ["a"]) | table::to_csv(self)
Result
a,b
x,1
x,2
from_array(records): dict function

Builds a table structure from an array of dict records keyed by column name (the inverse of to_array). Column order follows the keys of the first record; a key missing from a later record renders as an empty cell.

Module: import "table" | table::from_array(...)

Example
import "table" | table::from_array([{"a": "1", "b": "2"}, {"a": "3", "b": "4"}]) | table::to_csv(self)
Result
a,b
1,2
3,4
get_cell(table, row_index, col) function

Returns the string value of the data cell at row_index and column col (a header name or 0-based index; rows exclude the header), or None if either index is out of range.

Module: import "table" | table::get_cell(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::get_cell(self, 1, 0)
Result
3
insert_column(table, index, col): dict function

Insert a new column into the table at index (0-indexed), shifting existing columns right. col is [header_value, row0_value, row1_value, ...], like add_column's argument. Column numbers on every cell are renumbered so they stay consistent; the new column's alignment is "none".

Module: import "table" | table::insert_column(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::insert_column(self, 1, ["c", "9", "10"]) | table::to_csv(self)
Result
a,c,b
1,9,2
3,10,4
insert_row(table, index, row): dict function

Insert a new row into the table at data-row index index (0-indexed), shifting subsequent rows down. Row numbers on every row are renumbered so they stay consistent.

Module: import "table" | table::insert_row(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::insert_row(self, 1, ["5", "6"]) | table::to_csv(self)
Result
a,b
1,2
5,6
3,4
map_cells(table, f): dict function

Applies f to the string value of every data cell in the table (the header is untouched). Row/column numbers are preserved.

Module: import "table" | table::map_cells(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| x | y |")) | first(self) | table::map_cells(self, upcase) | table::to_csv(self)
Result
a,b
X,Y
map_rows(table, f): dict function

Map a function over each row in the table.

Module: import "table" | table::map_rows(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::map_rows(self, fn(row): row;) | table::to_csv(self)
Result
a,b
1,2
3,4
nest_rows(table, col, sep): dict function

Splits each row into multiple rows by exploding a delimiter-separated value in column col: one row is emitted per split value, with every other column copied unchanged onto each generated row. A row whose col value has no sep in it still produces exactly one row.

Module: import "table" | table::nest_rows(...)

Example
import "table" | table::from_array([{"id": "1", "tags": "a;b"}]) | table::nest_rows(self, "tags", ";") | table::to_csv(self)
Result
id,tags
1,a
1,b
num_cols(table): number function

Returns the number of columns in the table.

Module: import "table" | table::num_cols(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |")) | first(self) | table::num_cols(self)
Result
2
num_rows(table): number function

Returns the number of data rows in the table (excludes the header).

Module: import "table" | table::num_rows(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::num_rows(self)
Result
2
pivot_longer(table, value_columns, names_to, values_to): dict function

Reshape a table from wide format to long format (a.k.a. melt/unpivot). value_columns is an array of column indices to unpivot; each one becomes a row holding its header name (in the names_to column) and its cell value (in the values_to column). Columns not listed in value_columns are treated as identifier columns and repeated for every unpivoted value.

Module: import "table" | table::pivot_longer(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::pivot_longer(self, [1]) | table::to_csv(self)
Result
a,name,value
1,b,2
3,b,4
pivot_wider(table, names_from, values_from): dict function

Reshape a table from long format to wide format (a.k.a. pivot/cast). names_from is the column index whose distinct values become the headers of new columns; values_from is the column index supplying the values for those new columns. Columns other than names_from and values_from are treated as identifier columns and used to group rows together.

Module: import "table" | table::pivot_wider(...)

Example
import "table" | table::tables(to_markdown("| id | name | value |\n| --- | --- | --- |\n| 1 | x | 10 |\n| 1 | y | 20 |")) | first(self) | table::pivot_wider(self, 1, 2) | table::to_csv(self)
Result
id,x,y
1,10,20
remove_column(table, col): dict function

Removes a column (header name or 0-based index) from a table.

Module: import "table" | table::remove_column(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::remove_column(self, 0) | len(self[:rows][0])
Result
1
remove_row(table, row_index): dict function

Remove a row from a table at the specified index.

Module: import "table" | table::remove_row(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::remove_row(self, 0) | table::to_csv(self)
Result
a,b
3,4
rename_column(table, col, name): dict function

Returns a new table with the header of column col (a header name or 0-based index) replaced by name.

Module: import "table" | table::rename_column(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |")) | first(self) | table::rename_column(self, 0, "x") | table::to_csv(self)
Result
x,b
1,2
select_columns(table, columns): dict function

Returns a new table containing only the given columns (header names or 0-based indices), in the order given, so this can also reorder columns. Column numbers on the resulting header/row cells are renumbered to match their new positions.

Module: import "table" | table::select_columns(...)

Example
import "table" | table::tables(to_markdown("| a | b | c |\n| --- | --- | --- |\n| 1 | 2 | 3 |")) | first(self) | table::select_columns(self, [2, 0]) | table::to_csv(self)
Result
c,a
3,1
set_align(table, align): dict function

Set the alignment for a table.

Module: import "table" | table::set_align(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::set_align(self, ["left", "right"]) | table::to_csv(self)
Result
a,b
1,2
3,4
set_cell(table, row_index, col, value): dict function

Returns a new table with the data cell at row_index and column col (a header name or 0-based index; rows exclude the header) replaced by value.

Module: import "table" | table::set_cell(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::set_cell(self, 0, 1, "9") | table::to_csv(self)
Result
a,b
1,9
3,4
sort_rows(table, keys, order, kind): dict function

Sorts the data rows by one or more columns and renumbers them. The sort is stable. keys is a column (header name or 0-based index) or an array of columns (the first is the primary key). order is :asc or :desc, kind is :string or :number. To mix orders or types, pass an array of [column, order, kind] entries (the last two may be omitted). With no keys, rows are sorted by their content.

Module: import "table" | table::sort_rows(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| x | 10 |\n| y | 2 |")) | first(self) | table::sort_rows(self, "b", :desc, :number) | table::to_csv(self)
Result
a,b
x,10
y,2
tables(md_nodes): array function

Extract table structures from a list of markdown nodes.

Module: import "table" | table::tables(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | len(self)
Result
1
to_array(table): array function

Convert a table structure into an array of dict records keyed by header text. The resulting shape matches csv::csv_parse's output, so it composes with join_by and other record-array builtins.

Module: import "table" | table::to_array(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::to_array(self)
Result
[{"a": "1", "b": "2"}, {"a": "3", "b": "4"}]
to_csv(table, delimiter): string function

Convert a table structure into a CSV string with the specified delimiter.

Module: import "table" | table::to_csv(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::to_csv(self)
Result
a,b
1,2
3,4
to_markdown(table): array function

Convert a table structure back into a list of markdown nodes.

Module: import "table" | table::to_markdown(...)

Example
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::to_markdown(self) | len(self)
Result
7
transform_tables(md_nodes, f, only): array function

Applies f to every table in md_nodes and returns the whole node list with those tables replaced by the results, so it can be written back with -U. Nodes outside tables are left untouched. If only is given, tables for which only(header, rows) is false are left as they are.

Module: import "table" | table::transform_tables(...)

Example
import "table" | table::transform_tables(to_markdown("| a |\n| - |\n| 2 |\n| 1 |"), fn(t): table::sort_rows(t, "a");) | table::tables(self) | first(self) | table::to_csv(self)
Result
a
1
2
union(table_a, table_b): dict function

Concatenates the data rows of table_b onto table_a. Errors if the two tables don't have the same number of columns. table_a's header and alignment are kept; row numbers on the appended cells are renumbered to continue after table_a's existing rows.

Module: import "table" | table::union(...)

Example
import "table" | let a = first(table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |"))) | let b = first(table::tables(to_markdown("| a | b |\n| --- | --- |\n| 3 | 4 |"))) | table::to_csv(table::union(a, b))
Result
a,b
1,2
3,4
unnest_rows(table, col, sep): dict function

Inverse of nest_rows: collapses rows that share identical values in every column except col into a single row, joining their col values with sep. Column order follows the table's original header.

Module: import "table" | table::unnest_rows(...)

Example
import "table" | table::from_array([{"id": "1", "tags": "a"}, {"id": "1", "tags": "b"}]) | table::unnest_rows(self, "tags", ";") | table::to_csv(self)
Result
id,tags
1,a;b

Testing framework for mq A simple testing framework to execute test functions and output results

Source: test.mq

17 functions

assert(cond) function

Verifies that a condition is true and raises an error if it's false.

Module: import "test" | test::assert(...)

Example
true | include "test" | assert(true)
Result
true
assert_contains(array, value) function

Verifies that an array contains a specific value

Module: import "test" | test::assert_contains(...)

Example
[1, 2] | include "test" | assert_contains([1, 2], 1)
Result
[1, 2]
assert_empty(array) function

Verifies that an array is empty

Module: import "test" | test::assert_empty(...)

Example
[] | include "test" | assert_empty([])
Result
[]
assert_eq(actual, expected) function

Verifies that two values are equal

Module: import "test" | test::assert_eq(...)

Example
1 | include "test" | assert_eq(1, 1)
Result
1
assert_false(value) function

Verifies that a value is false

Module: import "test" | test::assert_false(...)

Example
false | include "test" | assert_false(false)
Result
false
assert_field(value, field) function

Verifies that a dict has the given field.

Module: import "test" | test::assert_field(...)

Example
{"a": 1} | include "test" | assert_field({"a": 1}, "a")
Result
{"a": 1}
assert_len(array, expected_length) function

Verifies that an array has a specific length

Module: import "test" | test::assert_len(...)

Example
[1, 2] | include "test" | assert_len([1, 2], 2)
Result
[1, 2]
assert_matches(value, pattern) function

Verifies that a value's string representation matches the given regular expression pattern.

Module: import "test" | test::assert_matches(...)

Example
"abc" | include "test" | assert_matches("abc", "a.c")
Result
abc
assert_ne(actual, expected) function

Verifies that two values are not equal

Module: import "test" | test::assert_ne(...)

Example
1 | include "test" | assert_ne(1, 2)
Result
1
assert_none(value) function

Verifies that a value is None

Module: import "test" | test::assert_none(...)

Example
None | include "test" | assert_none(None)
Result
assert_not_empty(array) function

Verifies that an array is not empty

Module: import "test" | test::assert_not_empty(...)

Example
[1] | include "test" | assert_not_empty([1])
Result
[1]
assert_not_none(value) function

Verifies that a value is not None

Module: import "test" | test::assert_not_none(...)

Example
1 | include "test" | assert_not_none(1)
Result
1
assert_true(value) function

Verifies that a value is true

Module: import "test" | test::assert_true(...)

Example
true | include "test" | assert_true(true)
Result
true
assert_type(value, expected_type) function

Verifies that a value has the given type. For markdown nodes this checks the node kind (e.g. "h1", "code", "list"), matching to_md_name. For every other value it checks the runtime type returned by type. On failure the source range of value is included so callers (e.g. content-lint rules) can point at the offending node.

Module: import "test" | test::assert_type(...)

Example
1 | include "test" | assert_type(1, "number")
Result
1
run_tests(tests): bool function

Executes multiple test functions. The whole report is built as a single string and printed with one print call, so concurrently running test files (the Rust runner may evaluate several files in parallel) can never interleave their output mid-line. Returns true if every test passed, so the caller can aggregate pass/fail across files itself instead of this function terminating the process.

Module: import "test" | test::run_tests(...)

run_tests_data(tests): array<dict> function

Like run_tests, but returns the per-test result dicts (name, status, duration, error, detail) instead of printing a Markdown report. Used by mq-test --format json so the caller can build its own machine-readable report.

Module: import "test" | test::run_tests_data(...)

Example
None | include "test" | run_tests_data([test_case("t", fn(): true;)])[0]["status"]
Result
passed
test_case(name, func): dict function

Helper function to create a test case

Module: import "test" | test::test_case(...)

Example
include "test" | test_case("my test", fn(): true;)["name"]
Result
my test

TOML Implementation in mq Based on TOML v1.0.0 specification

Source: toml.mq

6 functions

to_frontmatter(data): string function

Converts a data structure to a TOML front matter string.

Module: import "toml" | toml::to_frontmatter(...)

Example
import "toml" | toml::to_frontmatter({"key": 1})
Result
+++
key = 1
+++
toml_parse(input) function

Parses a TOML string and returns the parsed data structure.

Module: import "toml" | toml::toml_parse(...)

Example
import "toml" | toml::toml_parse("key = 1")
Result
{"key": 1}
toml_stringify(data): string function

Converts a data structure to a TOML string representation.

Module: import "toml" | toml::toml_stringify(...)

Example
import "toml" | toml::toml_stringify({"key": 1})
Result
key = 1
toml_to_json(data): string function

Converts a data structure to a JSON string representation.

Module: import "toml" | toml::toml_to_json(...)

Example
import "toml" | toml::toml_to_json({"key": 1})
Result
{"key":1}
toml_to_markdown_table(data): string function

Converts a TOML data structure to a Markdown table.

Module: import "toml" | toml::toml_to_markdown_table(...)

Example
import "toml" | toml::toml_to_markdown_table([{"a": 1}])
Result
| a |
| --- |
| 1 |
toml_try_parse(input): dict function

Parses a TOML string without raising on invalid input.

Module: import "toml" | toml::toml_try_parse(...)

Example 1
import "toml" | toml::toml_try_parse("key = 1")["ok"]
Result
true
Example 2
import "toml" | toml::toml_try_parse("key = ")["ok"]
Result
false

TOON implementation in mq

Source: toon.mq

3 functions

toon_parse(input) function

To parse a TOON string into a data structure

Module: import "toon" | toon::toon_parse(...)

Example
import "toon" | toon::toon_parse(toon::toon_stringify({"a": 1}))
Result
{"a": 1}
toon_stringify(data): string function

To convert a data structure into a TOON string

Module: import "toon" | toon::toon_stringify(...)

Example
import "toon" | toon::toon_stringify({"a": 1})
Result
a: 1
toon_try_parse(input): dict function

Parses a TOON string without raising on invalid input.

Module: import "toon" | toon::toon_try_parse(...)

Example 1
import "toon" | toon::toon_try_parse(toon::toon_stringify({"a": 1}))["ok"]
Result
true
Example 2
import "toon" | toon::toon_try_parse("[2]: 1")["ok"]
Result
false

XML Implementation in mq

Source: xml.mq

9 functions

xml_attr(data, name): string function

Returns the value of attribute name on element data, or None if the attribute isn't set.

Module: import "xml" | xml::xml_attr(...)

Example
import "xml" | xml::xml_attr(xml::xml_find(xml::xml_parse("<r><i id=\"1\"/></r>"), "i"), "id")
Result
1
xml_find(data, tag): dict function

Recursively finds the first element (including data itself) whose tag matches tag, or None if there's no match.

Module: import "xml" | xml::xml_find(...)

Example
import "xml" | xml::xml_find(xml::xml_parse("<r><i>hi</i></r>"), "i")["text"]
Result
hi
xml_find_all(data, tag): array function

Recursively finds every element (including data itself) whose tag matches tag, in document order.

Module: import "xml" | xml::xml_find_all(...)

Example
import "xml" | len(xml::xml_find_all(xml::xml_parse("<r><i>a</i><i>b</i></r>"), "i"))
Result
2
xml_parse(input) function

Parses an XML string and returns the corresponding data structure.

Module: import "xml" | xml::xml_parse(...)

Example
import "xml" | xml::xml_parse("<a>hi</a>")["tag"]
Result
a
xml_stringify(data): string function

Serializes a value to an XML string.

Module: import "xml" | xml::xml_stringify(...)

Example
import "xml" | xml::xml_stringify({"tag": "a", "attributes": {}, "children": [], "text": "hi"})
Result
<?xml version="1.0" encoding="UTF-8"?>
<a>hi</a>
xml_text(data): string function

Returns the concatenated text content of data and all its descendants, in document order.

Module: import "xml" | xml::xml_text(...)

Example
import "xml" | xml::xml_text(xml::xml_parse("<r><i>a</i><i>b</i></r>"))
Result
a b
xml_to_json(data): string function

Converts a data structure (typically the {tag, attributes, children, text} shape returned by xml_parse) to a JSON string representation.

Module: import "xml" | xml::xml_to_json(...)

Example
import "xml" | xml::xml_to_json({"tag": "a"})
Result
{"tag": "a"}
xml_to_markdown_table(data): string function

Converts an XML data structure to a Markdown table.

Module: import "xml" | xml::xml_to_markdown_table(...)

Example
import "xml" | xml::xml_to_markdown_table({"tag": "a", "attributes": {}, "children": [], "text": "hi"})
Result
| Tag | Attributes | Text | Children |
| --- | --- | --- | --- |
| a |  | hi | 0 |
xml_try_parse(input): dict function

Parses an XML string without raising on invalid input.

Module: import "xml" | xml::xml_try_parse(...)

Example 1
import "xml" | xml::xml_try_parse("<a>hi</a>")["ok"]
Result
true
Example 2
import "xml" | xml::xml_try_parse("<a>unclosed")["ok"]
Result
false

Based on YAML 1.2 specification

Source: yaml.mq

6 functions

to_frontmatter(data): string function

Converts a data structure to a YAML front matter string.

Module: import "yaml" | yaml::to_frontmatter(...)

Example
import "yaml" | yaml::to_frontmatter({"key": 1})
Result
---
key: 1
---
yaml_parse(input) function

Parses a YAML string and returns the parsed data structure. A single ----separated document is returned as-is; if the input contains multiple ----separated documents, an array of the parsed documents is returned.

Module: import "yaml" | yaml::yaml_parse(...)

Example
import "yaml" | yaml::yaml_parse("key: 1")
Result
{"key": 1}
yaml_stringify(data): string function

Converts a data structure to a YAML string representation.

Module: import "yaml" | yaml::yaml_stringify(...)

Example
import "yaml" | yaml::yaml_stringify({"key": 1})
Result
key: 1
yaml_to_json(data): string function

Converts a data structure to a JSON string representation.

Module: import "yaml" | yaml::yaml_to_json(...)

Example
import "yaml" | yaml::yaml_to_json({"key": 1})
Result
{"key": 1}
yaml_to_markdown_table(data): string function

Converts a YAML data structure to a Markdown table. The columns are the union of the keys of all rows, in first-seen order. | and newlines in cells are escaped, and an empty array gives an empty string.

Module: import "yaml" | yaml::yaml_to_markdown_table(...)

Example
import "yaml" | yaml::yaml_to_markdown_table([{"a": 1}])
Result
| a |
| --- |
| 1 |
yaml_try_parse(input): dict function

Parses a YAML string without raising on invalid input.

Module: import "yaml" | yaml::yaml_try_parse(...)

Example 1
import "yaml" | yaml::yaml_try_parse("key: 1")["ok"]
Result
true
Example 2
import "yaml" | yaml::yaml_try_parse("key: [unterminated")["ok"]
Result
false

72 selectors

..(): array selector

Recursively selects every descendant node (depth-first), not the node itself. Combine with a following selector for a descendant chain, e.g. .blockquote .code (sugar for .blockquote | .. | .code).

Example
to_markdown("> ## Nested")[0] | ..
Result
[Nested, ## Nested]
.<>(): markdown selector

Selects an HTML node.

.[](index: number, ...): markdown selector

Selects a list item node, optionally filtered by item index (e.g. .[](0)). To filter by checked state, use .task/.todo/.done instead.

Example
to_md_list("Item", 0) | .[]
Result
- Item
.[][](row: number, column: number): markdown selector

Selects a table cell node with the specified row and column.

Example
to_md_table_cell("A1", 0, 0) | .[][]
Result
A1
.align(): string selector

Returns the column alignments of a table as a comma separated string (e.g. :---,---:).

Example
to_md_table_align(["left", "right"]) | .align
Result
:---,---:
.alt(): string selector

Returns the alt text of an image or image reference.

Example
to_image("https://example.com/a.png", "Alt", "") | .alt
Result
Alt
.blockquote(): markdown selector

Aliases: .>

Selects a blockquote node.

Example
to_blockquote("Quote") | .blockquote
Result
> Quote
.break(): markdown selector

Aliases: .br

Selects a break node.

Example
to_markdown("Line1  \nLine2")[1] | .break
Result
\
.callout(kind: string, ...): markdown selector

Selects an Obsidian-style callout node, optionally filtered by kind (e.g. .callout("note")).

Example
to_markdown("> [!NOTE]\n> body")[0] | .callout
Result
> [!NOTE]
> body
.checked(): bool selector

Returns whether a task list item is checked, or none for an item that is not a task.

Example
to_markdown("- [x] done") | first() | .checked
Result
true
.children(): array selector

Aliases: .cn

Returns the child nodes of a container node as an array. Same as .values.

Example
to_md_list("Item", 0) | .children
Result
[Item]
.code(lang: string, ...): markdown selector

Aliases: .code_block

Selects a code block node with the specified language.

Example
to_code("x = 1", "python") | .code
Result
```python
x = 1
```
.code_inline(): markdown selector

Aliases: .inline_code

Selects an inline code node.

Example
to_code_inline("x") | .code_inline
Result
`x`
.column(): number selector

Returns the zero-based column of a table cell.

Example
to_markdown("| a | b |\n|---|---|\n| 1 | 2 |") | .table | last() | .column
Result
1
.definition(ident: string, ...): markdown selector

Selects a definition node, optionally filtered by identifier.

Example
to_markdown("[ref]: https://example.com")[0] | .definition
Result
[ref]: https://example.com
.delete(): markdown selector

Selects a delete (strikethrough) node.

Example
to_delete("Old") | .delete
Result
~~Old~~
.depth(): number selector

Returns the depth (1-6) of a heading.

Example
to_h("Title", 3) | .depth
Result
3
.done(): markdown selector

Selects a done item in the task list node.

Example
to_markdown("- [ ] Todo\n- [x] Done")[1] | .done
Result
- [x] Done
.embed(target: string, ...): markdown selector

Selects an Obsidian-style embed node, optionally filtered by target.

Example
to_markdown("![[image.png]]")[0] | .embed
Result
![[image.png]]
.emphasis(): markdown selector

Aliases: .**

Selects an emphasis (italic) node.

Example
to_em("Italic") | .emphasis
Result
*Italic*
.end_line(): number selector

Returns the one-based line on which a parsed node ends.

Example
to_markdown("a\nb") | first() | .end_line
Result
2
.fence(): bool selector

Returns true if a code block is fenced, false if it is indented.

Example
to_code("x = 1", "python") | .fence
Result
true
.footnote(ident: string, ...): markdown selector

Aliases: .^

Selects a footnote node, optionally filtered by identifier.

Example
to_markdown("Text[^1]\n\n[^1]: Note")[2] | .footnote
Result
[^1]: Note
.footnote_ref(ident: string, ...): markdown selector

Aliases: .[^]

Selects a footnote reference node, optionally filtered by identifier.

Example
to_markdown("Text[^1]\n\n[^1]: Note")[1] | .footnote_ref
Result
[^1]
.h(depth: number, ...): markdown selector

Selects a heading node with the specified depth.

Example
to_h("Title", 3) | .h
Result
### Title
.h1(): markdown selector

Selects a heading node with the 1 depth.

Example
to_h("Title", 1) | .h1
Result
# Title
.h2(): markdown selector

Selects a heading node with the 2 depth.

Example
to_h("Title", 2) | .h2
Result
## Title
.h3(): markdown selector

Selects a heading node with the 3 depth.

Example
to_h("Title", 3) | .h3
Result
### Title
.h4(): markdown selector

Selects a heading node with the 4 depth.

Example
to_h("Title", 4) | .h4
Result
#### Title
.h5(): markdown selector

Selects a heading node with the 5 depth.

Example
to_h("Title", 5) | .h5
Result
##### Title
.h6(): markdown selector

Selects a heading node with the 6 depth.

Example
to_h("Title", 6) | .h6
Result
###### Title
.heading(depth: number, ...): markdown selector

Selects a heading node with the specified depth.

Example
to_h("Title", 2) | .heading
Result
## Title
.horizontal_rule(): markdown selector

Aliases: .hr .--- .*** .___

Selects a horizontal rule node.

Example
to_hr() | .horizontal_rule
Result
***
.html(): markdown selector

Selects an HTML node.

Example
to_markdown("<div>hi</div>")[0] | .html
Result
<div>hi</div>
.ident(): string selector

Returns the normalized identifier of a definition, footnote, footnote reference, link reference or image reference.

Example
to_markdown("[Ref]: https://example.com") | first() | .ident
Result
ref
.image(url: string, ...): markdown selector

Selects an image node, optionally filtered by URL (e.g. .image("a.png")).

Example
to_image("https://example.com/a.png", "Alt", "") | .image
Result
![Alt](https://example.com/a.png "")
.image_ref(ident: string, ...): markdown selector

Selects an image reference node, optionally filtered by identifier.

Example
to_markdown("![alt][ref]\n\n[ref]: https://example.com/a.png")[0] | .image_ref
Result
![alt][ref]
.index(): number selector

Returns the zero-based index of a list item within its list.

Example
to_markdown("1. a\n2. b") | .list | last() | .index
Result
1
.inline_math(): markdown selector

Selects an inline math node.

Example
to_math_inline("x^2") | .inline_math
Result
$x^2$
.kind(): string selector

Returns the kind of a callout, e.g. NOTE.

Example
to_markdown("> [!NOTE]\n> body")[0] | .kind
Result
NOTE
.label(): string selector

Returns the label of a definition, link reference, image reference or footnote reference as written, or none.

Example
to_markdown("[Ref]: https://example.com") | first() | .label
Result
Ref
.lang(): string selector

Returns the language of a code block, or none when it has none.

Example
to_code("x = 1", "python") | .lang
Result
python
.level(): number selector

Returns the depth of a heading, or the nesting level of a list item.

Example
to_h("Title", 3) | .level
Result
3
.line(): number selector

Returns the one-based line on which a parsed node starts.

Example
to_markdown("a\nb") | first() | .line
Result
1
.link(url: string, ...): markdown selector

Selects a link node, optionally filtered by URL (e.g. .link("https://example.com")).

Example
to_link("https://example.com", "Example", "") | .link
Result
[Example](https://example.com)
.link_ref(ident: string, ...): markdown selector

Selects a link reference node, optionally filtered by identifier.

Example
to_markdown("[text][ref]\n\n[ref]: https://example.com")[0] | .link_ref
Result
[text][ref]
.list(index: number, ...): markdown selector

Aliases: .li

Selects a list item node, optionally filtered by item index (e.g. .list(0)). To filter by checked state, use .task/.todo/.done instead.

Example
to_md_list("Item", 0) | .list
Result
- Item
.math(): markdown selector

Aliases: .$$

Selects a math node.

Example
to_math("x^2") | .math
Result
$$
x^2
$$
.math_inline(): markdown selector

Selects a math inline node.

Example
to_math_inline("x^2") | .math_inline
Result
$x^2$
.mdx_flow_expression(): markdown selector

Selects an MDX flow expression node.

Example
to_mdx("{1 + 1}")[0] | .mdx_flow_expression
Result
{1 + 1}
.mdx_js_esm(): markdown selector

Selects an MDX JS ESM node.

.mdx_jsx_flow_element(name: string, ...): markdown selector

Aliases: .<

Selects an MDX JSX flow element node, optionally filtered by tag name.

Example
to_mdx("<Foo />")[0] | .mdx_jsx_flow_element
Result
<Foo />
.mdx_jsx_text_element(name: string, ...): markdown selector

Selects an MDX JSX text element node, optionally filtered by tag name.

Example
to_mdx("Hello <b>world</b>.")[1] | .mdx_jsx_text_element
Result
<b>world</b>
.mdx_text_expression(): markdown selector

Aliases: .{}

Selects an MDX text expression node.

Example
to_mdx("Value is {1 + 1}.")[1] | .mdx_text_expression
Result
{1 + 1}
.meta(): string selector

Returns the meta string that follows the language of a fenced code block, or none.

Example
to_markdown("```rust title\nx\n```") | first() | .meta
Result
title
.name(): string selector

Returns the tag name of an MDX JSX element.

Example
to_mdx("<Foo>x</Foo>") | first() | .name
Result
Foo
nodes(): array function

Collects every input node into a single array assigned to self, so the rest of the pipeline runs once over the whole input instead of once per node. Equivalent to prefixing a query with the -A/--aggregate CLI flag. Only valid at the top level of a program, not inside a def/fn body.

Example
nodes | type(self)
Result
array
.ordered(): bool selector

Returns true if a list item belongs to an ordered list.

Example
to_markdown("1. a\n2. b") | .list | first() | .ordered
Result
true
.row(): number selector

Returns the zero-based row of a table cell.

Example
to_markdown("| a | b |\n|---|---|\n| 1 | 2 |") | .table | last() | .row
Result
1
.strong(): markdown selector

Selects a strong (bold) node.

Example
to_strong("Bold") | .strong
Result
**Bold**
.table(row: number, column: number): markdown selector

Selects a table cell node with the specified row and column.

Example
to_md_table_cell("A1", 0, 0) | .table
Result
A1
.table_align(): markdown selector

Selects a table align node.

Example
to_md_table_align(["left", "right"]) | .table_align
Result
|:---|---:|
.task(): markdown selector

Selects a task list node.

Example
to_markdown("- [ ] Todo\n- [x] Done")[0] | .task
Result
- [ ] Todo
.text(): markdown selector

Aliases: .p .paragraph

Selects a text node.

Example
to_md_text("Hello") | .text
Result
Hello
.title(): string selector

Returns the title of a link, image, definition or callout, or none when it has none.

Example
to_link("https://example.com", "Example", "T") | .title
Result
T
.todo(): markdown selector

Selects a todo item in the task list node.

Example
to_markdown("- [ ] Todo\n- [x] Done")[0] | .todo
Result
- [ ] Todo
.toml(): markdown selector

Selects a TOML node.

Example
to_markdown("+++\nkey = 1\n+++\n\nBody")[0] | .toml
Result
+++
key = 1
+++
.url(): string selector

Returns the URL of a link, image, definition, wikilink or embed.

Example
to_link("https://example.com", "Example", "") | .url
Result
https://example.com
.value(): string selector

Returns the text content of a node, such as a text, code, link, heading, list item or table cell.

Example
to_code("x = 1", "python") | .value
Result
x = 1
.values(): array selector

Returns the child nodes of a container node (heading, link, list item, table cell, callout, footnote or MDX element) as an array.

Example
to_h("Title", 2) | .values
Result
[Title]
.wikilink(target: string, ...): markdown selector

Selects an Obsidian-style wikilink node, optionally filtered by target.

Example
to_markdown("[[target]]")[0] | .wikilink
Result
[[target]]
.yaml(): markdown selector

Selects a YAML node.

Example
to_markdown("---\nkey: 1\n---\n\nBody")[0] | .yaml
Result
---
key: 1
---

0 results for “”