attr(markdown: markdown, attribute: string)
function
Retrieves the value of the specified attribute from a markdown node.
640 functions
No results
434 functions
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.
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.
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.
extract_urls("see https://example.com.")
[{"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.
is_html(md): bool
function
Checks if markdown is html
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_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.
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.
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.
set_list_ordered(list: markdown, ordered: bool): markdown
function
Sets the ordered property of a markdown list node.
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.
strip_tags("<b>hi</b>")
hi
to_blockquote(value): markdown
function
Creates a markdown blockquote node with the given value.
to_blockquote("Quote")
> Quote
to_callout(value, kind: string, title: string): markdown
function
Creates a markdown callout node with the given value, kind, and title.
to_callout("Note text", "note", "")
> [!NOTE]
> Note text
to_code(value, language: string): markdown
function
Creates a markdown code block with the given value and language.
to_code("x = 1", "python")
```python
x = 1
```
to_code_inline(value): markdown
function
Creates an inline markdown code node with the given value.
to_code_inline("x")
`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.
to_definition("https://example.com", "ex", "")
[ex]: https://example.com
to_delete(value): markdown
function
Creates a markdown delete (strikethrough) node with the given value.
to_delete("Old")
~~Old~~
to_em(value): markdown
function
Creates a markdown emphasis (italic) node with the given value.
to_em("Italic")
*Italic*
to_footnote(value, ident: string): markdown
function
Creates a markdown footnote definition node with the given value and identifier.
to_footnote("Footnote text", "1")
[^1]: Footnote text
to_footnote_ref(ident: string): markdown
function
Creates a markdown footnote reference node with the given identifier.
to_footnote_ref("1")
[^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.
to_h("Title", 1)
# Title
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.
to_image("https://example.com/a.png", "Alt", "")

to_link(url: string, value, title: string): markdown
function
Creates a markdown link node with the given url and title.
to_link("https://example.com", "Example", "")
[Example](https://example.com)
to_markdown(markdown_string: string): array
function
Parses a markdown string and returns an array of markdown nodes.
to_markdown("# Hi")
[# 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.
to_math("x^2")
$$
x^2
$$
to_math_inline(value): markdown
function
Creates an inline markdown math node with the given value.
to_math_inline("x^2")
$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.
to_md_html("<br>")
<br>
to_md_list(value, indent: number): markdown
function
Creates a markdown list node with the given value and indent level.
to_md_list("Item", 0)
- Item
to_md_table_align(aligns: array): markdown
function
Creates a markdown table alignment row node from an array of alignments ("left", "right", "center", "none").
to_md_table_align(["left", "right"])
|:---|---:|
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.
to_md_table_cell("A1", 0, 0)
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.
to_md_text("hi")
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.
to_strong("Bold")
**Bold**
ascii_downcase(input: string): string
function
Converts ASCII uppercase letters (A-Z) in the given string to lowercase, leaving all other characters unchanged.
ascii_downcase("ABC")
abc
ascii_upcase(input: string): string
function
Converts ASCII lowercase letters (a-z) in the given string to uppercase, leaving all other characters unchanged.
ascii_upcase("abc")
ABC
casefold(input: string): string
function
Applies full Unicode case folding, for locale-independent case-insensitive comparison (e.g. German "ß" folds to "ss").
casefold("Straße")
strasse
center(s, width, pad_str): string
function
Centers a string within a given width using a padding string.
center("ab", 6, "*")
**ab**
chars(s): array
function
Splits a string into an array of characters (Unicode code points).
chars("abc")
["a", "b", "c"]
chomp(s): string
function
Removes one trailing newline (\n or \r\n) from a string.
chomp("line\n")
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.
common_indent(" a\n b\n c") == " "
true
contains(haystack, needle): bool
function
Checks if a string, byte array, array, or dict contains a substring, byte subsequence, element, or key.
contains("hello world", "world")
true
count_substr(s, sub): number
function
Returns the number of non-overlapping occurrences of a substring.
count_substr("banana", "an")
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.
dedent(" a\n b") == "a\nb"
true
downcase(input: string): string
function
Converts the given string to lowercase.
downcase("ABC")
abc
ends_with(value, suffix): bool
function
Checks if the given string or byte array ends with the specified suffix.
ends_with("hello", "lo")
true
explode(string: string): array
function
Splits the given string into an array of characters.
explode("ab")
[97, 98]
grapheme_len(input: string): number
function
Returns the number of extended grapheme clusters (user-perceived characters) in the string.
grapheme_len("👨👩👧")
1
graphemes(input: string): array
function
Splits the string into extended grapheme clusters (user-perceived characters), keeping combining marks and multi-codepoint emoji together.
graphemes("👨👩👧")
["👨👩👧"]
indent(s, prefix): string
function
Prepends the given prefix to every line of a string.
indent("a\nb", " ") == " a\n b"
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.
lines("a\nb\nc")
["a", "b", "c"]
lpad(s, length, pad_str): string
function
Left-pads a string to a specified length using a given padding string.
lpad("7", 3, "0")
007
ltrim(input)
function
Trims whitespace from the left end of the given string or byte array.
ltrim(" hi ")
hi
ltrimstr(s, left): string
function
Removes prefix string from input if it exists
ltrimstr("prefix_value", "prefix_")
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.
normalize_newlines("a\r\nb\rc", "lf")
a
b
c
remove_chars(s, set): string
function
Removes every character that appears in the given set.
remove_chars("hello world", "lo")
he wrd
repeat(string: string, count: number): string
function
Repeats the given string a specified number of times.
repeat("ab", 3)
ababab
replace(from, pattern, to)
function
Replaces all occurrences of a substring or byte subsequence with another one.
replace("aXbXc", "X", "-")
a-b-c
rpad(s, length, pad_str): string
function
Right-pads a string to a specified length using a given padding string.
rpad("7", 3, "0")
700
rsplit_once(s, sep): array
function
Splits a string at the last occurrence of a separator. Returns [s, None] if not found.
rsplit_once("a.b.c", ".")
["a.b", "c"]
rtrim(input)
function
Trims whitespace from the right end of the given string or byte array.
rtrim(" hi ")
hi
rtrimstr(s, right): string
function
Removes suffix string from input if it exists
rtrimstr("value_suffix", "_suffix")
value
slice(string: string, start: number, end: number): string
function
Extracts a substring from the given string.
slice("hello", 1, 3)
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.
slugify("Hello, World!")
hello-world
split(value, separator): array
function
Splits the given string (as a regular expression) or byte array (literal separator) by the specified separator.
split("a,b,c", ",")
["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.
split_once("key=a=b", "=")
["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.
squeeze_whitespace(" a b\n\tc ")
a b c
starts_with(value, prefix): bool
function
Checks if the given string or byte array starts with the specified prefix.
starts_with("hello", "he")
true
strip_ansi(s): string
function
Removes ANSI escape sequences (e.g. color codes) from a string
strip_ansi("\x1b[31mred\x1b[0m")
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.
token_count("Hello, world!")
4
translate(s, from, to): string
function
Replaces each character of from with the character at the same position in to (like tr).
translate("hello", "el", "ip")
hippo
trim(input)
function
Trims whitespace from both ends of the given string or byte array.
trim(" hi ")
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).
truncate("hello world", 5, "...")
he...
unicode_normalize(input: string, form: string): string
function
Normalizes the string to a Unicode normalization form: "nfc", "nfd", "nfkc", or "nfkd".
unicode_normalize("e\u{0301}", "nfc")
é
unlines(arr): string
function
Joins an array of strings into a single string with newline characters between them.
unlines(["a", "b", "c"]) == "a\nb\nc"
true
upcase(input: string): string
function
Converts the given string to uppercase.
upcase("abc")
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).
word_wrap("hello world", 5)
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.
words("fooBar_baz-QUX")
["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.
zfill(-42, 5)
-0042
all(v, f): bool
function
Returns true if all elements in the array or coroutine satisfy the provided function.
all([1, 2, 3], fn(x): x > 0;)
true
any(v, f): bool
function
Returns true if any element in the array or coroutine satisfies the provided function.
any([1, 2, 3], fn(x): x > 2;)
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.
chunk_by([1, 1, 2, 2, 3], identity)
[[1, 1], [2, 2], [3]]
chunks(v, size): array
function
Splits an array into chunks of a specified size, returning an array of arrays.
chunks([1, 2, 3, 4, 5], 2)
[[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.
def range(n): var i = 0 | while (i < n): yield: i | i += 1;;
| range(3) | collect()
[0, 1, 2]
combinations(arrays): array
function
Returns the Cartesian product of the given array of arrays, combining one element from each array.
combinations([[1, 2], [3, 4]])
[[1, 3], [1, 4], [2, 3], [2, 4]]
compact(array: array): array
function
Removes None values from the given array.
compact([1, None, 2])
[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.
compact_map([1, 2, 3], fn(x): if (x > 1): x;)
[2, 3]
del(array_or_string, index: number)
function
Deletes the element at the specified index in the array or string.
del([1, 2, 3], 1)
[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.
del_path({"a": {"b": 1, "c": 2}}, ["a", "b"])
{"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.
del_paths({"a": 1, "b": 2, "c": 3}, [["a"], ["c"]])
{"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.
difference([1, 2, 3], [2, 3, 4])
[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.
fill("x", 3)
["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.
filter([1, 2, 3, 4], fn(x): x > 2;)
[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.
find([1, 2, 3], fn(x): x == 2;)
2
find_index(arr, f): number
function
Returns the index of the first element in an array or coroutine that satisfies the provided function.
find_index([1, 2, 3], fn(x): x == 2;)
1
first(arr)
function
Returns the first element of an array, or consumes one value from a coroutine.
first([1, 2, 3])
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.
flat_map([1, 2], fn(x): [x, x];)
[1, 1, 2, 2]
flatten(array: array): array
function
Flattens a nested array into a single level array.
flatten([[1, 2], [3]])
[1, 2, 3]
fold(arr, init, f)
function
Reduces an array to a single value by applying a function, starting from an initial value.
fold([1, 2, 3], 0, fn(acc, x): acc + x;)
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.
fold_while([1, 2, 3, 4], 0, fn(acc, x): [acc + x < 5, acc + x];)
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}.
frequencies_by(["a", "b", "a"], identity)
{"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.
from_entries([["a", 1], ["b", 2]])
{"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.
get_or({"a": 1}, "b", 0)
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.
get_path({"a": {"b": 1}}, ["a", "b"])
1
group_by(arr, f): dict
function
Groups elements of an array by the result of applying a function to each element
has(value, key): bool
function
Checks if a dict has the given key, or an array has an element at the given index.
has({"a": 1}, "a")
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.
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.
index("hello", "ll")
2
index_by(arr, f): dict
function
Creates a dictionary indexed by a key extracted from each element.
index_by([1, 2, 3], to_string)
{"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.
indices("hello world hello", "hello")
[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.
insert([1, 2, 3], 1, "x")
[1, "x", 2, 3]
interleave(arr1, arr2): array
function
Interleaves two arrays, stopping at the shorter one.
interleave([1, 2, 3], ["a", "b", "c"])
[1, "a", 2, "b", 3, "c"]
interpose(arr, sep): array
function
Inserts a separator between the elements of an array.
interpose([1, 2, 3], 0)
[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.
intersection([1, 2, 3], [2, 3, 4])
[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.
invert({"a": 1, "b": 2})
{"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.
join([1, 2, 3], ",")
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.
join_by([{"id": 2, "name": "bob"}], [{"uid": 2, "age": 30}], "id", "uid")
[{"id": 2, "name": "bob", "uid": 2, "age": 30}]
join_by([{"id": 1}, {"id": 2}], [{"uid": 2}, {"uid": 2}], "id", "uid", "semi")
[{"id": 2}]
join_by([{"id": 1}, {"id": 2}], [{"uid": 2}, {"uid": 2}], "id", "uid", "anti")
[{"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.
last([1, 2, 3])
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.
leaf_entries({"a": {"b": 1}})
[{"path": ["a", "b"], "value": 1, "type": "number", "depth": 2}]
len(value): number
function
Returns the length of the given string or array.
len("hello")
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.
map_values(d, f): dict
function
Applies a function to each value of a dict, keeping the keys.
map_values({"a": 1, "b": 2}, fn(v): v * 10;)
{"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.
map_while([1, 2, 3, 4], fn(x): if (x < 3): x * 10 else: None;)
[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.
merge_defaults({"a": {"x": 1}}, {"a": {"x": 0, "y": 2}, "b": 3})
{"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.
merge_with({"a": 1, "b": {"x": 1}}, {"b": {"y": 2}, "c": 3}, "replace")
{"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.
ngram("abcd", 2)
["ab", "bc", "cd"]
omit(d, keys): dict
function
Returns a new dictionary excluding the specified keys from the original dictionary.
omit({"a": 1, "b": 2}, ["a"])
{"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.
partition([1, 2, 3, 4], fn(x): x > 2;)
[[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.
paths({"a": {"b": 1}})
[["a", "b"]]
pick(d, keys): dict
function
Returns a new dictionary containing only the specified keys from the original dictionary, if they exist.
pick({"a": 1, "b": 2}, ["a"])
{"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.
range(0, 5, 1)
[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.
reject([1, 2, 3, 4], fn(x): x > 2;)
[1, 2]
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.
rindex("hello", "l")
3
select(v, f)
function
Returns value if condition is true, None otherwise
select(5, true)
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.
set_path({"a": {"b": 1}}, ["a", "b"], 2)
{"a": {"b": 2}}
skip(arr, n): array
function
Skips the first n elements of an array and returns the rest. A coroutine input returns a coroutine after discarding the first n yielded values.
skip([1, 2, 3, 4], 2)
[3, 4]
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.
skip_while([1, 2, 3, 4], fn(x): x < 3;)
[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.
sort([3, 1, 2])
[1, 2, 3]
sort_by(arr, f): array
function
Sorts an array using a key function that extracts a comparable value for each element.
sort_by([3, 1, 2], identity)
[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).
sort_natural(["file10", "file2"])
["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.
split_records("a,b,c", ",")
[{"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.
take([1, 2, 3, 4], 2)
[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.
take_while([1, 2, 3, 4], fn(x): x < 3;)
[1, 2]
tally(arr): dict
function
Counts occurrences of each element in an array, returning a dict of {value: count}.
tally(["a", "b", "a"])
{"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.
transpose([[1, 2], [3, 4]])
[[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.
union([1, 2, 3], [2, 3, 4])
[1, 2, 3, 4]
uniq(arr): array
function
Removes duplicate elements from the given array, keeping the first occurrence.
uniq([1, 1, 2])
[1, 2]
unique_by(arr, f): array
function
Returns a new array with duplicate elements removed, comparing by the result of the provided function.
unique_by([1, 2, 1, 3], identity)
[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.
unzip([[1, "a"], [2, "b"]])
[[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.
update_path({"a": {"b": 1}}, ["a", "b"], fn(x): x + 1;)
{"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.
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.
with_entries({"a": 1}, fn(e): [e[0], e[1] + 1];)
{"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.
zip([1, 2], ["a", "b"])
[[1, "a"], [2, "b"]]
abs(number: number): number
function
Returns the absolute value of the given number.
abs(-10)
10
accumulate(arr, init, f): array
function
Like fold, but returns every intermediate accumulator value (excluding init).
accumulate([1, 2, 3], 0, fn(acc, x): acc + x;)
[1, 3, 6]
acos(number: number): number
function
Returns the arc cosine of the given number (in radians).
acos(1)
0
asin(number: number): number
function
Returns the arc sine of the given number (in radians).
asin(0)
0
atan(number: number): number
function
Returns the arc tangent of the given number (in radians).
atan(0)
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.
atan2(0, 1)
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.
band(12, 10)
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.
bor(12, 10)
14
bsearch(arr, target): number
function
Performs a binary search on a sorted array to find the index of the target value.
bsearch([1, 3, 5, 7, 9], 5)
2
cbrt(number: number): number
function
Returns the cube root of the given number.
cbrt(27)
3
ceil(number: number): number
function
Rounds the given number up to the nearest integer.
ceil(3.2)
4
clamp(x, lo, hi): number
function
Clamps a number between a minimum and maximum value.
clamp(15, 0, 10)
10
cos(number: number): number
function
Returns the cosine of the given number (in radians).
cos(0)
1
cosh(number: number): number
function
Returns the hyperbolic cosine of the given number.
cosh(0)
1
count_by(arr, f): number
function
Returns the count of elements in the array that satisfy the provided function.
count_by([1, 2, 3, 4], fn(x): x > 2;)
2
cumavg(arr): array
function
Returns an array of running (cumulative) averages of the given array of numbers.
cumavg([1, 2, 3, 4])
[1, 1.5, 2, 2.5]
cumsum(arr): array
function
Returns an array of running (cumulative) sums of the given array of numbers.
cumsum([1, 2, 3, 4])
[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.
describe([1, 2, 3, 4, 5])
{"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.
div(6, 2)
3
exp(number: number): number
function
Returns the exponential (e^x) of the given number.
exp(0)
1
floor(number: number): number
function
Rounds the given number down to the nearest integer.
floor(3.8)
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.
gcd(12, 18)
6
geomean(arr): number
function
Returns the geometric mean of an array of numbers, or None if the array is empty.
geomean([1, 4])
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.
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.
human_bytes(1500)
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.
human_size(1536)
1.5K
hypot(x: number, y: number): number
function
Returns the length of the hypotenuse, sqrt(x^2 + y^2).
hypot(3, 4)
5
infinite(): number
function
Returns an infinite number value.
is_integer(n): bool
function
Returns true if the number is an integer.
lcm(a, b): number
function
Returns the least common multiple of two integers. Raises an error if an argument is not a finite integer.
lcm(4, 6)
12
ln(number: number): number
function
Returns the natural logarithm (base e) of the given number.
ln(1)
0
log(number: number): number
function
Returns the natural logarithm (base e) of the given number.
log(1)
0
log10(number: number): number
function
Returns the base-10 logarithm of the given number.
log10(100)
2
log2(number: number): number
function
Returns the base-2 logarithm of the given number.
log2(8)
3
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.
max_by([3, 1, 2], identity)
3
mean(arr): number
function
Returns the average (mean) of an array of numbers, or None if the array is empty.
mean([1, 2, 3])
2
median(arr): number
function
Returns the median of an array of numbers, or None if the array is empty.
median([1, 2, 3, 4])
2.5
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.
min_by([3, 1, 2], identity)
1
mod(value1, value2)
function
Calculates the remainder of the division of the first value by the second value.
mod(7, 3)
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.
mode([1, 2, 2, 3])
[2]
nan(): number
function
Returns a Not-a-Number (NaN) value.
negate(number: number): number
function
Returns the negation of the given number.
negate(5)
-5
percentile(arr, p): number
function
Calculates the p-th percentile of an array of numbers using linear interpolation between closest ranks.
percentile([1, 2, 3, 4, 5], 0.5)
3
pow(base: number, exponent: number): number
function
Raises the base to the power of the exponent.
pow(2, 10)
1024
product(arr): number
function
Returns the product of the numbers in an array.
product([1, 2, 3, 4])
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.
round(3.5)
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.
shift_left(1, 2)
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.
shift_right(8, 2)
2
sin(number: number): number
function
Returns the sine of the given number (in radians).
sin(0)
0
sinh(number: number): number
function
Returns the hyperbolic sine of the given number.
sinh(0)
0
sqrt(number: number): number
function
Returns the square root of the given number.
sqrt(9)
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.
stddev(arr): number
function
Returns the population standard deviation of an array of numbers, or None if the array is empty.
stddev([2, 4, 4, 4, 5, 5, 7, 9])
2
sub(value1, value2)
function
Subtracts the second value from the first value.
sub(5, 2)
3
sum(arr): number
function
Returns the sum of the elements in an array after applying a transformation function to each element.
sum([1, 2, 3])
6
tan(number: number): number
function
Returns the tangent of the given number (in radians).
tan(0)
0
tanh(number: number): number
function
Returns the hyperbolic tangent of the given number.
tanh(0)
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.
top_by([3, 1, 4, 1, 5, 9, 2], identity, 3)
[9, 5, 4]
trunc(number: number): number
function
Truncates the given number to an integer by removing the fractional part.
trunc(3.9)
3
variance(arr): number
function
Returns the population variance of an array of numbers, or None if the array is empty.
variance([2, 4, 4, 4, 5, 5, 7, 9])
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.
xor(12, 10)
6
and(value1: bool, value2: bool): bool
function
Performs a logical AND operation on two boolean values.
and(true, false)
false
array(args): array
function
Creates an array from the given values
array(1, 2, 3)
[1, 2, 3]
arrays(a)
function
Returns array if input is array, None otherwise
arrays([1, 2])
[1, 2]
between(value, min, max): bool
function
Checks if a value is between min and max (inclusive).
between(5, 1, 10)
true
booleans(b)
function
Returns boolean if input is boolean, None otherwise
booleans(true)
true
coalesce(value1, value2)
function
Returns the first non-None value from the two provided arguments.
coalesce(None, 5)
5
complement(f): bool
function
Returns a new predicate function that negates the result of the given function.
let f = complement(is_none) | f(1)
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).
dicts(d)
function
Returns dict if input is dict, None otherwise
dicts({"a": 1})
{"a": 1}
gt(a, b): bool
function
Checks if the first value is greater than the second
gt(2, 1)
true
gte(a, b): bool
function
Checks if the first value is greater than or equal to the second
gte(1, 1)
true
in(v, elem): bool
function
Returns true if the element is in the array.
in([1, 2, 3], 2)
true
is_blank(s): bool
function
Returns true if the string is empty or contains only Unicode whitespace.
is_blank(" ")
true
is_coroutine(c): bool
function
Checks if input is a generator function's coroutine
def g(): yield: 1; | is_coroutine(g())
true
is_empty(s): bool
function
Checks if string, array or dict is empty
is_empty([])
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
iterables([1, 2])
[1, 2]
lt(a, b): bool
function
Checks if the first value is less than the second
lt(1, 2)
true
lte(a, b): bool
function
Checks if the first value is less than or equal to the second
lte(1, 1)
true
not(value: bool): bool
function
Performs a logical NOT operation on a boolean value.
not(true)
false
or(value1: bool, value2: bool): bool
function
Performs a logical OR operation on two boolean values.
or(true, false)
true
scalars(v)
function
Returns the value if it is not an array or dict (i.e. a leaf/scalar value), None otherwise
scalars(1)
1
strings(s)
function
Returns string if input is string, None otherwise
strings("hi")
hi
to_array(value): array
function
Converts the given value to an array.
to_array(1)
[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.
to_boolean("true")
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()).
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.
to_number("42")
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.
to_number_or("42", 0)
42
to_number_or("not a number", 0)
0
to_string(value): string
function
Converts the given value to a string.
to_string(1)
1
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".
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.
from_date("1970-01-01T00:00:00Z")
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)].
gmtime(0)
[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).
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").
strftime(0, "%Y-%m-%d")
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).
strptime("1970-01-01", "%Y-%m-%d")
0
to_date(timestamp: number, format: string): string
function
Converts a timestamp to a date string with the given format.
to_date(0, "%Y-%m-%d")
1970-01-01
to_date_iso8601(d): string
function
Formats a date to ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ)
to_date_iso8601(0)
1970-01-01T00:00:00Z
base64(input: string): string
function
Encodes the given string to base64.
base64("hi")
aGk=
base64d(input: string): string
function
Decodes the given base64 string.
base64d("aGk=")
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.
base64url("hi")
aGk
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.
capture("v1.2.3", "(?P<major>[0-9]+)")
{"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.
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.
glob_match("*.md", "readme.md")
true
gsub(from: string, pattern: string, to: string): string
function
Replaces all occurrences matching a regular expression pattern with the replacement string.
gsub("a1b2", "[0-9]", "#")
a#b#
hexdump(bytes: bytes): string
function
Renders bytes as a hexdump (offset, hex bytes, ASCII gutter), like xxd/hexdump -C.
html_escape(string: string): string
function
Escapes &, <, >, ", and ' in the given string as HTML entities.
html_escape("<a>")
<a>
html_unescape(string: string): string
function
Decodes named and numeric HTML entities in the given string into their corresponding characters.
html_unescape("<a>")
<a>
is_not_regex_match(string: string, pattern: string): bool
function
Checks if the given pattern does not match the string.
is_not_regex_match("abc", "x")
true
is_regex_match(string: string, pattern: string): bool
function
Checks if the given pattern matches the string.
is_regex_match("abc", "a.c")
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.
markdown_escape("**bold**", "text")
\*\*bold\*\*
markdown_escape("a | b", "table_cell")
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.
redact({"user": "alice", "password": "hunter2"}, [{type: "key", pattern: "password"}])
{"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.
regex_escape("a.b*c?")
a\.b\*c\?
regex_match(string: string, pattern: string): array
function
Finds all matches of the given pattern in the string.
regex_match("abc123", "[0-9]+")
["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.
regex_replace("a1b2", "[0-9]", fn(m): "[" + m["match"] + "]";)
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.
replace_prose("Use foo to call foo.", "foo", "bar")
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.
scan("a1b2", "[0-9]")
["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).
shell_quote("it's a test")
'it'"'"'s a test'
test(s, pattern): bool
function
Tests if string matches a pattern
test("abc", "a.c")
true
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.
url_decode("a%20b")
a b
url_encode(input: string): string
function
URL-encodes the given string.
url_encode("a b")
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.
utf8bytelen(string: string): number
function
Returns the number of bytes of the given string when encoded as UTF-8.
utf8bytelen("héllo")
6
basename(path: string): string
function
Returns the final component of a path string (e.g. "file.txt" from "/a/b/file.txt").
basename("/a/b/file.txt")
file.txt
close(stream)
function
Forces a generator coroutine to completion, releasing its suspended frames early instead of waiting for it to be dropped.
def g(): yield: 1; | let stream = g() | close(stream) | next(stream)
{"value": , "done": true}
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.
dirname("/a/b/file.txt")
/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.
extname("file.txt")
.txt
Checks if a file exists at the given path. Requires the --allow-read CLI flag; otherwise returns a runtime error.
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.
Returns the size, in bytes, of the file at the given path. Requires the --allow-read CLI flag; otherwise returns a runtime error.
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.
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
next(stream): dict
function
Resumes a generator coroutine and returns its next value and completion status.
def g(): yield: 1; | let stream = g() | next(stream)
{"value": 1, "done": false}
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.
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").
path_join("/a/b", "c.txt")
/a/b/c.txt
print(message: string)
function
Prints a message to standard output and returns the current value.
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.
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.
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.
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.
safe_filename("My: Report? <2024>.pdf")
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.
def g(): let a = yield: 1 | yield: a; | let stream = g() | next(stream) | send(stream, 2)
{"value": 2, "done": false}
status(stream): symbol
function
Returns a generator coroutine's lifecycle state as a symbol: :created, :suspended, :running, :completed, or :failed.
def g(): yield: 1; | status(g())
: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").
stem("/a/b/file.txt")
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.
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.
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.
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.
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))).
let f = comp(fn(x): x + 1;, fn(x): x * 2;) | f(3)
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.
flip(sub, 2, 10)
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.
intern("hi")
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)].
let f = juxt(first, last) | f([1, 2, 3])
[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).
tap(1, 2)
1
uuid(): string
function
Generates a random (version 4, RFC 4122) UUID string.
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.
bit_length(n: number): number
function
Returns the number of bits needed to write a non-negative integer in binary, 0 for 0.
bit_length(255)
8
bit_length(256)
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.
hash("hello")
4952387935952618
hash("hello", 1) != hash("hello", 2)
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.
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.
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"]]
["12", 2, 3, "n"]
No results
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(...)
cbor_stringify(data): bytes
function
Serializes a value to CBOR bytes.
Module: import "cbor" | cbor::cbor_stringify(...)
import "cbor" | cbor::cbor_stringify(1)
f93c00
No results
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(...)
import "csv" | csv::backward_fill([{"a": ""}, {"a": "x"}], ["a"])
[{"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(...)
import "csv" | csv::constant_fill([{"a": ""}, {"a": "x"}], {"a": "N/A"})
[{"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(...)
import "csv" | csv::csv_needs_quote("a,b", ",")
true
csv_parse(input, has_header): array
function
Parses CSV content using a comma as the delimiter.
Module: import "csv" | csv::csv_parse(...)
import "csv" | csv::csv_parse("name,age\nAlice,30", true)
[{"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(...)
import "csv" | csv::csv_parse_with_delimiter("a;b\n1;2", ";", true)
[{"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(...)
import "csv" | csv::csv_stringify([{"name": "Alice", "age": 30}], ",")
name,age
Alice,30
csv_to_json(data): string
function
Converts CSV data to a JSON string.
Module: import "csv" | csv::csv_to_json(...)
import "csv" | csv::csv_to_json([{"name": "Alice", "age": 30}])
[{"name":"Alice","age":30}]
import "csv" | csv::csv_to_json([{"name": "back\\slash"}])
[{"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(...)
import "csv" | csv::csv_to_markdown_table([{"name": "Alice", "age": 30}])
| 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(...)
import "csv" | csv::forward_fill([{"a": "x"}, {"a": ""}], ["a"])
[{"a": "x"}, {"a": "x"}]
psv_parse(input, has_header): array
function
Parses PSV (Pipe-Separated Values) content.
Module: import "csv" | csv::psv_parse(...)
import "csv" | csv::psv_parse("name|age\nAlice|30", true)
[{"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(...)
import "csv" | csv::sort_rows([{"n": "10"}, {"n": "9"}], "n")
[{"n": "9"}, {"n": "10"}]
import "csv" | csv::sort_rows([{"c": "a", "n": "1"}, {"c": "a", "n": "2"}], {"c": "asc", "n": "desc"})
[{"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(...)
import "csv" | csv::tsv_parse("name\tage\nAlice\t30", true)
[{"name": "Alice", "age": "30"}]
No results
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(...)
import "fuzzy" | fuzzy::fuzzy_best_match(["apple", "aple", "banana"], "aple")
{"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(...)
import "fuzzy" | fuzzy::fuzzy_filter(["apple", "aple", "banana"], "aple", 0.8)
[{"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(...)
import "fuzzy" | fuzzy::fuzzy_match(["apple", "aple", "banana"], "aple")
[{"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(...)
import "fuzzy" | fuzzy::fuzzy_match_jaro(["apple", "aple", "banana"], "aple")
[{"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(...)
import "fuzzy" | fuzzy::fuzzy_match_levenshtein(["apple", "aple", "banana"], "aple")
[{"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(...)
import "fuzzy" | fuzzy::jaro("martha", "marhta")
0.9444444444444445
jaro_winkler(s1, s2): number
function
Calculates the Jaro-Winkler distance between two strings.
Module: import "fuzzy" | fuzzy::jaro_winkler(...)
import "fuzzy" | fuzzy::jaro_winkler("martha", "marhta")
0.9611111111111111
levenshtein(s1, s2): number
function
Calculates the Levenshtein distance between two strings.
Module: import "fuzzy" | fuzzy::levenshtein(...)
import "fuzzy" | fuzzy::levenshtein("kitten", "sitting")
3
No results
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(...)
import "gron" | gron::gron_parse("json.a = 1;\njson.b = 2;")
{"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(...)
import "gron" | gron::gron_stringify({"a": 1, "b": 2})
json = {};
json.a = 1;
json.b = 2;
No results
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(...)
import "json" | json::json_diff({"a": 1, "b": 2}, {"a": 1, "b": 3})
[{"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(...)
import "json" | json::json_merge_patch({"a": 1, "b": {"c": 2, "d": 3}}, {"a": None, "b": {"c": 9}})
{"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(...)
import "json" | json::json_parse("{\"a\": 1}")
{"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(...)
import "json" | json::json_patch({"a": [1, 3]}, [{"op": "add", "path": "/a/1", "value": 2}])
{"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(...)
import "json" | json::json_pointer_del({"a": 1, "b": 2}, "/a")
{"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(...)
import "json" | json::json_pointer_from_path(["a/b", 0])
/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(...)
import "json" | json::json_pointer_get({"a": [1, 2]}, "/a/1")
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(...)
import "json" | json::json_pointer_has({"a": None}, "/a")
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(...)
import "json" | json::json_pointer_set({"a": [1]}, "/a/-", 2)
{"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(...)
import "json" | json::json_pointer_to_path({"a": [1, 2]}, "/a/1")
["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(...)
import "json" | json::json_stringify({"a": 1})
{"a": 1}
import "json" | json::json_stringify({"a": "he said \"hi\"\nbye"})
{"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(...)
import "json" | json::json_to_markdown_table([{"a": 1, "b": 2}])
| 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(...)
import "json" | json::json_try_parse("{\"a\": 1}")["ok"]
true
import "json" | json::json_try_parse("{bad")["ok"]
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(...)
import "json" | json::merge3({"a": 1, "b": 1}, {"a": 2, "b": 1}, {"a": 1, "b": 3})
{"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(...)
import "json" | json::to_frontmatter({"key": 1})
;;;
{"key": 1}
;;;
No results
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(...)
import "md" | md::blockquote("Quote")
> 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(...)
import "md" | md::callout("Note text", "note", "")
> [!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(...)
import "md" | md::code_inline("x")
`x`
comment(value): markdown
function
Wraps value in an HTML comment.
Module: import "md" | md::comment(...)
import "md" | md::comment("todo")
<!-- 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(...)
import "md" | md::definition("https://example.com", "ex", "")
[ex]: https://example.com
delete(value): markdown
function
Wraps value in a delete (strikethrough) node.
Module: import "md" | md::delete(...)
import "md" | md::delete("Old")
~~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(...)
em(value): markdown
function
Wraps value in an emphasis (italic) node.
Module: import "md" | md::em(...)
import "md" | md::em("Italic")
*Italic*
embed(target, display): markdown
function
Creates an embed of target (![[target]]), with optional display text.
Module: import "md" | md::embed(...)
import "md" | md::embed("image.png")
![[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(...)
import "md" | md::escape("a*b")
a\*b
footnote(value, ident): markdown
function
Wraps value in a footnote definition node identified by ident.
Module: import "md" | md::footnote(...)
import "md" | md::footnote("Footnote text", "1")
[^1]: Footnote text
footnote_ref(ident): markdown
function
Creates a footnote reference node pointing at ident.
Module: import "md" | md::footnote_ref(...)
import "md" | md::footnote_ref("1")
[^1]
h(value, depth): markdown
function
Wraps value in a heading node at the given depth (1-6).
Module: import "md" | md::h(...)
import "md" | md::h("Title", 1)
# Title
h1(value): markdown
function
Shorthands for h(value, 1) through h(value, 6).
Module: import "md" | md::h1(...)
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(...)
highlight(value): markdown
function
Wraps value in highlight markers.
Module: import "md" | md::highlight(...)
import "md" | md::highlight("key")
==key==
hr(): markdown
function
Creates a horizontal rule node.
Module: import "md" | md::hr(...)
import "md" | md::hr()
***
html(value): markdown
function
Wraps value in a raw HTML node, emitted as-is.
Module: import "md" | md::html(...)
import "md" | md::html("<br>")
<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(...)
import "md" | md::image("https://example.com/a.png", "Alt", "")

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(...)
import "md" | md::link("https://example.com", "Example", "")
[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(...)
import "md" | md::list("Item", 0)
- Item
math(value): markdown
function
Wraps value in a math block node.
Module: import "md" | md::math(...)
import "md" | md::math("x^2")
$$
x^2
$$
math_inline(value): markdown
function
Wraps value in an inline math node.
Module: import "md" | md::math_inline(...)
import "md" | md::math_inline("x^2")
$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(...)
import "md" | len(md::reference_index(to_markdown("[a][b]\n\n[b]: https://example.com \"B\""))[:links]["b"])
1
import "md" | len(md::reference_index(to_markdown("[a][b]\n\n[b]: https://x.com\n[b]: https://y.com"))[:links]["b"])
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(...)
import "md" | first(md::resolve_references(to_markdown("[a][b]\n\n[b]: https://example.com")))[:resolved]
true
import "md" | first(md::resolve_references(to_markdown("[a][b]\n\n[b]: https://example.com"), dict()))[:resolved]
false
strong(value): markdown
function
Wraps value in a strong (bold) node.
Module: import "md" | md::strong(...)
import "md" | md::strong("Bold")
**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(...)
import "md" | md::doc(md::table(["A", "B"], [["1", "2"], ["3", "4"]]))
|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(...)
import "md" | md::table_align(["left", "right"])
|:---|---:|
table_cell(value, row, column): markdown
function
Creates a single table cell node at the given row/column.
Module: import "md" | md::table_cell(...)
import "md" | md::table_cell("A1", 0, 0)
A1
table_row(cells): markdown
function
Creates a table row node from an array of cell values.
Module: import "md" | md::table_row(...)
import "md" | md::table_row(["a", "b"])
|a|b|
text(value): markdown
function
Creates a plain text node from value.
Module: import "md" | md::text(...)
import "md" | md::text("hi")
hi
wikilink(target, text): markdown
function
Creates a wikilink to target, with optional display text.
Module: import "md" | md::wikilink(...)
import "md" | md::wikilink("Page", "alias")
[[Page|alias]]
No results
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
import "section" | len(section::section(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), "A"))
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(...)
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")))))
2
bodies(sections): array
function
Extracts body from all sections.
Module: import "section" | section::bodies(...)
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"))))
3
body(section): array
function
Returns the body of a section (all nodes except the header).
Module: import "section" | section::body(...)
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")))))
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(...)
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))
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(...)
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"))
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(...)
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"))))
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(...)
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))
A1
filter_sections(md_nodes, predicate): array
function
Filters sections based on a given predicate function.
Module: import "section" | section::filter_sections(...)
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;))
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(...)
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"))
A1
has_body(section): bool
function
Checks if a section has any content beyond the header.
Module: import "section" | section::has_body(...)
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"))))
true
level(section): number
function
Returns the header level (1-6) of a section.
Module: import "section" | section::level(...)
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"))))
1
map_sections(md_nodes, mapper): array
function
Maps sections using a given mapper function.
Module: import "section" | section::map_sections(...)
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);)
["A", "A1", "B"]
nth(sections, n)
function
Returns the nth section from an array of sections (0-indexed).
Module: import "section" | section::nth(...)
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))
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(...)
import "section" | len(section::section(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), "A"))
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(...)
import "section" | len(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
3
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))))
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(...)
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))
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(...)
import "section" | len(section::split(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B"), 1))
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(...)
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")))))
1
title(section): string
function
Returns the title text of a section (header text without the # symbols).
Module: import "section" | section::title(...)
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"))))
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(...)
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"))
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(...)
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"))
1
title_match(sections, pattern): array
function
Filters sections by a pattern match in the title text.
Module: import "section" | section::title_match(...)
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"))
2
titles(sections): array
function
Extracts titles from all sections.
Module: import "section" | section::titles(...)
import "section" | section::titles(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
["A", "A1", "B"]
toc(sections): array
function
Generates a table of contents from sections.
Module: import "section" | section::toc(...)
import "section" | section::toc(section::sections(to_markdown("# A\n\nBody A\n\n## A1\n\nSub A\n\n# B\n\nBody B")))
[" - 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(...)
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")))
[" - [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(...)
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")))))
1
tree::ancestors(roots, node): array
function
Returns the ancestors of a section, top-level first.
Module: import "section" | section::tree::ancestors(...)
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])))
["A", "A1"]
tree::at(roots, idx_path)
function
Returns the section at idx_path, or None.
Module: import "section" | section::tree::at(...)
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]))
A2
tree::breadcrumb(roots, node): array
function
Returns the heading titles from the top level down to node.
Module: import "section" | section::tree::breadcrumb(...)
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]))
["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(...)
import "section" | section::titles(section::tree::flatten(section::tree(to_markdown("# A\n\n## A1\n\n### A1a\n\n## A2\n\n# B"))))
["A", "A1", "A1a", "A2", "B"]
tree::next_sibling(roots, node)
function
Returns the next sibling, or None.
Module: import "section" | section::tree::next_sibling(...)
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])))
A2
tree::parent(roots, node)
function
Returns the parent section, or None at the top level.
Module: import "section" | section::tree::parent(...)
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])))
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(...)
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]))
[0, 1]
tree::prev_sibling(roots, node)
function
Returns the previous sibling, or None.
Module: import "section" | section::tree::prev_sibling(...)
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])))
A1
tree::siblings(roots, node): array
function
Returns the other sections under the same parent, in document order.
Module: import "section" | section::tree::siblings(...)
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])))
["A1", "A3"]
No results
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(...)
import "semver" | semver::semver_to_string(semver::semver_bump_major(semver::semver_parse("1.2.3")))
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(...)
import "semver" | semver::semver_to_string(semver::semver_bump_minor(semver::semver_parse("1.2.3")))
1.3.0
semver_bump_patch(v): dict
function
Increments the patch version and clears pre-release.
Module: import "semver" | semver::semver_bump_patch(...)
import "semver" | semver::semver_to_string(semver::semver_bump_patch(semver::semver_parse("1.2.3")))
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(...)
import "semver" | semver::semver_compare(semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0"))
-1
semver_eq(a, b): bool
function
Returns true if version a equals version b (ignoring build metadata).
Module: import "semver" | semver::semver_eq(...)
import "semver" | semver::semver_eq(semver::semver_parse("1.0.0"), semver::semver_parse("1.0.0"))
true
semver_gt(a, b): bool
function
Returns true if version a is greater than version b.
Module: import "semver" | semver::semver_gt(...)
import "semver" | semver::semver_gt(semver::semver_parse("2.0.0"), semver::semver_parse("1.0.0"))
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(...)
import "semver" | semver::semver_gte(semver::semver_parse("1.0.0"), semver::semver_parse("1.0.0"))
true
semver_lt(a, b): bool
function
Returns true if version a is less than version b.
Module: import "semver" | semver::semver_lt(...)
import "semver" | semver::semver_lt(semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0"))
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(...)
import "semver" | semver::semver_lte(semver::semver_parse("1.0.0"), semver::semver_parse("1.0.0"))
true
semver_max(versions): dict
function
Returns the maximum version from an array of parsed SemVer dicts.
Module: import "semver" | semver::semver_max(...)
import "semver" | semver::semver_to_string(semver::semver_max([semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0")]))
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(...)
import "semver" | semver::semver_max_satisfying(["1.0.0", "1.5.0", "2.0.0"], "^1.0.0")
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(...)
import "semver" | semver::semver_to_string(semver::semver_min([semver::semver_parse("1.0.0"), semver::semver_parse("2.0.0")]))
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(...)
import "semver" | semver::semver_to_string(semver::semver_parse("1.2.3-beta.1"))
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(...)
import "semver" | semver::semver_satisfies("1.5.0", "^1.0.0")
true
import "semver" | semver::semver_satisfies("1.1.0", "1.0.0 - 1.2.0")
true
import "semver" | semver::semver_satisfies("2.5.0", "1.0.0 - 1.2.0||>=2.0.0")
true
semver_sort(versions): array
function
Sorts an array of parsed SemVer dicts in ascending order.
Module: import "semver" | semver::semver_sort(...)
import "semver" | map(semver::semver_sort([semver::semver_parse("2.0.0"), semver::semver_parse("1.0.0")]), semver::semver_to_string)
["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(...)
import "semver" | semver::semver_to_string(semver::semver_parse("1.2.3-beta"))
1.2.3-beta
No results
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
import "table" | len(table::tables(to_markdown("| a | b |\n| - | - |\n| 1 | 2 |")))
1
35 functions
add_column(table, col): dict
function
Add a new column to a table.
Module: import "table" | table::add_column(...)
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)
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(...)
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)
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(...)
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)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |")) | first(self) | table::column_index(self, "b")
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::column_values(self, 1)
["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(...)
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)
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(...)
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)
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(...)
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)
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(...)
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)
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(...)
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)
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(...)
import "table" | table::from_array([{"a": "1", "b": "2"}, {"a": "3", "b": "4"}]) | table::to_csv(self)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::get_cell(self, 1, 0)
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(...)
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)
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(...)
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)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| x | y |")) | first(self) | table::map_cells(self, upcase) | table::to_csv(self)
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(...)
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)
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(...)
import "table" | table::from_array([{"id": "1", "tags": "a;b"}]) | table::nest_rows(self, "tags", ";") | table::to_csv(self)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |")) | first(self) | table::num_cols(self)
2
num_rows(table): number
function
Returns the number of data rows in the table (excludes the header).
Module: import "table" | table::num_rows(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::num_rows(self)
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(...)
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)
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(...)
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)
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(...)
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])
1
remove_row(table, row_index): dict
function
Remove a row from a table at the specified index.
Module: import "table" | table::remove_row(...)
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)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |")) | first(self) | table::rename_column(self, 0, "x") | table::to_csv(self)
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(...)
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)
c,a
3,1
set_align(table, align): dict
function
Set the alignment for a table.
Module: import "table" | table::set_align(...)
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)
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(...)
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)
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(...)
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)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | len(self)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::to_array(self)
[{"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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::to_csv(self)
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(...)
import "table" | table::tables(to_markdown("| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |")) | first(self) | table::to_markdown(self) | len(self)
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(...)
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)
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(...)
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))
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(...)
import "table" | table::from_array([{"id": "1", "tags": "a"}, {"id": "1", "tags": "b"}]) | table::unnest_rows(self, "tags", ";") | table::to_csv(self)
id,tags
1,a;b
No results
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(...)
true | include "test" | assert(true)
true
assert_contains(array, value)
function
Verifies that an array contains a specific value
Module: import "test" | test::assert_contains(...)
[1, 2] | include "test" | assert_contains([1, 2], 1)
[1, 2]
assert_empty(array)
function
Verifies that an array is empty
Module: import "test" | test::assert_empty(...)
[] | include "test" | assert_empty([])
[]
assert_eq(actual, expected)
function
Verifies that two values are equal
Module: import "test" | test::assert_eq(...)
1 | include "test" | assert_eq(1, 1)
1
assert_false(value)
function
Verifies that a value is false
Module: import "test" | test::assert_false(...)
false | include "test" | assert_false(false)
false
assert_field(value, field)
function
Verifies that a dict has the given field.
Module: import "test" | test::assert_field(...)
{"a": 1} | include "test" | assert_field({"a": 1}, "a")
{"a": 1}
assert_len(array, expected_length)
function
Verifies that an array has a specific length
Module: import "test" | test::assert_len(...)
[1, 2] | include "test" | assert_len([1, 2], 2)
[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(...)
"abc" | include "test" | assert_matches("abc", "a.c")
abc
assert_ne(actual, expected)
function
Verifies that two values are not equal
Module: import "test" | test::assert_ne(...)
1 | include "test" | assert_ne(1, 2)
1
assert_none(value)
function
Verifies that a value is None
Module: import "test" | test::assert_none(...)
None | include "test" | assert_none(None)
assert_not_empty(array)
function
Verifies that an array is not empty
Module: import "test" | test::assert_not_empty(...)
[1] | include "test" | assert_not_empty([1])
[1]
assert_not_none(value)
function
Verifies that a value is not None
Module: import "test" | test::assert_not_none(...)
1 | include "test" | assert_not_none(1)
1
assert_true(value)
function
Verifies that a value is true
Module: import "test" | test::assert_true(...)
true | include "test" | assert_true(true)
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(...)
1 | include "test" | assert_type(1, "number")
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(...)
None | include "test" | run_tests_data([test_case("t", fn(): true;)])[0]["status"]
passed
test_case(name, func): dict
function
Helper function to create a test case
Module: import "test" | test::test_case(...)
include "test" | test_case("my test", fn(): true;)["name"]
my test
No results
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(...)
import "toml" | toml::to_frontmatter({"key": 1})
+++
key = 1
+++
toml_parse(input)
function
Parses a TOML string and returns the parsed data structure.
Module: import "toml" | toml::toml_parse(...)
import "toml" | toml::toml_parse("key = 1")
{"key": 1}
toml_stringify(data): string
function
Converts a data structure to a TOML string representation.
Module: import "toml" | toml::toml_stringify(...)
import "toml" | toml::toml_stringify({"key": 1})
key = 1
toml_to_json(data): string
function
Converts a data structure to a JSON string representation.
Module: import "toml" | toml::toml_to_json(...)
import "toml" | toml::toml_to_json({"key": 1})
{"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(...)
import "toml" | toml::toml_to_markdown_table([{"a": 1}])
| a |
| --- |
| 1 |
toml_try_parse(input): dict
function
Parses a TOML string without raising on invalid input.
Module: import "toml" | toml::toml_try_parse(...)
import "toml" | toml::toml_try_parse("key = 1")["ok"]
true
import "toml" | toml::toml_try_parse("key = ")["ok"]
false
No results
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(...)
toon_stringify(data): string
function
To convert a data structure into a TOON string
Module: import "toon" | toon::toon_stringify(...)
import "toon" | toon::toon_stringify({"a": 1})
a: 1
toon_try_parse(input): dict
function
Parses a TOON string without raising on invalid input.
Module: import "toon" | toon::toon_try_parse(...)
import "toon" | toon::toon_try_parse("[2]: 1")["ok"]
false
No results
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(...)
import "xml" | xml::xml_attr(xml::xml_find(xml::xml_parse("<r><i id=\"1\"/></r>"), "i"), "id")
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(...)
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(...)
import "xml" | len(xml::xml_find_all(xml::xml_parse("<r><i>a</i><i>b</i></r>"), "i"))
2
xml_parse(input)
function
Parses an XML string and returns the corresponding data structure.
Module: import "xml" | xml::xml_parse(...)
import "xml" | xml::xml_parse("<a>hi</a>")["tag"]
a
xml_stringify(data): string
function
Serializes a value to an XML string.
Module: import "xml" | xml::xml_stringify(...)
import "xml" | xml::xml_stringify({"tag": "a", "attributes": {}, "children": [], "text": "hi"})
<?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(...)
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(...)
import "xml" | xml::xml_to_json({"tag": "a"})
{"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(...)
import "xml" | xml::xml_to_markdown_table({"tag": "a", "attributes": {}, "children": [], "text": "hi"})
| 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(...)
import "xml" | xml::xml_try_parse("<a>hi</a>")["ok"]
true
import "xml" | xml::xml_try_parse("<a>unclosed")["ok"]
false
No results
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(...)
import "yaml" | yaml::to_frontmatter({"key": 1})
---
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(...)
import "yaml" | yaml::yaml_parse("key: 1")
{"key": 1}
yaml_stringify(data): string
function
Converts a data structure to a YAML string representation.
Module: import "yaml" | yaml::yaml_stringify(...)
import "yaml" | yaml::yaml_stringify({"key": 1})
key: 1
yaml_to_json(data): string
function
Converts a data structure to a JSON string representation.
Module: import "yaml" | yaml::yaml_to_json(...)
import "yaml" | yaml::yaml_to_json({"key": 1})
{"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(...)
import "yaml" | yaml::yaml_to_markdown_table([{"a": 1}])
| a |
| --- |
| 1 |
yaml_try_parse(input): dict
function
Parses a YAML string without raising on invalid input.
Module: import "yaml" | yaml::yaml_try_parse(...)
import "yaml" | yaml::yaml_try_parse("key: 1")["ok"]
true
import "yaml" | yaml::yaml_try_parse("key: [unterminated")["ok"]
false
No results
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).
.<>(): 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.
.[][](row: number, column: number): markdown
selector
Selects a table cell node with the specified row and column.
.align(): string
selector
Returns the column alignments of a table as a comma separated string (e.g. :---,---:).
.callout(kind: string, ...): markdown
selector
Selects an Obsidian-style callout node, optionally filtered by kind (e.g. .callout("note")).
.checked(): bool
selector
Returns whether a task list item is checked, or none for an item that is not a task.
.children(): array
selector
Aliases: .cn
Returns the child nodes of a container node as an array. Same as .values.
.code(lang: string, ...): markdown
selector
Aliases: .code_block
Selects a code block node with the specified language.
.definition(ident: string, ...): markdown
selector
Selects a definition node, optionally filtered by identifier.
to_markdown("[ref]: https://example.com")[0] | .definition
[ref]: https://example.com
.embed(target: string, ...): markdown
selector
Selects an Obsidian-style embed node, optionally filtered by target.
.footnote(ident: string, ...): markdown
selector
Aliases: .^
Selects a footnote node, optionally filtered by identifier.
.footnote_ref(ident: string, ...): markdown
selector
Aliases: .[^]
Selects a footnote reference node, optionally filtered by identifier.
.ident(): string
selector
Returns the normalized identifier of a definition, footnote, footnote reference, link reference or image reference.
.image(url: string, ...): markdown
selector
Selects an image node, optionally filtered by URL (e.g. .image("a.png")).
to_image("https://example.com/a.png", "Alt", "") | .image

.image_ref(ident: string, ...): markdown
selector
Selects an image reference node, optionally filtered by identifier.
to_markdown("![alt][ref]\n\n[ref]: https://example.com/a.png")[0] | .image_ref
![alt][ref]
.label(): string
selector
Returns the label of a definition, link reference, image reference or footnote reference as written, or none.
.link(url: string, ...): markdown
selector
Selects a link node, optionally filtered by URL (e.g. .link("https://example.com")).
.link_ref(ident: string, ...): markdown
selector
Selects a link reference node, optionally filtered by identifier.
.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.
.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.
.mdx_jsx_text_element(name: string, ...): markdown
selector
Selects an MDX JSX text element node, optionally filtered by tag name.
.meta(): string
selector
Returns the meta string that follows the language of a fenced code block, or none.
.name(): string
selector
Returns the tag name of an MDX JSX element.
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.
.table(row: number, column: number): markdown
selector
Selects a table cell node with the specified row and column.
.title(): string
selector
Returns the title of a link, image, definition or callout, or none when it has none.
.value(): string
selector
Returns the text content of a node, such as a text, code, link, heading, list item or table cell.
.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.
.wikilink(target: string, ...): markdown
selector
Selects an Obsidian-style wikilink node, optionally filtered by target.
No results
0 results for “”
No results