Qu

File I/O

The tables below are generated from the interpreter's own builtin dispatch table (the fn call_builtin match statement in engine/crates/qu-interp/src/lib.rs), not written speculatively ahead of the implementation — every function listed here runs today.

> Note — WASM has no filesystem at all. Qu's browser target > (wasm32-unknown-unknown) has no native filesystem access — that's an > Emscripten-target feature, not this one. Every builtin on this page that > touches a PATH (fopen, read_csv, write_csv, ...) is native-only; a > browser build can only reach files through JS-mediated mechanisms like the > File System Access API or a plain <input type=file> read. See Book 3, "A > hard platform boundary," for the full reasoning. The "Data-Format > Conversion" builtins below (jsonify/csvify/xmlify/parse_json/ > parse_csv/parse_xml and the pairwise converters) are the one exception > on this page: they only ever touch in-memory strings, no path/file > involved, so this platform boundary doesn't apply to them.

Opening & Closing Files

fopen/close are a general-purpose text/binary file-handling pair, returning/consuming an opaque Value::File handle. mode follows MATLAB's own fopen convention. Text and binary modes are treated identically at the byte level — the b suffix is accepted for MATLAB-familiar scripts, but "r" and "rb" behave the same way internally.

FunctionSignatureDescription
fopenfopen(path, mode)Opens a file for reading, writing, or appending. path (string) is the filesystem path. mode (string) is one of "r" (read, errors if the file doesn't exist), "w" (write, truncate-or-create), "a" (append, create-if-missing), or the same three with a "b" suffix ("rb"/"wb"/"ab") for binary — text and binary modes behave identically at the byte level. Returns an opaque Value::File handle to pass to every other builtin in this chapter.
closeclose(f)Flushes and releases a file handle. f (file handle, from fopen/StreamFile) is the handle to release. Returns Nothing. Reading/writing a closed handle errors clearly afterward rather than silently no-op'ing or panicking. Any pending partial write_bit byte is flushed, zero-padded. Calling close again on an already-closed handle is a harmless no-op.
touchtouch(path)Unix touch semantics. path (string) is the filesystem path: creates an empty file if it doesn't exist; if it already exists, updates its modification time WITHOUT altering its content. Returns Nothing. Uses a real mtime-set syscall (via the filetime crate) rather than the unreliable "open for append, write nothing" trick, which does not reliably bump mtime on every platform/filesystem.

> Note — "r" mode reads are a real stream, not a whole-file buffer. > Opening a file for reading no longer loads its entire contents into memory > up front — fopen(path, "r") opens a real buffered stream > (std::io::BufReader) and only reads as many bytes as read_line/ > read_all/read_char/seek/etc. actually ask for. This matters for large > files: a multi-hundred-MB (or larger) file can be opened and processed > line-by-line or byte-by-byte without ever holding the whole thing in > memory at once. Every read builtin's return values are unaffected — this > is purely an internal memory-use improvement, not a behavior change > (write/append modes were never eager-loading anything and are > untouched).

> Note — a different close exists for plotting. The bare command > close (no parentheses, used as a plot-window verb alongside pan/zoom/ > colorbar) is a separate, unrelated no-op accepted for GUI-script > compatibility in headless static exports. It lives in a completely > different match statement (the plot-command dispatch) from the > close(f) file-handle builtin documented here.

Text I/O

Every read returns Nothing — Qu's "absent" marker (composes with ??, e.g. read_line(f) ?? "done") — once nothing is left to read, except read_all, where an empty string is itself a legitimate non-exceptional result.

FunctionSignatureDescription
read_lineread_line(f)Reads one line from f (file handle, opened readable). Returns a string holding the line's content without its trailing newline (\r\n or \n), or Nothing once there is no more content to read.
read_allread_all(f)Reads every remaining byte from f (file handle, opened readable). Returns the remaining content as one string — possibly the empty string "" if called right at EOF, which is a legitimate result here, not the Nothing sentinel every other read in this section returns.
read_untilread_until(f, delimiter)Reads from f (file handle, opened readable) up to and including the next occurrence of delimiter (string), consuming it. Returns a string of everything read, with delimiter stripped off the end. If delimiter never appears again before EOF, returns everything remaining instead of erroring.
read_charsread_chars(f, n)Reads exactly n (number, count of Unicode characters, UTF-8 aware) characters from f (file handle, opened readable). Returns a string of up to n characters — fewer than n if the file ends first — or Nothing if already at EOF.
read_charread_char(f)Reads one character from f (file handle, opened readable), UTF-8 aware. Returns a one-character string, or Nothing at EOF.
write_linewrite_line(f, s)Writes s (string) to f (file handle, opened writable/appendable) plus a trailing \n. Returns Nothing.
write_charwrite_char(f, s)Writes s (string) to f (file handle, opened writable/appendable) with no newline added. Returns Nothing.

Interactive input

Not a file handle at all — reads one line typed by whoever is running the script right now, the way MATLAB's input/Python's input() do. Added in v0.3.0.

FunctionSignatureDescription
read_inputread_input([prompt])Reads one line of interactive input, returned as a string with its trailing newline stripped. prompt (string, optional), if given, is printed first with no added newline. In a real terminal (qu run/qu repl) this reads real stdin directly; a host that isn't a terminal (e.g. a Jupyter kernel) can wire its own prompt/reply round-trip instead — see that host's own documentation for what "interactive" means there. Not called input (already the machine-learning pipeline's input-layer builtin) or read_line (already "read one line from an open file/URL-stream/serial handle") — both are unrelated existing meanings, not available for this.

Writing to a handle opened in "r" mode errors clearly rather than silently no-op'ing or panicking; the same holds for every write builtin below.

Position Control & Non-Advancing Peeks

seek/tell/rewind/eof control a readable handle's read cursor directly; peek_line/peek_char/peek_byte (§ 2026-09-01) read the next unit exactly the way read_line/read_char/read_byte would, WITHOUT moving that cursor — a second peek_* call, or the very next real read_* call, sees the identical data again. Implemented as a real save-position/read/restore-position round trip around the same buffered reader seek/tell already control (not a hand-rolled one-item lookahead buffer), so it composes correctly with everything else that touches the cursor.

All of these are restricted to readable handles (the same restriction seek/tell/rewind already have) — a write-only or append-mode handle has no tracked read cursor to save/restore or report.

FunctionSignatureDescription
seekseek(f, offset, [whence="start"])Moves f's (file handle, opened readable) read cursor. offset (number, byte count) is the distance to move. whence (string, optional, default "start") is "start", "current", or "end", matching C's fseek — the point offset is measured from. Returns Nothing; errors if the resulting position falls outside [0, file length].
telltell(f)Reports f's (file handle, opened readable) current read position. Returns a number: the current byte-aligned offset from the start of the file.
rewindrewind(f)Resets f's (file handle, opened readable) read cursor to the beginning — exactly seek(f, 0). Returns Nothing.
eofeof(f)Checks whether f (file handle, opened readable) has any bytes left to read from the current position. Returns a boolean: true iff none remain.
peek_linepeek_line(f)Looks at the next line of f (file handle, opened readable) without consuming it. Returns exactly what read_line(f) would return (a string, or Nothing at EOF), but leaves the read cursor exactly where it was.
peek_charpeek_char(f)Looks at the next character of f (file handle, opened readable) without consuming it. Returns exactly what read_char(f) would return (a one-character string, or Nothing at EOF), cursor restored.
peek_bytepeek_byte(f)Looks at the next raw byte of f (file handle, opened readable) without consuming it. Returns exactly what read_byte(f) would return (a number 0-255, or Nothing at EOF), cursor restored.

Three distinct peek functions — matching read_line/read_char/ read_byte's own three existing granularities one-for-one — rather than a single generic peek(): this codebase already made that same naming choice on the read side (there is no bare read()), and a lone peek() would additionally collide with the unrelated fifo collection's own .peek() method (see Data Structures), which answers a completely different question.

Reach for peek_line whenever a parser needs to look at the next line before deciding whether to actually consume it — a "does this file start with a header row?" check, or a loop that groups lines until it sees one that doesn't belong. The example below opens a three-line log file and shows that peek_line and the following read_line see the identical first line, and only the read cursor moves once a real read_line call happens:

# The three-line file this reads is written here. It used to open a

# log.txt that the chapter does not create until 700 lines further down,

# so this block failed and was dropped from the page while the build

# reported success.

w = fopen("log.txt", "w")
write_line(w, "a")
write_line(w, "b")
write_line(w, "c")
close(w)

f = fopen("log.txt", "r")
first_line = peek_line(f)          # doesn't consume anything

same_line  = read_line(f)          # sees first_line again

next_line  = read_line(f)          # only NOW does this move on

print("{first_line} | {same_line} | {next_line}")
close(f)
# a | a | b

output
a | a | b

peek_char/peek_byte work the same way at their own granularity — a character peek for text decisions, a byte peek for binary ones — and both compose cleanly with read_until/read_chars/read_byte on the same handle, because every one of these calls shares the same underlying cursor. The example below writes "Hello,World" to a file with no newline, then walks it back with a mix of consuming reads and non-consuming peeks, printing every intermediate value so each call's effect (or lack of one) on the cursor is visible:

f = fopen("greeting.txt", "w")
write_char(f, "Hello,World")
close(f)

g = fopen("greeting.txt", "r")
first       = read_char(g)         # "H"

peeked      = peek_char(g)         # "e" -- cursor not moved

next        = read_char(g)         # "e" again, same char peeked returned

chunk       = read_chars(g, 3)     # "llo"

next_byte   = peek_byte(g)         # 44, the byte for ',' -- still not consumed

before_comma = read_until(g, ",")  # "" -- the comma was right there, now consumed

w_byte      = read_byte(g)         # 87, the byte for 'W'

rest        = read_all(g)          # "orld"

close(g)
print("{first}{next}{chunk} peeked={peeked} next_byte={next_byte} before_comma=\"{before_comma}\" w_byte={w_byte} rest={rest}")
# Hello peeked=e next_byte=44 before_comma="" w_byte=87 rest=orld

output
Hello peeked=e next_byte=44 before_comma="" w_byte=87 rest=orld

Binary I/O

Typed reads/writes accept an endian= keyword argument ("little" default, or "big"), implemented with Rust's own from_le_bytes/to_le_bytes (and their _be_ counterparts) — no hand-rolled byte shuffling. A typed read returns Nothing if fewer bytes remain than the type needs.

FunctionSignatureDescription
read_byteread_byte(f)Reads one raw byte from f (file handle, opened readable). Returns a number in 0..=255, or Nothing at EOF.
read_bitread_bit(f)Reads one bit from f (file handle, opened readable), MSB-first, advancing a sub-byte cursor that only moves to the next byte once all 8 bits of it are consumed. Returns a number, 0 or 1, or Nothing at EOF.
read_int16read_int16(f, [endian=])Reads a signed 16-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 2 bytes remain.
read_uint16read_uint16(f, [endian=])Reads an unsigned 16-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 2 bytes remain.
read_int32read_int32(f, [endian=])Reads a signed 32-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 4 bytes remain.
read_uint32read_uint32(f, [endian=])Reads an unsigned 32-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 4 bytes remain.
read_int64read_int64(f, [endian=])Reads a signed 64-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 8 bytes remain. Every Value here is an f64, exact only up to 2^53 — a value outside -2^53..=2^53 (about 9 quadrillion) comes back rounded to the nearest representable double, silently losing its low bits, the same limitation any language whose only numeric type is a double has (JavaScript's Number, for one).
read_uint64read_uint64(f, [endian=])Reads an unsigned 64-bit integer from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 8 bytes remain. Same 2^53 exact-precision ceiling as read_int64.
read_floatread_float(f, [endian=])Reads a 32-bit IEEE-754 float from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 4 bytes remain.
read_doubleread_double(f, [endian=])Reads a 64-bit IEEE-754 float from f (file handle, opened readable). endian (string, optional, default "little", or "big") selects byte order. Returns a number, or Nothing if fewer than 8 bytes remain.
write_bytewrite_byte(f, b)Writes one raw byte to f (file handle, opened writable/appendable). b (number) must be in 0..=255, or the call errors. Returns Nothing.
write_bitwrite_bit(f, b)Writes one bit to f (file handle, opened writable/appendable). b (number) must be 0 or 1, accumulated MSB-first into a pending byte and flushed to disk every 8 bits (close(f) flushes any final partial byte, zero-padded). Returns Nothing.
write_int16write_int16(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a signed 16-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_uint16write_uint16(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as an unsigned 16-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_int32write_int32(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a signed 32-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_uint32write_uint32(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as an unsigned 32-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_int64write_int64(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a signed 64-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing. Same 2^53 exact-precision ceiling on n as read_int64.
write_uint64write_uint64(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as an unsigned 64-bit integer. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing. Same 2^53 exact-precision ceiling on n as read_int64.
write_floatwrite_float(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a 32-bit IEEE-754 float. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
write_doublewrite_double(f, n, [endian=])Writes n (number) to f (file handle, opened writable/appendable) as a 64-bit IEEE-754 float. endian (string, optional, default "little", or "big") selects byte order. Returns Nothing.
read_intread_int(f, [bytes=4], [signed=true], [endian="little"])The width-as-a-value counterpart of the fixed-width family above: reads bytes (a number, 1/2/4/8 only) from f (file handle, opened readable) and decodes them as an integer, with signed (boolean) and endian (string) chosen at runtime rather than by which function you called. Reach for it when a format declares its field width in a header instead of in its spec. Returns a number, or Nothing if fewer than bytes bytes remain. Every number here is an f64, so an 8-byte value above 2^53 comes back rounded — the same ceiling read_int64 documents.
write_intwrite_int(f, value, [bytes=4], [signed=true], [endian="little"])The mirror of read_int, writing value (a number) to f (file handle, opened writable/appendable) in the given width and byte order. Unlike write_int16/write_int32, this checks that value fits and errors if it does not, rather than silently wrapping: bytes=/signed= are runtime values that can come from a variable, so a wrapped result here would be far harder to notice than picking the wrong fixed-width function. Returns Nothing.
read_binread_bin(f, n)Reads up to n (a number) raw bytes from f (file handle, opened readable). A partial read is not an error — hitting the end partway gives however many bytes were there, which is what makes a "drain this file in chunks" loop composable without an eof check each time round. Returns a Vec of numbers 0-255, or Nothing only when no bytes remain at all.
write_binwrite_bin(f, bytes)The inverse of read_bin: writes raw bytes to f (file handle, opened writable/appendable). bytes is a Vec/List of numbers, every one of them a whole number in 0..=255 — anything else errors rather than being truncated into range. Returns Nothing.

Reach for write_bit/read_bit when a format is defined at the bit level rather than the byte level — status-flag registers, packed boolean arrays, anything from an instrument or protocol spec that talks about individual bits rather than whole bytes. They pack individual bits into bytes MSB-first; close(f) flushes and zero-pads any partial byte left pending. The example below writes four bits (1,0,1,1), which is not a whole byte, closes the file to force that flush, then reads the same four bits back and confirms only one byte was actually written to disk:

f = fopen("flags.bin", "wb")
write_bit(f, 1)
write_bit(f, 0)
write_bit(f, 1)
write_bit(f, 1)
close(f)                       # only 4 bits written -- flushed as one padded byte


g = fopen("flags.bin", "rb")
b0 = read_bit(g)
b1 = read_bit(g)
b2 = read_bit(g)
b3 = read_bit(g)
close(g)
print("{b0}{b1}{b2}{b3}")      # 1011

print(file_size("flags.bin"))  # 1 -- one byte on disk for 4 bits

output
1011
1

The other fixed-width types round-trip the same way, each with its own read_*/write_* pair — this is the toolset for reading and writing a binary format with a known, fixed layout: a data-logger capture, a device's native save file, or any interchange format built around fixed-width integers and floats rather than text. The example below writes one value of each width (a signed 16-bit int, an unsigned 16-bit int, an unsigned 32-bit int, and a 64-bit double) back to back, then reads them back in the same order to show the round trip is exact:

f = fopen("sample.bin", "wb")
write_int16(f, -5)
write_uint16(f, 300)
write_uint32(f, 70000)
write_double(f, 3.14159)
close(f)

g = fopen("sample.bin", "rb")
a = read_int16(g)
b = read_uint16(g)
c = read_uint32(g)
d = read_double(g)
close(g)
print("{a} {b} {c} {d}")       # -5 300 70000 3.14159

output
-5 300 70000 3.14159

read_int64/write_int64 and their unsigned counterparts round-trip the same way, with one real caveat worth seeing rather than just stating: every Value here is an f64, exact only up to 2^53, so a 64-bit integer past that (about 9 quadrillion) comes back rounded, not exact. write_array/read_array are the block versions of the fixed-width functions above — a whole Vec or Mat written or read in one call instead of one element at a time; a Mat is written in its own column-major order, so reading it back needs a reshape/-> (r, c) to recover the original shape (a flat file has no shape of its own):

f = fopen("sample64.bin", "wb")
write_int64(f, -123456789012)
write_uint64(f, 9007199254740993)   # 1 past 2^53 -- the exact-precision edge

close(f)

g = fopen("sample64.bin", "rb")
a = read_int64(g)
b = read_uint64(g)
close(g)
print("{a} {b}")               # -123456789012 9007199254740992 -- rounded


M = [1, 2, 3; 4, 5, 6]
write_array("matrix.bin", M, type = "int32")
back = read_array("matrix.bin", type = "int32") -> (2, 3)
print(back)                    # [1, 2, 3; 4, 5, 6] -- shape recovered via reshape

output
-123456789012 9007199254740992
[1, 2, 3; 4, 5, 6]

Compression & Entropy Coding

Three from-scratch entropy coders — Huffman, adaptive range coding, and rANS — plus the zlib/DEFLATE decoder read_mat and load_image already carried internally, exposed as script-callable builtins rather than left as an implementation detail only those two readers could reach.

All four take their input the same way: a Str (its UTF-8 bytes) or a Vec of numbers in 0..=255. All four decoders hand bytes back the same way too — a Vec of 0-255 numbers by default, or the decoded text as a Str with as_str = true. An encoder returns a Record rather than a bare byte string because a decoder needs the model as well as the payload; pass the whole record straight back to the matching decoder.

There is no compressor to pair with zlib_decompress yet. That is a real gap, named here rather than implied away.

FunctionSignatureDescription
huffman_encodehuffman_encode(data)Canonical Huffman coding of data (a Str, or a Vec of 0-255 byte values). Stores the code as one byte of code length per symbol, so the decoder rebuilds the tree rather than carrying it. Returns a Record with fields lengths (a length-256 Vec, the code length of each byte value, 0 for a value that never occurs), bits (a Vec of 0-255 packed code bytes), bit_len (a Num, how many of those bits are real) and symbol_count (a Num, the input length). Empty input gives none rather than a record: there is no data to encode, and none to decode back.
huffman_decodehuffman_decode(enc, [as_str=false])Inverse of huffman_encode: enc is the whole Record that call returned, passed back unchanged; as_str (named boolean, default false) asks for text instead of bytes. Returns a Vec of 0-255 numbers, or the decoded text as a Str when as_str = true.
range_encoderange_encode(data)Byte-oriented adaptive range coding of data (a Str, or a Vec of 0-255 byte values). The model adapts as it goes, so nothing but the symbol count travels alongside the payload. Returns a Record with fields bytes (a Vec of 0-255 coded bytes) and symbol_count (a Num, the input length). Empty input gives none rather than a record.
range_decoderange_decode(enc, [as_str=false])Inverse of range_encode: enc is the Record that call returned; as_str (named boolean, default false) asks for text instead of bytes. Returns a Vec of 0-255 numbers, or the decoded text as a Str when as_str = true.
rans_encoderans_encode(data)rANS entropy coding of data (a Str, or a Vec of 0-255 byte values) — a static frequency table, unlike range_encode's adaptive model, so the table travels with the payload. Returns a Record with fields freq (a length-256 Vec, the symbol frequency table), bytes (a Vec of 0-255 coded bytes) and symbol_count (a Num, the input length). Empty input gives none rather than a record.
rans_decoderans_decode(enc, [as_str=false])Inverse of rans_encode: enc is the Record that call returned; as_str (named boolean, default false) asks for text instead of bytes. Returns a Vec of 0-255 numbers, or the decoded text as a Str when as_str = true.
zlib_decompresszlib_decompress(data, [as_str=false])Inflates a zlib stream (RFC 1950 wrapper around RFC 1951 DEFLATE): data is a Str or a Vec of 0-255 byte values; as_str (named boolean, default false) asks for text instead of bytes. Errors clearly on a stream it cannot parse rather than returning partial output. Returns a Vec of 0-255 numbers, or the decompressed text as a Str when as_str = true.

A round trip through any of the three coders returns exactly what went in:

s = "hello hello hello compression world"
enc = rans_encode(s)
print(numel(enc.bytes))                    # coded length, in bytes

print(rans_decode(enc, as_str = true) == s)  # true

output
18
true

Directories & Paths

A script that reads a file usually has to find it first. These are the builtins that answer "where am I", "what is in here" and "which of these files do I actually want" — the last of which is list_files, and it is the one worth reading about.

list_dir and list_files divide the work between them. list_dir gives the bare names inside one directory, files and subdirectories alike, and stops there. list_files takes a whole-path pattern, walks as deep as the pattern tells it to, returns paths you can open, and never returns a directory. The second is what you want for "every HTML page under website/"; the first is what you want when you are about to look at each entry and decide.

FunctionSignatureDescription
cur_dir, pwdcur_dir() / pwd()Takes no arguments. cur_dir says what it gives back and pwd is what anyone who has used a shell types first, so both spellings exist rather than one being renamed out from under existing scripts. Returns a Str: the process's current working directory, using the platform's own separator.
cdcd(path)Changes the working directory to path (a Str) for the whole process, so every later relative path in the script resolves from there. Errors if path does not exist or is not a directory, rather than leaving you somewhere you did not expect. To run one command elsewhere without moving the script, use exec's cwd= instead. Returns Nothing.
list_dir, listdir, dirlist_dir(path, [pattern])The bare names inside path (a Str), sorted — "a.qu", not "tools/a.qu". Files and subdirectories both; filter them apart with file_exists/dir_exists per entry. pattern (an optional Str) keeps only the names matching a */? wildcard, e.g. "*.csv". listdir and dir are the same builtin under the names other languages and shells use. Returns a List of Str.
list_files, globlist_files([dir], [pattern], [filter=], [contains=], [size=], [recursive=])Every file matching a whole-path wildcard, as full paths, sorted — never a directory, which is what makes the content and size filters mean something on every entry. dir is a directory to search and pattern a wildcard to match (* and ? stay inside one path segment, ** crosses them); a single argument is read as a pattern when it holds a wildcard and as a directory when it does not. filter= is the keyword spelling of the pattern; contains= keeps only files whose bytes hold that text; size= compares against the byte size (">2MB", "<=100KB", "=0", with 1024-based units); recursive= searches subdirectories without writing ** yourself. glob is the same search with no filters, under the name most other languages give it. Returns a List of Str, empty when nothing matched.
file_exists, dir_existsfile_exists(path) / dir_exists(path)Whether path (a Str) exists and is a regular file / a directory. A path that is not there at all is false, not an error — its absence is the answer you asked for. Returns a Bool.
mkdirmkdir(path)Creates the directory path (a Str), including any missing parents — mkdir -p, not bare mkdir. Idempotent: a directory that already exists is success, not an error, because "make sure this exists" is what callers actually want. Returns Nothing.
make_filemake_file(path)Creates an empty file at path (a Str), truncating it if it is already there — the same promise fopen(path, "w") makes, so the two agree. Returns Nothing.
tmp_filetmp_file()Takes no arguments. Creates a new empty file under the OS temp directory with a name nothing else will collide with (process id, nanosecond clock, and a counter — any one alone has a plausible collision window). Returns a Str: its path, not an open handle, so it composes with fopen like any other path.
remove_fileremove_file(path, [permanent=false])Deletes path (a Str) to the OS Recycle Bin/Trash by default, so it can be recovered; permanent=true deletes it outright (*default changed in v0.4.5*; the older recycle_bin=false still means permanent). Errors if it does not exist or is not a regular file, rather than silently doing nothing; on a system or volume with no trash it is an error naming permanent=true, never a silent permanent delete. With file history on, a permanent delete keeps a version first. Returns Nothing.
remove_dirremove_dir(path, [recursive=false], [permanent=false])Deletes the directory path, to the Recycle Bin/Trash by default and outright with permanent=true, as remove_file. Refuses a non-empty directory unless recursive=true — this check applies either way, since "may I remove a whole tree" and "should this be recoverable" are different questions. Returns Nothing.
rename_filerename_file(old, new, [on_exists="error"])Renames old to new (both Str), generally within the same filesystem. on_exists controls what happens if new already exists: "error" (default) refuses; "overwrite" replaces it; "skip" does nothing and returns false instead of erroring. Returns true if the rename happened, false if skipped. Unlike move_file, does not fall back to copy+delete across drives — a cross-drive rename_file fails with a clear error instead of silently becoming a slower, different operation.
move_filemove_file(src, dst, [on_exists="error"])Moves src to dst, falling back to copy-then-remove-the-original when a plain rename fails (e.g. across drives) — the on_exists collision check happens first either way, so the fallback can never overwrite something the fast path would have refused. Same on_exists values and return convention as rename_file.
copy_filecopy_file(src, dst, [on_exists="error"])Copies src to dst, leaving the original in place. Same on_exists values and return convention as rename_file/move_file.
create_filecreate_file(path, [on_exists="error"])make_file with a collision policy: "error" (default) refuses if path already exists, "overwrite" truncates it like make_file does unconditionally, "skip" does nothing and returns false. make_file itself is unchanged — this is the builtin for callers who need to say what should happen on collision, not a replacement for it.

File history

With history on, every builtin that is about to overwrite a file -- write_text, append_text, write_csv, save, savefig, write_report, save_image, save_model, the Office save_as/to_pdf, fopen in "w"/"a" mode, make_file, a copy_file/move_file/rename_file/create_file with on_exists="overwrite", a permanent remove_file -- first keeps a copy of what is there, in a .qu-versions/<file name>/ folder beside it. It is the same store Qu Studio's editor keeps on every save, so versions made by a script show in Studio's history panel and the other way round. The 50 newest versions of each file are kept; files over 100 MB are not copied (a note says so once). History is off by default; file_versioning(true) turns it on for the run, or set QU_FILE_HISTORY=1 in the environment. *Added in v0.4.5.*

FunctionSignatureDescription
file_versioningfile_versioning([on])Turns file history on (true) or off (false) for the rest of the run; with no argument, changes nothing. Returns the previous setting as a Bool.
file_historyfile_history(path)The saved versions of path, newest first, as a table with columns version (the id), saved (UTC time) and bytes. Empty when there are none. Reading history works whether or not it is on.
read_versionread_version(path, version)The content of one saved version of path as a Str. version is an id from file_history or a position: 1 is the most recent, 2 the one before.
restore_versionrestore_version(path, version)Writes that version back to path, first keeping the current content as a new version, so a restore can itself be undone. Refused under --sandbox. Returns Nothing.
file_versioning(true)
write_text("notes.txt", "first draft")
write_text("notes.txt", "second draft")    # "first draft" is kept

print(file_history("notes.txt"))
print(read_version("notes.txt", 1))        # first draft

restore_version("notes.txt", 1)            # back to the first draft

All six above are disabled in sandboxed execution (see sandbox_mode), the same as touch and write_csv — each is capable of destroying or overwriting a file the script did not create, recycle_bin=true or not.

The wildcards list_files understands

WildcardMatches
*any run of characters, within one path segment
?exactly one character, within one path segment
**zero or more whole segments, so a/**/b.txt finds a/b.txt, a/x/b.txt and a/x/y/b.txt alike

* deliberately stops at a separator. If it did not, website/*.html would also match website/fn/add.html and the ordinary case would be wrong — which is why ** has to be spelled differently, in every shell and every language that ships a glob.

Both / and \ separate segments in a pattern, so a Windows path can be written either way, and the paths that come back use the platform's own separator.

Reading list_files's arguments

One argument is a pattern if it has a wildcard in it and a directory if it does not, so neither spelling needs a keyword to say which was meant:

list_files()                          every file in the current directory
list_files("C:/users/pc")             every file in that directory
list_files("*.html")                  by pattern, here
list_files("C:/users/pc", "*.html")   directory and pattern, given apart
list_files("website/**/*.html")       the whole subtree

filter= is the keyword spelling of the pattern. Passing both a positional pattern and filter= is an error rather than a silent choice between them.

Narrowing by size and by content

KeywordWhat it keeps
contains=files whose bytes contain this text — matched against raw bytes, so it works on any file and never fails on one that is not valid UTF-8. Case-sensitive.
size=files whose byte size satisfies a comparison written as a string: ">2MB", "<=100KB", "=0", "!=0". Operators are >, >=, <, <=, =, ==, !=; with no operator at all it means equality, which is what makes size="0" read as "the empty ones".
recursive=search subdirectories too, without writing ** yourself — list_files(d, "*.html", recursive = true) is exactly list_files(d, "**/*.html").

KB/MB/GB are 1024-based here, the way a file manager reports a size rather than the 1000-based SI reading. KiB/MiB/GiB are accepted as explicit spellings of those same values. A unit that is not one of these errors, rather than being read as bytes: ">2Mb" is a typo worth hearing about, and answering it as "2 bytes" would give a wrong answer that looks like a right one.

The filters run in the order that reads the fewest bytes — the name pattern first, which opens nothing; then size=, one metadata call; then contains=, which has to read the file. Pairing contains= with a pattern or a size bound is what keeps a search over a large tree cheap.

The example below makes its own files first, so it finds the same thing wherever it is run — and note what it does not do: print cur_dir(). That would put this machine's absolute path into the page, since the documentation build runs every example and keeps what it printed.

mkdir("list_demo")
write_text("list_demo/report.qu", "print(1)")
write_text("list_demo/plot.qu", "print(2)")
write_text("list_demo/notes.txt", "the needle is here")
make_file("list_demo/empty.log")

qu_files = list_files("list_demo", "*.qu")
print("{length(qu_files)} Qu files")

carrying = list_files("list_demo/*", contains = "needle")
for f in carrying
    print("carries the needle: {f}")
end for

blank = list_files("list_demo/*", size = "0")
print("{length(blank)} empty file")
output
2 Qu files
carries the needle: list_demo\notes.txt
1 empty file

Running Other Programs

Qu could already run *code* in another language — python_exec, js_exec, matlab_exec — but not a *program*. That is a strange hole for a language whose own build tooling is written in itself: the shell scripts under tools/ exist largely because the Qu program inside each one could not ask git a question.

Two builtins, because there are two different jobs and one call does not do both well.

FunctionSignatureDescription
execexec(program, [args], [shell=], [cwd=], [stdin=], [env=], [timeout=])Runs program (a Str) and waits, capturing what it printed. args is an optional List of arguments passed to the OS as separate items — not joined into a command line and re-split — so a path with a space in it needs no quoting rule. shell=true instead reads program as a whole command line for cmd /C (Windows) or sh -c, so pipes and && work. cwd= (a Str) runs it in that directory without moving the caller. stdin= (a Str) is written to the program's input, which is then closed, so a program reading to EOF gets exactly that and does not hang. Returns a Record with stdout (a Str), stderr (a Str), success (a Bool) and exit_code (a Num) — the same fields python_exec/js_exec/matlab_exec give back, plus timed_out. env= (a Record of NAME = "value" pairs, written {NAME = "value"}) adds environment variables for the child only, e.g. env = {main_memory = "12000000"} for pdflatex. timeout= (positive seconds) kills the child and its whole process tree when it runs longer: the Record then has timed_out = true, and success/exit_code report the killed process, not a lie.
shellshell(command, [style])Hands command (a Str) to the OS shell and returns immediately, without waiting — Visual Basic's Shell, which is where the window styles come from too. style (an optional Str, positional or style=) is one of "normal" (the default), "hidden" (also spelled "ghost"), "minimized" or "maximized". Returns a Num: the process id.
load_libraryload_library(path)Loads a native shared library (.dll on Windows, .so on Linux, .dylib on macOS) so its C functions can be called with native_call. Loading runs the library's own initialisation code, and the library stays loaded until the process exits. Refused under qu run --sandbox. Returns a library handle. Added in v0.4.3.
native_callnative_call(lib, name, signature, args...)Calls the C function name in a load_library handle, with its C signature stated as a string, because a library does not record its argument types. Three shapes are supported: scalars, R(T, ...) with 0-6 arguments all of one type T in double/int32/int64 and R one of those or void ("double(double, double)"); an array kernel, R(double*, N) with N int32 or int64, which receives a copy of a vector and its length, void returning the modified copy ("void(double*, int32)"); and an array transform, void(double*, double*, N), input and same-length output, returning the output. Any other signature is refused before any native code runs. A wrong signature is undefined behaviour and a crash in the library ends the interpreter -- try cannot catch it. Callable as lib.native_call(...). Refused under --sandbox. Added in v0.4.3.

A program that fails is not a Qu error. A non-zero exit comes back as success = false, not as an exception — exec("git", ("diff", "--quiet")) uses the exit code as its answer, and a language that raised on it would make that unwritable. What *does* error is being unable to start the program at all, which is a genuinely different thing.

shell's process id is not always the program's own. "minimized" and "maximized" have no API reachable from Rust's Command, so they go through cmd /C start /MIN|/MAX, and the id that comes back belongs to that launcher — which exits as soon as it has started the program. "normal" and "hidden" spawn directly and give a real, live id. Worth knowing before you store one.

On anything other than Windows, "normal" and "hidden" behave (there is no window to hide, so hidden simply means no terminal is borrowed), and "minimized"/"maximized" error rather than being quietly ignored. They are window-manager instructions with no meaning to sh, and accepting them in silence would mean a script that looks portable and is not.

Both are refused under qu run --sandbox, alongside python_exec, js_exec and matlab_exec. Starting a process is the most capability-bearing thing a script can do, and a sandbox that let one through would not be one.

r = exec("echo hello from a program", shell = true)
print("said: {trim(r.stdout)}")
print("success {r.success}, exit code {r.exit_code}")

failed = exec("exit 3", shell = true)
print("a failure is data, not an error: success {failed.success}, code {failed.exit_code}")
output
said: hello from a program
success true, exit code 0
a failure is data, not an error: success false, code 3

Memory-Mapped Files

Read-only, random-access mapping of a file's bytes via the memmap2 crate, without loading the file into a Vec up front — useful for jumping around inside a large file (a header at a known offset, a fixed-width record at an arbitrary index) without either an eager full read or a chain of seek calls on a fopen handle. Distinct from Value::File: an mmap handle has no read cursor to advance — every mmap_read call takes an explicit byte range. Writable mapping is out of scope; use fopen/the write builtins above for writing.

FunctionSignatureDescription
mmap_openmmap_open(path)Memory-maps path (string, filesystem path) read-only. Returns an opaque mmap handle. Errors if the file doesn't exist or is empty (mapping a zero-length file is unsupported).
mmap_lenmmap_len(m)Reports the mapped file's size. m (mmap handle, from mmap_open) is the mapping to inspect. Returns a number: the total length in bytes.
mmap_readmmap_read(m, start, len)Reads a byte range out of a mapping without moving any cursor. m (mmap handle, from mmap_open) is the mapping to read from. start (number, byte offset from the beginning of the file) and len (number, byte count) select the range. Returns a Vec of len numbers, each 0-255 — the same representation read_bin uses. A range that runs past the end of the file is a clear error, not a silent truncation (unlike read_bin's "graceful partial read" — an mmap handle always knows its own length up front via mmap_len, so a past-EOF range is far more likely a caller bug than an intentional "give me whatever's left").

Reach for mmap_open/mmap_read instead of fopen/seek/read_bin when a program needs to jump around inside a large file at arbitrary offsets — a header at a known position, or one record out of a huge array of fixed-width records — without either reading the whole file up front or issuing a seek call for every access. The example below maps a binary file, reads its first 16 bytes as a "header," then reads 64 bytes starting at byte offset 5 * 64 as if the file were a flat array of 64-byte records, and prints both to show a single mapping serves any number of independent, arbitrary-offset reads:

# The file is written here first. Mapping one the repository does not

# carry would make this block fail, and a block that fails is dropped

# from the page while the build still reports success.

write_array("big_dataset.bin", 0 to 511, type = "u8")

m = mmap_open("big_dataset.bin")
n = mmap_len(m)
header = mmap_read(m, 0, 16)          # first 16 bytes, wherever they live

record5 = mmap_read(m, 5 * 64, 64)    # the 6th fixed-width 64-byte record

print(n)
print(header)
print(record5)
output
512
[0, 1, 2, 3, 4, 5, 6, 7, ... (16 elements)]
[255, 255, 255, 255, 255, 255, 255, 255, ... (64 elements)]

Polymorphic Streams: StreamFile / StreamURL

StreamFile(path, [mode]) and StreamURL(url) (§ StreamFile/StreamURL polymorphic streams, 2026-08-31) are two constructors that produce values exposing the same method names — read_line/read_all/eof/close — so code written against "a stream" doesn't need to know or check which concrete kind it was handed:

FunctionSignatureDescription
StreamFileStreamFile(path, [mode])A second name for exactly fopen's own machinery. path (string, filesystem path) is the file to open. mode (string, optional, default "r") accepts the same mode strings fopen does. Returns a Value::File handle — the same concrete type fopen returns — so every existing real-streaming fopen builtin (read_line, read_all, seek, eof, read_bin, ...) already works on it, not just the four listed here.
StreamURLStreamURL(url)url (string, an HTTP or HTTPS URL) is fetched eagerly with a GET request (same request http_get makes: GET only, 30s timeout, clear errors on an unreachable host or non-2xx status — see Networking (HTTP)). Returns an opaque stream handle wrapping the whole response body in a read-only, in-memory cursor exposing read_line/read_all/eof/close.
.read_line() / read_line(s)—s is a StreamFile/StreamURL handle. Returns one line as a string, without its trailing newline, or Nothing at EOF — identical contract on both stream kinds.
.read_all() / read_all(s)—s is a StreamFile/StreamURL handle. Returns the remaining content as one string (possibly empty at EOF).
.eof() / eof(s)—s is a StreamFile/StreamURL handle. Returns a boolean: true iff no bytes remain to read from the current position.
.close() / close(s)—s is a StreamFile/StreamURL handle. Releases it and returns Nothing. Idempotent on both kinds — closing an already-closed stream is a no-op, not an error. Reading or checking eof after close is a clear error naming the handle.

StreamURL is fetch-then-wrap, not incremental network streaming — a deliberate, investigated choice, not a shortcut. ureq's response body IS a real Read-implementing stream, but reusing fopen's exact streaming-reader plumbing against it would require widening FileHandleState's reader field to a boxed trait object AND handling HTTP responses that have no Content- Length at all (chunked transfer encoding) — a real FileHandleState redesign, not a reasonable extension of it. So StreamURL fetches the whole body up front (exactly what http_get already does) and serves it back through the same method names as a read-only in-memory stream — every method above behaves identically to the file side, just without the "hasn't downloaded yet" state a genuinely incremental reader would have.

The whole point: one function, written once against the shared method names, works unmodified against either kind. The example below defines a drain function once, using only eof/read_line/close, and calls it against a local file opened with StreamFile and a remote resource opened with StreamURL — neither the function body nor the caller needs to know which kind of stream it was handed:

n = fopen("notes.txt", "w")
write_line(n, "line one")
write_line(n, "line two")
close(n)

function drain(s)
    total = ""
    while not eof(s)
        total = total + read_line(s) + "|"
    end while
    close(s)
    return total
end function

a = drain(StreamFile("notes.txt"))
print(a)                                    # line one|line two|


b = drain(StreamURL("https://example.com/"))
print(length(b) > 0)                        # true -- some HTML came back

output
line one|line two|
true

CSV

read_csv/write_csv operate directly on a path — no fopen handle involved; they open/read/write the file internally in one call.

FunctionSignatureDescription
read_csvread_csv(path, [headers=true], [sep=","], [decimal="."])Reads a CSV file into a Table. path (string) is the file to read. headers (boolean, optional, default true) — false treats the first line as data instead of column names (columns are then auto-named col1, col2, ...). sep (string, optional, default ",") is the field delimiter. decimal (string, optional, default ".") is the decimal-point marker (e.g. sep=";", decimal="," for the European convention). Returns a Table with one row per data line and one column per field. table.load(path) is sugar for this (no keyword-argument forwarding — use read_csv directly for headers=/sep=/decimal=).
write_csvwrite_csv(df, path)Writes a Table to a CSV file. df (Table) is the data to write. path (string) is the destination file. Returns Nothing. table.write(df, path) is sugar for this — same argument order.

table.load/table.write are part of a small, closed table./timer. "namespace-dot" alias set (§ ergonomic API layer, 2026-08-31): the parser recognizes exactly the token sequence table . load ( / table . write ( and rewrites it, at parse time, straight to read_csv(...)/write_csv(...) — evaluation is byte-identical, since it's literally the same call. table is not a real namespace value; it still works as an ordinary variable name (table = 5) and the existing table(...) table-constructor call is completely unaffected (that's a different token shape — no . involved).

*Added in v0.4.0:* for a real module rather than this fixed three-name alias set, see the with <module> ... end block form in the Standard Library Reference overview — with xlsx ... .read(path) ... end reaches xlsx.read, xlsx.write, etc. the same way, for any module and any of its functions, not just table/timer/signals.

Native Modules: xlsx, codec, pdf, docx and pptx

These are not builtins, and builtins() does not list them. They are modules compiled into the engine, and a program reaches them through import, which opens their names and leaves the qualified path available at the same time:

import xlsx
names = sheets("book.xlsx")        # opened by the import

names = xlsx.sheets("book.xlsx")   # qualified, always available

Where the bare name would be ambiguous it is refused rather than guessed at. xlsx offers a read and so does the language, so a bare read after import xlsx is an error naming the fix — write xlsx.read(...) for the module's, or drop the import to get the builtin back. import nope names the modules a build actually has, which is the reliable way to find out.

Spreadsheets: xlsx

FunctionSignatureDescription
xlsx.sheetsxlsx.sheets(path)Names a workbook's worksheets without reading any of them, so a program can find out what it is holding before deciding what to load. path (string) is the .xlsx file. Returns a List of Str, the worksheet names in workbook order.
xlsx.readxlsx.read(path, [sheet], [headers=true])Reads one worksheet of a workbook into a Table, the same type read_csv produces, so everything that consumes a CSV consumes a spreadsheet unchanged. path (string) is the .xlsx file. sheet (string, optional, positional or sheet=) picks it by name; omitting it takes the first. headers (boolean, optional, default true) — false treats the first row as data and names the columns by position (A, B, C) instead. Returns a Table, one column per spreadsheet column, each column numeric or text according to what the cells hold.
xlsx.writexlsx.write(path, df, [sheet="Sheet1"])Writes a Table out as a one-worksheet workbook. path (string) is the destination, overwritten if it exists. df (Table) is the data. sheet (string, optional, positional or sheet=, default "Sheet1") names the worksheet inside the file. Returns Nothing.

A round trip, which is also the way to see what headers=false does — the header row comes back as data under positional column names:

import xlsx

t = table(city = ("Aachen", "Bonn", "Cologne"), pop = (249, 331, 1087))
xlsx.write("cities.xlsx", t, sheet = "Cities")

print(xlsx.sheets("cities.xlsx"))          # ("Cities")

print(xlsx.read("cities.xlsx"))            # a Table, city/pop

print(xlsx.read("cities.xlsx", headers = false))
output
("Cities")
city      pop
-------  ----
Aachen    249
Bonn      331
Cologne  1087
A        B   
-------  ----
city     pop 
Aachen   249 
Bonn     331 
Cologne  1087

Audio: codec

The readers take src as either a path (string) or the file's bytes as a Vec of whole numbers 0-255 — a script that already has the bytes, from a socket or an archive, should not have to write a temporary file to use them, and the two can never be confused because a FLAC stream starts with the bytes fLaC.

The WAV writer is split in two for the same reason, pointed the other way: codec.write_wav writes a file, and codec.encode_wav hands back the bytes for a script that is going to send them somewhere rather than store them. Only WAV is written — see the note below the table for what is not.

FunctionSignatureDescription
codec.flac_infocodec.flac_info(src)Reads a FLAC file's header without decoding any audio, which is how to check a file is what you expect before paying for the samples. src (string path, or Vec of bytes) is the stream. Returns a Record with fields: fs (Num, the sample rate in Hz), channels (Num, how many channels the stream carries), bits (Num, bits per sample), frames (Num, or none — a FLAC stream is allowed not to declare its length, and none says so where 0 would read as an empty file).
codec.decode_flaccodec.decode_flac(src, [channel=])Decodes a FLAC file to samples. src (string path, or Vec of bytes) is the stream. channel (number, optional, named only) picks one channel out of a multi-channel file, numbered from 0. Returns a Signal when the result is a single series, and a Record of Signals when it is not — see the two forms below.
codec.decode_wavcodec.decode_wav(src, [channel=])Decodes a WAV file. Same arguments and same two return forms as codec.decode_flac. Integer WAV is normalised by 2^(bits-1), exactly as FLAC is, so the same recording in either container gives the same numbers. Float WAV passes through untouched — it is already in -1.0 ..= 1.0, and rescaling it would be the one case where normalising changes the data — and reports bits as none, because a float format has a width but no quantisation step. Returns a Signal for a single series — a mono file, or any file with channel= — and otherwise a Record with fs, bits, frames and channels, exactly as codec.decode_flac does.
codec.decode_mp3codec.decode_mp3(src, [channel=])Decodes an MP3 file. Same arguments and same two return forms as codec.decode_flac. bits is always none: MP3 is lossy, its output is real numbers rather than a quantised grid, and a plausible 16 there would invite arithmetic that means nothing. MP3 has no header — only a run of frames — so a file that is not MP3 fails by finding no frames rather than by rejecting a magic number, and the error says so. Returns a Signal for a single series — a mono file, or any file with channel= — and otherwise a Record with fs, bits, frames and channels, exactly as codec.decode_flac does.
codec.write_wavcodec.write_wav(path, x, depth=, [dither=])Writes audio out as a WAV file. path (string) is the destination, overwritten if it exists. x is a Signal, or a List of Signals for a multi-channel file — a signal carries its own sample rate, so there is no fs= argument to get wrong, and the rates of a list have to agree because a WAV header holds exactly one. depth (number, named, required) is 16, 24 or 32, where 32 means 32-bit float. dither (string, named) is "tpdf" or "none", and at depth=16 it is required — see below. Returns Nothing. Added in v0.2.4.
codec.encode_wavcodec.encode_wav(x, depth=, [dither=])The same encoder as codec.write_wav, returning the file's bytes as a Vec of whole numbers 0-255 instead of writing them — the exact inverse of what codec.decode_wav accepts, so a stream can be re-encoded and passed on without ever touching disk. Same x, depth and dither arguments, and the same rule about naming dither at depth=16. Returns a Vec. Added in v0.2.4.

flac_info needs no split — a header is a header. The three decoders differ only in which format they read: they return the same shapes, scale to the same range, and a script that handles one handles all three.

Bit depth and dither are named, never defaulted

depth has no default because the depth is what decides how much of the signal survives the write, and a default would be the library quietly choosing that for you.

dither is required at depth=16 specifically, and leaving it out is an error rather than a silent truncation:

import codec

codec.write_wav("out.wav", x, depth = 16)
# error -- depth = 16 quantises 64-bit samples down to 16 bits, and doing

# that without saying how is an error: silent truncation of audio is

# audible. Name dither = "tpdf" or dither = "none".

Samples are 64-bit floats inside a Signal, so 16-bit is always a reduction, and it is the depth where the difference is plainly audible — rounding alone leaves harmonic distortion on fades and quiet passages. "tpdf" adds ±1 LSB of triangular noise, which trades that distortion for a flat noise floor uncorrelated with the signal; "none" is plain rounding, which is a legitimate choice as long as it is a *choice*. The dither is drawn from the interpreter's own generator, so seed(n) makes a dithered write reproducible.

depth=24 does not require the argument (it accepts it), and depth=32 refuses it: 32-bit float has no quantisation step, so there would be nothing for a dither to do.

import codec

a = codec.decode_wav("take.wav")            # a stereo file

codec.write_wav("take24.wav", a.channels, depth = 24)
codec.write_wav("take16.wav", a.channels, depth = 16, dither = "tpdf")

A round trip at a file's own depth is exact, not approximate: the scale is 2^(depth-1) in both directions, a power of two, so the integers come back as the integers they were. The one asymmetry is the format's — two's complement has no +2^(depth-1), so a sample of exactly +1.0 clips to one step below full scale, while -1.0 is exact.

Not written, and not silently implied covered: RF64 (the >4GB WAV variant), and FLAC/OGG/MP3/AIFF/CAF encoding. hound has no RF64 support in either direction and claxon is a FLAC *decoder* only, so each of these means a from-scratch container implementation — exactly what IMPL.md §7 exists to prevent. Reading FLAC, MP3 and WAV is unaffected; it is only the write direction that stops at WAV.

None of the codec examples here are run by the build: they need an audio file, and the repository carries none.

import codec

info = codec.flac_info("take.flac")
print("{info.fs} Hz, {info.channels} ch, {info.bits} bit")

Overloads: codec.decode_flac

What comes back depends on how many series the call produces, because there is no one type that fits both without lying about one of them.

Case: one series — mono, or channel=

src is a mono file; channel, when given, picks one channel out of any file, numbered from 0. Returns a Signal: the sample rate travels with the samples, so spectrogram/welch/sosfilt need no second argument. That is the whole reason Signal exists, and it is the common case.

import codec

x = codec.decode_flac("take.flac", channel = 0)
spectrogram(x)

Case: several series — multi-channel

src is a file with more than one channel; channel is absent, so no single series is picked out. Returns a Record with fields: fs (Num, the sample rate in Hz), bits (Num, bits per sample), frames (Num, samples per channel), channels (List of Signal, one per channel, each already carrying the rate — so a.channels[0] goes straight into anything that takes a signal, with no reassembly needed). A Signal is one series and a Mat has nowhere to put the sample rate, which is why this form cannot hand back either of them.

import codec

a = codec.decode_flac("stereo.flac")
print("{a.fs} Hz, {len(a.channels)} channels, {a.frames} frames")
welch(a.channels[0])

Documents: pdf

Reads and rearranges the *structure* of a PDF: how many pages it has, what it says about itself, how to join or split files, how to write or strip its metadata, and how to search or diff its text and structure against another document. It does not render, OCR, fill forms or redact — all four need a native library linked into the engine, and this module deliberately has no such dependency (see docs/design/toolkit-pdf.md for the larger roadmap this is the first slice of).

The same destination split as codec above: pdf.merge and pdf.extract_pages build a new PDF and hand back its bytes, while pdf.write_merge and pdf.write_pages build the same PDF and write it to a path given first. Two names rather than one function with an optional out =, so the return type never depends on whether a keyword was passed — and so a sandboxed script can be denied the writing pair by name while keeping the byte-returning pair, exactly as codec.write_wav/codec.encode_wav are treated.

Every function takes its source the way codec does: a path, or the file's bytes as a Vec of whole numbers 0-255. That is what lets the output of pdf.merge go straight back into pdf.page_count or pdf.extract_pages without ever touching disk.

Pages are numbered from 1, the number printed on the page. 0 is a named error rather than a silent synonym for the first page.

FunctionSignatureDescription
pdf.page_count <br> *Added in v0.3.0*pdf.page_count(src)Counts a PDF's pages. src (string path, or Vec of bytes) is the document. Counted by walking the page tree to its leaves rather than trusting the catalog's own /Count field, which a malformed or incrementally-updated file can disagree with. Returns a Num.
pdf.info <br> *Added in v0.3.0, keywords field added in v0.4.0*pdf.info(src)Reads what a PDF says about itself, without extracting any content. src (string path, or Vec of bytes) is the document. Returns a Record with fields: pages (Num, as pdf.page_count), version (Str, the header version such as "1.6"), title, author, subject, keywords, creator, producer (each Str, or none where the file's /Info dictionary omits the key — none and "" are different answers and this does not merge them), and encrypted (Bool, whether the file carries an /Encrypt dictionary, which explains in advance why another call on it might fail).
pdf.render <br> *Added in v0.4.3*pdf.render(src, [page=1], [dpi=150])Renders one page (numbered from 1) to an Image -- text, vector graphics, images and annotations, composited onto white -- at dpi dots per inch (a page is width_in_points * dpi / 72 pixels wide). src is a path or a Vec of bytes. Rasterising PDF needs a real PDF engine, so this uses Google's PDFium (the one inside Chrome), loaded when first called rather than compiled in: download pdfium.dll / libpdfium.so / libpdfium.dylib for your platform from github.com/bblanchon/pdfium-binaries and put it next to the qu program, or set QU_PDFIUM to its path (a file or its folder); the system library path is searched last. Without it the call is an error saying exactly that. Pair with save_image(path, img) to write a PNG.
pdf.merge <br> *Added in v0.3.0*pdf.merge(list)Joins several PDFs into one, in list order, keeping every page. list is a List of sources (each a string path or a Vec of bytes); an empty list is an error. Bookmarks/outlines are dropped — a half-merged outline tree pointing at pages that moved is worse than none. Returns a Vec of bytes, the new PDF.
pdf.write_merge <br> *Added in v0.3.0*pdf.write_merge(path, list)Exactly pdf.merge, written to a file instead of returned. path (string) is the destination, overwritten if it exists; list is as above. Denied in sandboxed execution. Returns Nothing.
pdf.extract_pages <br> *Added in v0.3.0*pdf.extract_pages(src, pages)A new PDF holding just the pages asked for. src (string path, or Vec of bytes) is the document; pages is a page number, or a Vec/List of them (1 to 3 works — it is already a Vec), numbered from 1. Pages come out in the document's order, not the order asked for, and a page the document does not have is a named error rather than a silently shorter file. Implemented by removing the other pages, so the ones that stay keep their own fonts, resources and annotations. Returns a Vec of bytes.
pdf.write_pages <br> *Added in v0.3.0*pdf.write_pages(path, src, pages)Exactly pdf.extract_pages, written to a file instead of returned. path (string) is the destination, overwritten if it exists. Denied in sandboxed execution. Returns Nothing.
pdf.extract_text <br> *Added in v0.3.0, normalize= and lines= added in v0.4.7*pdf.extract_text(src, [pages], [page=], [normalize=false], [lines=false])Text reconstructed from a PDF's content streams. src (string path, or Vec of bytes) is the document; pages (optional, positional or page=) is a page number or a Vec/List of them, defaulting to every page. Returns a Str. Read the warning below before relying on this. With normalize=true (added in v0.4.7) ligatures are expanded (fi fl ff ffi ffl and the presentation forms U+FB00 to U+FB06), no-break spaces become spaces, runs of whitespace collapse to one space, empty lines are dropped, and a word split by a line-end hyphen is re-joined (Fi- then nally gives Finally, the two lines becoming one) -- only when the hyphen follows a letter and the next line starts lowercase, so well- / Known is left alone. With lines=true (added in v0.4.7) the result is a List of Str, one per text line, instead of one Str: lines are rebuilt from where each text-showing operator starts (text matrix and cm are followed), grouped by baseline and ordered top to bottom, left to right within a line. There are no glyph widths, so a piece of text is placed by its start only; /Rotate is ignored; a multi-column page comes out interleaved row by row; and a page whose text is inside a Form XObject, or whose fonts have no usable encoding, is an error saying lines could not be recovered, never a faked answer. Both options default to false, which leaves the result byte-identical to earlier versions; both accept only true or false.
pdf.images <br> *Added in v0.4.7*pdf.images(src, [pages], [page=])Lists the embedded images (image XObjects) of the pages asked for, default every page, as a List of Records: page (Num), index (Num, from 1 within the page -- the number pdf.extract_image takes), name (Str, the resource name; an image inside a Form XObject, searched one level deep, is Form/Image), width, height, bits (Num; 1 for an image mask), colorspace (Str, e.g. DeviceRGB, ICCBased, Indexed, ImageMask, or none), filter (Str, the filters joined by ,, or none) and bytes (Num, the size of the stored, still-encoded stream). Inline images (BI ... EI) are not listed. An empty List, not an error, for a page with none.
pdf.extract_image <br> *Added in v0.4.7*pdf.extract_image(src, page, index)Decodes image number index (from pdf.images) of page page to an Image. Decoded: DCTDecode (JPEG, grey or RGB), and raw or FlateDecode/LZWDecode/ASCII-filtered samples (with PNG or TIFF predictors) in DeviceGray, DeviceRGB, CalGray, CalRGB, 1- or 3-component ICCBased and Indexed colour spaces, at 1, 2, 4, 8 or 16 bits (16 keeps the high byte), and image masks as black on white. An image using JBIG2Decode, CCITTFaxDecode or JPXDecode is an error naming that filter, as are CMYK, Separation, Lab and DeviceN images and a JPEG chained after another filter. A soft mask (/SMask, transparency) is not applied: you get the colour channels only. Different from pdf.render, which draws the whole page and needs PDFium: this returns the stored picture at its own resolution.
pdf.to_html <br> *Added in v0.4.7*pdf.to_html(src[, pages], [page=], [images=false])A simple HTML fragment for the pages asked for (default all; pages is positional, not a keyword): one <section class="page" data-page="N"> per page holding one <p> per paragraph, text escaped (& < >). A new paragraph starts where the gap between two lines exceeds 1.6 times the font size; a paragraph's lines are joined with spaces and line-end hyphenation is repaired (as normalize=true). Layout and fonts are not reproduced: no sizes, colours, columns, tables, links or positions, and no headings are recognised -- it is the recovered text in page order (the same limits as pdf.extract_text(lines=true) apply, including the error for a page whose lines cannot be recovered). With images=true each page's images follow its text as <img> data URIs (JPEG kept as stored, other images re-encoded as PNG; an image that cannot be decoded becomes an HTML comment naming why); their position on the page is not recovered, and the HTML can get large.
pdf.set_metadata <br> *Added in v0.4.0*pdf.set_metadata(src, [title=], [author=], [subject=], [keywords=], [creator=])Writes into a PDF's /Info dictionary (creating it if the file has none), touching only the fields passed — a keyword left out is left exactly as it was, never cleared. At least one keyword is required. An empty string (title="") is a real written value, but reads back as none from pdf.info regardless, because pdf.info already treats an empty /Info string the same as an absent key; use pdf.strip_metadata to actually remove a field's presence. Returns a Vec of bytes, the new PDF — same destination convention as pdf.merge.
pdf.strip_metadata <br> *Added in v0.4.0*pdf.strip_metadata(src)Removes a PDF's /Info dictionary entirely, and its catalog's /Metadata XMP stream reference if it has one (the XMP stream's own contents are not parsed — only the reference to it is removed, since this module has no XMP reader). A file with no /Info at all is not an error. Returns a Vec of bytes.
pdf.find_text <br> *Added in v0.4.0*pdf.find_text(src, query, [case_sensitive=])Searches every page's pdf.extract_text output for query (built on that function, not a separate reconstruction — the same warning below applies: a page extract_text cannot read is a page this cannot search either, and errors the same way). case_sensitive defaults to true; passing false case-folds character-by-character rather than via a byte comparison. Returns a List of Records, one per match, each with page (Num, from 1), offset (Num, a character offset into that page's extract_text string — not a byte offset, and not an on-page coordinate; this module reads PDF structure, not rendered glyph positions) and length (Num, the match's length in characters).
pdf.text_diff <br> *Added in v0.4.0*pdf.text_diff(src_a, src_b)Page-by-page text diff of two documents, built entirely on pdf.extract_text/pdf.page_count. Returns a Record: pages_a, pages_b (Num, each document's page count) and differing_pages — a List of Records, only for pages that differ (a page present on only one side counts as differing too), each with page (Num), only_in_a/only_in_b (Bool) and lines (List of Records with kind — "same", "added" or "removed" — and text, from a line-based LCS diff; empty when the page exists on only one side).
pdf.structural_diff <br> *Added in v0.4.0*pdf.structural_diff(src_a, src_b)A coarse, non-content comparison: page count, per-page /MediaBox size, whether each document has an outline (/Outlines) and each document's total annotation count. Returns a Record: pages_a, pages_b (Num), differing_dimensions (List of Records only for pages whose size differs or that exist on only one side, each with page (Num) and a/b — a Record {width, height} in PDF points, or none when that side lacks the page), bookmarks_a/bookmarks_b (Bool) and annotations_a/annotations_b (Num). Deliberately shallow — bookmark-by-bookmark or annotation-by-annotation comparison is a larger feature this does not attempt.
pdf.outlines <br> *Added in v0.4.0*pdf.outlines(src)The document's bookmark/outline tree, flattened into a Table — one row per entry, depth-first. Columns: index (the row's own position, and the handle parent= below takes), level (Num, 0 for a top-level entry), parent_index (Num, the index of the entry this one is nested under, or -1 for a top-level entry), title (Str), and page_index (Num, one-based, or NaN where the entry's destination is not a direct page reference this reads — a named destination or a non-GoTo action). An empty Table (zero rows), not an error, for a PDF with no outlines.
pdf.add_bookmark <br> *Added in v0.4.0*pdf.add_bookmark(src, title, page_index, parent=)Adds a new outline entry titled title, pointing at page_index (one-based). parent= (optional Num) nests it under an existing entry, named by the index column of a prior pdf.outlines(src) call on THIS document — the one stable handle to an existing entry this module exposes. Omitted, the new entry is top-level. Returns a Vec of bytes, the new PDF.
pdf.annotations <br> *Added in v0.4.0*pdf.annotations(src, page)A page's annotations as a List of Records: index (Num, the handle pdf.remove_annotation takes), type (Str, the annotation's /Subtype verbatim — "Text", "Square", "Highlight", "Link", ...), rect (Vec of 4 numbers, [x0, y0, x1, y1]), and text (Str, or none where the annotation carries no /Contents). An empty List, not an error, for a page with none.
pdf.add_annotation <br> *Added in v0.4.0*pdf.add_annotation(src, page, type=, rect=, text=, [color=])Adds a simple annotation to a page (page counts from 1). type= (Str) is written verbatim as the PDF /Subtype — this does not validate it against PDF's own list. rect= is [x0, y0, x1, y1]. text= (optional Str) becomes the annotation's /Contents. color= (optional [r, g, b], each 0 to 1) sets the annotation colour (for "FreeText" it is the text colour, on a light-yellow callout box). The four text-markup types "Highlight", "Underline", "StrikeOut" and "Squiggly" are drawn from /QuadPoints, which Qu writes from rect= so they actually show (default colours yellow, green, red, red); a Highlight without them exists in the file but renders as nothing. "Text" (a note icon) and "Square" draw as written. Returns a Vec of bytes: save with bytes_write(path, bytes).
pdf.remove_annotation <br> *Added in v0.4.0*pdf.remove_annotation(src, page, index)Removes the index-th entry of a page's /Annots array (the index pdf.annotations reports), deleting the underlying object too. An out-of-range index is a named error. Returns a Vec of bytes.
pdf.add_link <br> *Added in v0.4.0*pdf.add_link(src, page, rect=, target_page=)Adds a /Link annotation over rect= that jumps to target_page= (one-based) of the SAME document. Returns a Vec of bytes.
pdf.replace_text <br> *Added in v0.4.12*pdf.replace_text(src, old, new, [page=], [count=], [case_sensitive=true])Changes text in an existing PDF and returns the edited file as a Vec of bytes (save with bytes_write). Edits the strings of Tj/TJ/'/" operators (literal or hex, Flate decoded) in page content streams, for simple fonts (Type1/TrueType, one byte per glyph): a match may span several strings of one TJ array or several consecutive show operators, and a TJ gap wider than a space matches a space. page= limits the edit to one page, count= to the first N replacements, case_sensitive=false folds case. Pages it does not change are left byte-identical. Refuses with a named error (never a corrupted file) when nothing can be replaced: text in a composite Type0/CID font (the error names the font), text only in a Form XObject, text split by positioning/colour operators, or a replacement character the font cannot show; in a subset font (ABCDEF+Name) or a Type3 font (matplotlib's default) only characters already shown on that page can be used. Nothing is reflowed: a longer replacement keeps its starting point and can overlap what follows.
pdf.add_text <br> *Added in v0.4.12*pdf.add_text(src, page, x, y, text, [size=12], [color=[0,0,0]], [font="Helvetica"])Stamps one line of text on a page with its baseline starting at (x, y) in PDF points from the bottom-left of the unrotated page (/Rotate and /CropBox are not compensated). font is one of the 12 standard fonts (Helvetica, Helvetica-Bold, Times-Roman, Courier, ...); text is WinAnsi-encoded, so characters outside Western European + common punctuation, and newlines, are errors. The existing page content is wrapped in q/Q so it cannot affect the stamp. Returns a Vec of bytes; the stamp is simple-font text, so pdf.replace_text can edit it later.
pdf.attachments <br> *Added in v0.4.0*pdf.attachments(src)The document's embedded files, listed via the catalog's /Names/EmbeddedFiles name tree, as a List of Records: filename (Str) and size (Num, the decompressed byte length). An empty List, not an error, for a document with none. Only the flat form of the name tree is read — see pdf.add_attachment.
pdf.add_attachment <br> *Added in v0.4.0*pdf.add_attachment(src, filename, bytes)Embeds a file under filename. bytes is a path or a Vec of bytes, the same dual form every other src argument here takes. Creates the /Names/EmbeddedFiles chain if the document does not have one yet. Adding the same filename twice keeps both — pdf.extract_attachment then reads back the first. Returns a Vec of bytes.
pdf.extract_attachment <br> *Added in v0.4.0*pdf.extract_attachment(src, filename)The raw bytes of the first embedded file named filename; a name that is not there is a named error. Returns a Vec of bytes.
pdf.media_box <br> *Added in v0.4.0*pdf.media_box(src, page)The page's /MediaBox -- the boundary a PDF prints on, in PDF points (1/72 inch). page is a single page number. Resolves inheritance from an ancestor /Pages node when the page sets none of its own (the common case for a document where every page is the same size), the way a real reader does. Returns a Record with fields x0, y0, x1, y1 (each Num): lower-left then upper-right corner.
pdf.crop_box <br> *Added in v0.4.0*pdf.crop_box(src, page)The page's /CropBox -- the region a viewer actually shows, which can be smaller than /MediaBox. Falls back to /MediaBox when the page has no /CropBox of its own or inherited, which is what an absent /CropBox means per the spec, not an error. Same Record shape as pdf.media_box.
pdf.rotate_page <br> *Added in v0.4.0*pdf.rotate_page(src, page, degrees)Sets a page's /Rotate -- degrees a viewer turns the page CLOCKWISE before display. degrees is added to whatever rotation the page already has (its own, or inherited), so calling this twice with 90 turns a page 180° total; must be a multiple of 90, refused by name otherwise. Result is normalized into 0..360. Returns a Vec of bytes, the new PDF.
pdf.crop_page <br> *Added in v0.4.0*pdf.crop_page(src, page, x0, y0, x1, y1)Sets a page's /CropBox to the given rectangle (PDF points). Validated against the page's /MediaBox: an inverted/zero-area rectangle, or one reaching outside the media box, is refused by name rather than silently accepted. Returns a Vec of bytes, the new PDF.
pdf.add_page <br> *Added in v0.4.0*pdf.add_page(src, index, [width=], [height=])Inserts a blank page at index (numbered from 1; one past the last page appends). width/height are in PDF points, defaulting to A4 (595 × 842) when omitted -- no paper-size convention exists elsewhere in the engine, and this matches what this module's own test fixtures already use. The new page has a real, empty content stream (a legitimate blank page). Returns a Vec of bytes, the new PDF.
pdf.delete_page <br> *Added in v0.4.0*pdf.delete_page(src, page)Removes page. Every other page's own resources, fonts and content are untouched. Deleting a document's only page is refused by name -- a zero-page PDF is not a document any reader can open. Returns a Vec of bytes, the new PDF.
pdf.duplicate_page <br> *Added in v0.4.0*pdf.duplicate_page(src, page)Inserts a copy of page immediately after it. The copy is a new page object -- rotating or cropping one afterward does not touch the other -- but shares its /Contents//Resources with the original (legal in PDF, and far cheaper than duplicating a stream's bytes). Returns a Vec of bytes, the new PDF.
pdf.move_page <br> *Added in v0.4.0*pdf.move_page(src, from, to)Relocates page from so it becomes page to, keeping every other page's relative order. Both are numbered from 1 and must already be within the document's page range. Returns a Vec of bytes, the new PDF.
pdf.reverse_pages <br> *Added in v0.4.0*pdf.reverse_pages(src)Reverses page order: the last page becomes the first and vice versa. Returns a Vec of bytes, the new PDF.
pdf.split_every <br> *Added in v0.4.0*pdf.split_every(src, n)Splits src into consecutive chunks of up to n pages each, in document order (the last chunk may be shorter). Returns a List, each element a Vec of bytes (one document per chunk).
pdf.split_at <br> *Added in v0.4.0*pdf.split_at(src, index)Splits src into exactly two documents at index (numbered from 1): the first holds pages 1..index, the second index..page_count. Both halves must come out non-empty -- index must be strictly between 1 and the page count, refused by name otherwise. Returns a List of exactly 2 elements, each a Vec of bytes.

Bookmarks, annotations/links and attachments are all pure object-graph edits — no rendering, and no dependency beyond lopdf. Each mutating function (pdf.add_bookmark, pdf.add_annotation, pdf.remove_annotation, pdf.add_link, pdf.add_attachment) takes a source PDF and returns a new one as bytes, the same build-bytes-not-write-a-file shape pdf.merge/pdf.extract_pages use — there is no pdf.write_bookmark-style pair for these, so chain them by feeding one call's Vec output straight into the next call's src.

import pdf

doc = pdf.merge(["intro.pdf", "results.pdf"])
doc = pdf.add_bookmark(doc, "Introduction", 1)
doc = pdf.add_bookmark(doc, "Results", 3)
rows = pdf.outlines(doc)
print(rows)  # index, level, parent_index, title, page_index


doc = pdf.add_annotation(doc, 1, type = "Text", rect = [10, 10, 200, 40], text = "draft")
doc = pdf.add_attachment(doc, "notes.txt", "notes.txt")
pdf.write_pages("with_extras.pdf", doc, 1 to pdf.page_count(doc))

Every page-tree op above (add_page/delete_page/duplicate_page/ move_page/reverse_pages/split_every/split_at) resolves any /MediaBox//CropBox//Rotate//Resources a page inherits from an ancestor /Pages node and copies it directly onto the page before restructuring the tree -- so a page whose size came from an intermediate node, not its own dict, does not silently change size (or lose it) when it moves. None of the eleven functions above opens a file: like pdf.merge/pdf.extract_pages, they take bytes or a path and hand back bytes, so none is on the sandbox's deny list (only pdf.write_merge/ pdf.write_pages are) and none has a write_* sibling of its own -- pipe the returned bytes into pdf.write_pages or ordinary file I/O to persist one.

pdf.extract_text is the weak one, and says so

A PDF does not store paragraphs. It stores "draw glyph X at (321, 418)", so extraction is a *reconstruction*, and it only works when a document's fonts use a standard encoding or ship a /ToUnicode map. Two specific limits apply:

What this module will *not* do is hand back "" and let that read as "this document has no text". When extraction produces nothing, it checks whether the requested pages can reach any embedded font — following Form XObjects, not just the page's own resources. No font reachable means the page really has no text (a scanned bitmap, a pure vector drawing) and "" is the honest answer. A font reachable but no text out means the extractor failed, and that is an error naming the reason, not an empty string.

Measured on the 34 PDFs committed in this repository (2026-09-23): 21 gave readable text, 8 raised that error (every pdfcrop-produced file among them), and 5 were genuinely textless. None returned the wrong text. pdf.page_count, pdf.info, pdf.merge and pdf.extract_pages were correct on all 34 — they are the solid part of this module.

import pdf

i = pdf.info("paper.pdf")
print("{i.pages} pages, PDF {i.version}, produced by {i.producer}")

# Join two files, then take one page out of the result -- no disk in

# between, because every function also accepts bytes.

both = pdf.merge(["intro.pdf", "results.pdf"])
print(pdf.page_count(both))
pdf.write_pages("just_page_3.pdf", both, 3)

# A page range. `1 to 5` is already a Vec, so it just works.

pdf.write_pages("front.pdf", "paper.pdf", 1 to 5)

Text extraction, written the way it should be — assuming it can fail:

import pdf

try
    t = pdf.extract_text("paper.pdf", page = 1)
    print(t)
catch err
    print("no text layer this engine can read: {err}")
end

Metadata write, text search, and comparing two revisions of the same document:

import pdf

# Only `subject` changes; title/author/producer/... are untouched.

tagged = pdf.set_metadata("paper.pdf", subject = "Impedance spectroscopy")
pdf.write_merge("tagged.pdf", [tagged])  # or write it out any other way


hits = pdf.find_text("paper.pdf", "impedance", case_sensitive = false)
for h in hits
    print("page {h.page}, offset {h.offset}")
end

d = pdf.text_diff("draft_v1.pdf", "draft_v2.pdf")
print("{length(d.differing_pages)} of {d.pages_b} pages changed")

s = pdf.structural_diff("draft_v1.pdf", "draft_v2.pdf")
if s.pages_a != s.pages_b
    print("page count changed: {s.pages_a} -> {s.pages_b}")
end

None of the pdf examples here are run by the build: they need document files that are not in the repository.

Office documents: docx, pptx, and editing workbooks with xlsx

Word documents, PowerPoint presentations and Excel workbooks, opened as handles and edited in place. doc = docx.open("paper.docx") returns a small handle value; every edit changes the document behind it, and docx.save_as(doc, path) writes it out. This is file-handle semantics on purpose: a document is a mutable thing with an identity, like an open file.

The editing is *surgical* (see docs/design/toolkit-office.md). The original package is kept, only the parts an operation touches are rewritten, and everything else a file holds -- themes, fonts, embedded objects, macros, custom XML, vendor extensions -- is written back byte for byte. That is the difference between editing someone's thesis and reconstructing a lookalike of it.

The function names never coincide with a builtin (save_as, not save; get_cell, not get), so importing these modules never makes a builtin ambiguous.

import docx
import pptx
import xlsx

doc = docx.open("paper.docx")
docx.replace_text(doc, "2025", "2026")
docx.add_heading(doc, "Results", 1)
docx.add_paragraph(doc, "The measured impedance was 42.3 ohm.", bold = true)
docx.add_table(doc, table(f = [1000, 2000], Z = [42.3, 40.1]))
docx.add_image(doc, "nyquist.png", width = 12 cm)
docx.add_link(doc, 1, "https://example.org/eis-primer", on = "impedance")
docx.add_comment(doc, 2, "Check this value", on = "42.3", author = "Ahmed")
docx.set_footer(doc, "Page #page of #pages", align = "center")
docx.add_toc(doc, at = 0, title = "Contents")      # Word builds it on open

docx.save_as(doc, "paper_2026.docx")
docx.to_pdf(doc, "paper_2026.pdf")          # needs LibreOffice

docx.to_latex(doc, "latex/paper.tex")       # images go to latex/figures/


p = pptx.open("lecture.pptx")
s = pptx.add_slide(p, title = "Impedance Spectroscopy", body = ["Nyquist", "Bode"])
pptx.add_image(p, s, "eis.png", x = 120 mm, y = 40 mm, w = 100 mm)
pptx.save_as(p, "lecture_new.pptx")

wb = xlsx.open("results.xlsx")
xlsx.set_cell(wb, "Results", "A1", "Frequency")
xlsx.fill_formula(wb, "Results", "C2:C100", "=A2*B2")
xlsx.freeze_panes(wb, "Results", "A2")
xlsx.save_as(wb, "results_new.xlsx")

Word: docx

FunctionSignatureDescription
docx.open <br> *Added in v0.4.3*docx.open(path)Opens a Word document for reading and editing and returns a handle. Editing is surgical: only the parts an operation changes are rewritten, and everything else -- themes, fonts, embedded objects, custom XML, macros, extensions Qu has never heard of -- is written back byte for byte.
docx.new <br> *Added in v0.4.3*docx.new()A new, empty A4 document with Normal, Title and Heading 1-3 styles. Returns a handle.
docx.save_as <br> *Added in v0.4.3*docx.save_as(doc, path)Writes the document (overwriting). Refused under --sandbox. docx.discard(doc) releases the handle early.
docx.full_text <br> *Added in v0.4.3*docx.full_text(doc)Every paragraph's text in document order -- body, tables, text boxes -- one per line, tabs and line breaks included.
docx.paragraphs <br> *Added in v0.4.3*docx.paragraphs(doc)The body-level paragraphs as a List of Str. Their positions are the indices set_paragraph/insert_paragraph/remove_paragraph use (0-based).
docx.headings <br> *Added in v0.4.3*docx.headings(doc)A List of {level, text} records for heading-styled paragraphs, resolved through the document's own style names (so a German Überschrift 1 counts); the Title style is level 0.
docx.find_text <br> *Added in v0.4.3*docx.find_text(doc, text)Indices of the body paragraphs containing text, as a vector.
docx.replace_text <br> *Added in v0.4.3*docx.replace_text(doc, old, new)Replaces old with new everywhere text lives -- body, tables, text boxes, headers, footers, footnotes, endnotes, comments -- even where Word split the text across formatting runs. The replacement keeps the formatting of the run each match starts in. Returns the number of replacements.
docx.set_paragraph <br> *Added in v0.4.3*docx.set_paragraph(doc, i, text)Replaces body paragraph i's text, keeping its paragraph style and its first run's character formatting.
docx.insert_paragraph <br> *Added in v0.4.3*docx.insert_paragraph(doc, i, text, [formatting])Inserts a paragraph so it becomes body paragraph i; takes the same keywords as add_paragraph. docx.remove_paragraph(doc, i) deletes one.
docx.add_heading <br> *Added in v0.4.3*docx.add_heading(doc, text[, level])Appends a heading; level 0 is the Title style, 1-9 the Heading styles (created in the document's style sheet if it lacks them). level is positional (default 1) -- level=2 as a keyword is not accepted.
docx.add_paragraph <br> *Added in v0.4.3*docx.add_paragraph(doc, text, [bold=], [italic=], [underline=], [size=], [font=], [color=], [align=], [style=])Appends a paragraph. size in points, color #rrggbb, align left/center/right/justify, style a paragraph style id (Quote). \n in text is a line break, \t a tab.
docx.add_table <br> *Added in v0.4.3*docx.add_table(doc, data, [header=])Appends a bordered table from a Table (its column names become a bold header row that repeats on each page), a matrix or a list of rows.
docx.add_image <br> *Added in v0.4.3*docx.add_image(doc, path, [width=], [height=])Appends a PNG, JPEG or GIF as its own paragraph. width/height are millimetres or lengths (6 cm); give one and the other follows the aspect ratio, neither and it is placed at 96 dpi capped to the text width.
docx.add_page_break <br> *Added in v0.4.3*docx.add_page_break(doc)Appends a page break.
docx.tables <br> *Added in v0.4.3*docx.tables(doc)Every body table as a list of rows of cell texts. docx.set_cell(doc, table, row, col, text) changes one cell (all 0-based), keeping its formatting.
docx.comments <br> *Added in v0.4.3*docx.comments(doc){author, date, text} records. docx.footnotes(doc) and docx.endnotes(doc) return the notes' texts.
docx.info <br> *Added in v0.4.3*docx.info(doc)A record of the document properties (title, creator, created, modified, ...) plus counts: paragraphs, words, characters, tables, images, comments, headings. docx.set_info(doc, title=, author=, subject=, keywords=, description=, category=) sets them.
docx.accept_changes <br> *Added in v0.4.3*docx.accept_changes(doc)Accepts every tracked change (insertions kept, deletions dropped, formatting changes kept) in every part of the document; docx.reject_changes(doc) does the opposite. Returns the number of revision marks resolved.
docx.to_markdown <br> *Added in v0.4.3*docx.to_markdown(doc)The content as Markdown: headings as #, tables as pipe tables, list paragraphs as - items.
docx.to_latex <br> *Added in v0.4.3*docx.to_latex(doc, [path], [full=true])The content as LaTeX: Title as \title, headings as \section/\subsection, bold/italic/underline kept, list paragraphs as itemize, tables as tabular, images as \includegraphics, special characters escaped. With path, writes the .tex and the images into figures/ beside it. full=false returns the body only, for \input. Content, not appearance: page layout and custom styles are not carried over. Returns the source.
docx.to_pdf <br> *Added in v0.4.3*docx.to_pdf(doc, path, [timeout=300])Converts to PDF by running LibreOffice headless in a private profile (so it neither needs nor disturbs an open LibreOffice). Laying out a document is a word processor's whole job, so Qu hands it to one: no LibreOffice, no conversion, and the error says how to get it (or set QU_SOFFICE to its soffice executable). Refused under --sandbox. Returns the PDF's size in bytes.
docx.add_linkdocx.add_link(doc, i, url, [on=])Makes body paragraph i -- all of it, or the first occurrence of the text on (case-sensitive) -- a hyperlink to url. A url starting with # links to a bookmark in the document ("#results"). Runs are split at the edges so the rest of the paragraph keeps its formatting; the linked text gets the document's Hyperlink character style (created if missing). *Added in v0.4.5*
docx.linksdocx.links(doc)Every hyperlink in the body (tables included) as {text, url} records; internal links come back as #name. *Added in v0.4.5*
docx.add_commentdocx.add_comment(doc, i, text, [on=], [author="Qu"], [initials=], [date=])Attaches a comment to body paragraph i (or to the text on in it), creating the document's comments part when it has none. \n in text starts a new comment paragraph; date is ISO 8601 and defaults to now (UTC). Read back with docx.comments. *Added in v0.4.5*
docx.add_bookmarkdocx.add_bookmark(doc, i, name, [on=])Puts a bookmark named name around body paragraph i (or the text on in it) -- the target for add_cross_ref and #name links. Names follow Word's rule: a letter, then letters, digits or _, at most 40 characters. docx.bookmarks(doc) lists {name, text} records (Word's hidden _Toc/_GoBack ones included). *Added in v0.4.5*
docx.add_cross_refdocx.add_cross_ref(doc, i, name, [show="text"])Appends a cross-reference to bookmark name at the end of body paragraph i: show="text" shows the bookmarked text (a REF field, filled in now with the true text), "page" its page number (PAGEREF), "number" its paragraph number. Page and paragraph numbers depend on layout, so they are left for Word/LibreOffice to compute when the document is opened. *Added in v0.4.5*
docx.add_fielddocx.add_field(doc, i, code, [text=])Appends any field -- "PAGE", "NUMPAGES", "DATE \\@ \"d MMMM yyyy\"", "REF name \\h" -- to the end of body paragraph i, marked dirty so the word processor computes it on open; text is what shows until then. docx.fields(doc) lists the instructions of every field in the body, simple and complex. *Added in v0.4.5*
docx.add_tocdocx.add_toc(doc, [levels=3], [at=], [title=])Inserts a table-of-contents field for heading levels 1 to levels, before body paragraph at (or at the end), optionally under a title paragraph. Qu does not lay out pages, so it does not invent entries: the field is marked dirty and the document asks Word to update fields on open. LibreOffice does not rebuild a TOC when it opens a .docx (so neither does docx.to_pdf): until someone updates it (Tools > Update > Update All), it shows a line saying so. *Added in v0.4.5*
docx.sectionsdocx.sections(doc)Each section's page setup as a record: width, height, top, bottom, left, right (mm), orientation ("portrait"/"landscape"), start (next_page, continuous, even_page, odd_page), and headers/footers -- the kinds (default, first, even) the section defines itself; the rest it inherits from the section before. *Added in v0.4.5*
docx.page_setupdocx.page_setup(doc, [section=], [size=], [orientation=], [margins=], [top=], [bottom=], [left=], [right=])Changes page size ("A4", "A3", "A5", "B5", "Letter", "Legal", or [width, height]), orientation ("portrait"/"landscape", which swaps width and height) and margins (millimetres or lengths; margins sets all four, the others override it) -- of section section (0-based), or of every section when omitted. *Added in v0.4.5*
docx.add_section_breakdocx.add_section_break(doc, [start="next_page"])Ends the current section at the end of the document; what is added next is a new section starting next_page, continuous, even_page or odd_page, with the same page setup until page_setup(doc, section=...) changes it. The new section inherits its headers and footers until it is given its own. *Added in v0.4.5*
docx.set_headerdocx.set_header(doc, text, [section=], [kind="default"], [align=])Sets a header's text, replacing its content (creating the header part if there is none). #page and #pages in text become page-number and page-count fields ("Page #page of #pages") -- not {page}, which a Qu string would interpolate. kind is default, first (first page of the section; turns on "different first page") or even (turns on different odd/even pages). Without section every header of that kind is set (section 0 gets one if the document has none); with it, only that section's, which gets its own if it was inheriting one. docx.set_footer is the same for footers. *Added in v0.4.5*
docx.header_textdocx.header_text(doc, [section=0], [kind="default"])The text of a section's header (following inheritance from earlier sections), one line per paragraph, or none if it has none. docx.footer_text reads footers. Fields show their last computed value. *Added in v0.4.5*
docx.add_list_itemdocx.add_list_item(doc, text, [kind="bullet"], [level=0], [restart=false])Appends a bulleted (kind="bullet") or numbered (kind="number") list paragraph at nesting level 0-8, creating the document's numbering definitions when it has none. Consecutive numbered items continue one list; restart=true starts again from 1. Numbered levels go 1. / a. / i.; bullets •, ◦, ▪. *Added in v0.4.5*
docx.set_listdocx.set_list(doc, i, [kind="bullet"], [level=0], [restart=false])Makes existing body paragraph i a list item, or plain again with kind="none". *Added in v0.4.5*
docx.add_rowdocx.add_row(doc, table, [values], [at=])Inserts a row into body table table (0-based) so it becomes row at (default: appended). values is a list with one item per cell, the rest left blank. The new row copies its neighbour's layout -- cell widths, borders, shading, merges, and the first run's formatting -- but never a header row's "repeat on every page" flag or bold; a row inserted inside a vertically merged block joins the merge. *Added in v0.4.7*
docx.add_columndocx.add_column(doc, table, [values], [at=])Inserts a column so it becomes grid column at (default: appended), with one value per row. The table keeps its width: existing columns shrink to make room, as in Word. Where the new column falls inside a merged cell, that cell grows to cover it and takes no value. *Added in v0.4.7*
docx.merge_cellsdocx.merge_cells(doc, table, row1, col1, row2, col2)Merges the rectangle of cells from (row1,col1) to (row2,col2), inclusive and 0-based, into one cell (a column span across, a vertical merge down). The top-left cell's formatting wins and the other cells' text follows it, one paragraph each (empty ones dropped). Columns are *grid* columns -- the columns docx.tables shows until cells are merged. A range that cuts through an existing merged cell is refused. *Added in v0.4.7*
docx.split_celldocx.split_cell(doc, table, row, col, [cols=])Undoes a merge: the merged cell containing grid cell (row,col) becomes its individual cells again, the text staying in the top-left one. With cols=N (2 or more) a cell that is *not* merged is cut into N side by side, and the other rows keep their layout by spanning the new columns. *Added in v0.4.7*
docx.format_textdocx.format_text(doc, i, [on=], [all=false], [bold=], [italic=], [underline=], [strike=], [size=], [color=], [font=])Formats existing text in body paragraph i: the first occurrence of on, every occurrence with all=true, or the whole paragraph when on is omitted. Runs are cut at the edges of the span -- even inside a hyperlink or a tracked insertion -- so the text outside keeps its formatting exactly, and only the properties given change inside it. bold=false switches an inherited bold off. size in points, color #rrggbb. Returns how many spans were formatted. *Added in v0.4.7*
docx.line_spacingdocx.line_spacing(doc, i, [to=], [lines=], [exactly=], [at_least=], [before=], [after=])Sets spacing for body paragraphs i through to (default: just i). Line spacing is one of lines= (a multiple: 1.5, 2.0), exactly= or at_least= (points); before= and after= are points of space around the paragraph. Properties not given are left as they are. Returns how many paragraphs changed. *Added in v0.4.7*
docx.move_paragraphdocx.move_paragraph(doc, from, to)Moves body paragraph from so that it becomes body paragraph to (as numbered after the move). Tables and other block content stay where they are. A paragraph that ends a section carries the section break and is refused. *Added in v0.4.7*
docx.add_footnotedocx.add_footnote(doc, i, text, [on=])Creates a footnote with text (\n starts a new paragraph in it) anchored after the first occurrence of on in body paragraph i, or at the end of the paragraph. Word numbers footnotes by position. Creates the footnotes part, its separator notes and the note styles when the document has none; docx.footnotes reads them back. *Added in v0.4.7*
docx.track_insertdocx.track_insert(doc, i, text, [after=], [before=], [author="Qu"], [date=])Inserts text into body paragraph i as a tracked insertion (w:ins by author, ISO 8601 date, default now): directly after the first occurrence of after, directly before the first occurrence of before, or at the end. The text takes the formatting of the run next to it. docx.accept_changes keeps it, docx.reject_changes removes it. Refused inside a field or another tracked insertion. *Added in v0.4.7*
docx.track_deletedocx.track_delete(doc, i, [on=], [all=false], [author="Qu"], [date=])Marks text in body paragraph i as a tracked deletion (w:del, the text kept as w:delText): the first occurrence of on, every occurrence with all=true, or all of the paragraph -- including its paragraph mark, so accepting removes the paragraph -- when on is omitted. Rejecting restores the text. Refused inside a field's result. Returns how many spans were marked. *Added in v0.4.7*

PowerPoint: pptx

FunctionSignatureDescription
pptx.open <br> *Added in v0.4.3*pptx.open(path)Opens a presentation for reading and editing and returns a handle -- surgical editing, as docx.open. Slides are numbered from 0 in the order PowerPoint shows them.
pptx.new <br> *Added in v0.4.3*pptx.new()A new, empty 16:9 presentation with four layouts: Title Slide, Title and Content, Title Only, Blank.
pptx.save_as <br> *Added in v0.4.3*pptx.save_as(p, path)Writes the presentation. Refused under --sandbox. pptx.discard(p) releases the handle.
pptx.slide_count <br> *Added in v0.4.3*pptx.slide_count(p)The number of slides. pptx.slides(p) returns every slide's text; pptx.slide_text(p, i) one slide's (a line per paragraph, tables included); pptx.slide_title(p, i) its title placeholder's text or none; pptx.notes(p, i) its speaker notes.
pptx.find_text <br> *Added in v0.4.3*pptx.find_text(p, text)Indices of the slides containing text.
pptx.replace_text <br> *Added in v0.4.3*pptx.replace_text(p, old, new, [notes=true])Replaces across every slide (and the speaker notes unless notes=false), across formatting runs, keeping each match's formatting. Returns the count.
pptx.layouts <br> *Added in v0.4.3*pptx.layouts(p)The layout names add_slide can use.
pptx.add_slide <br> *Added in v0.4.3*pptx.add_slide(p, [layout=], [title=], [body=], [at=])Adds a slide from a layout (by name, case-insensitive, or index; default Title and Content), filling its title placeholder and its body placeholder (body a string, one bullet per line, or a list). at inserts at that position instead of appending. Returns the new slide's index.
pptx.delete_slide <br> *Added in v0.4.3*pptx.delete_slide(p, i)Deletes a slide with its notes, and removes it from any section. pptx.move_slide(p, from, to) reorders; pptx.duplicate_slide(p, i) copies a slide (without its notes) right after itself and returns the copy's index; pptx.hide_slide/pptx.unhide_slide(p, i) skip it in the slide show.
pptx.add_text <br> *Added in v0.4.3*pptx.add_text(p, i, text, [x=], [y=], [w=100], [h=20], [size=], [bold=], [italic=], [color=], [font=], [align=])Adds a text box to slide i. Positions are millimetres from the top-left corner or lengths (20 mm); size in points. Newlines start new paragraphs.
pptx.add_image <br> *Added in v0.4.3*pptx.add_image(p, i, path, [x=], [y=], [w=], [h=])Adds a PNG/JPEG/GIF; give one of w/h and the other follows the aspect ratio, neither and it is centred at 96 dpi.
pptx.add_table <br> *Added in v0.4.3*pptx.add_table(p, i, data, [x=], [y=], [w=200], [h=], [size=14], [header=])Adds a table (from a Table, matrix or list of rows) in PowerPoint's built-in Medium Style 2.
pptx.info <br> *Added in v0.4.3*pptx.info(p)Document properties plus slides, width_mm, height_mm and layouts. pptx.set_info sets properties as docx.set_info does.
pptx.to_markdown <br> *Added in v0.4.3*pptx.to_markdown(p)One ## Slide N: title section per slide, the other text as bullets and the notes as a quote.
pptx.to_pdf <br> *Added in v0.4.3*pptx.to_pdf(p, path, [timeout=300])Converts to PDF through LibreOffice, as docx.to_pdf.
pptx.set_notespptx.set_notes(p, i, text)Sets slide i's speaker notes (newlines start paragraphs). A slide with no notes page gets one, and a deck with no notes master gets a minimal one; only the notes parts, that slide's relationships and the package bookkeeping are written -- the slide itself is untouched. *Added in v0.4.5*
pptx.shapespptx.shapes(p, i)The slide's top-level shapes, back to front, as records with id, name, kind (text, placeholder, shape, picture, table, chart, graphic, group, connector), placeholder (its type, or none), x, y, w, h in mm (a placeholder that sets no position reports the one it inherits from its layout or master) and text. The other shape functions take a shape as this id (stable across saves) or its name; a group is one shape. *Added in v0.4.5*
pptx.set_shape_textpptx.set_shape_text(p, i, shape, text)Replaces a text box's, placeholder's or shape's text, one paragraph per line, keeping the first run's formatting. *Added in v0.4.5*
pptx.set_slide_titlepptx.set_slide_title(p, i, text)Sets the slide's title placeholder text, adding the title placeholder from the slide's layout if the slide has none. *Added in v0.4.5*
pptx.move_shapepptx.move_shape(p, i, shape, [x=], [y=])Moves a shape (mm or lengths); pptx.resize_shape(p, i, shape, [w=], [h=]) resizes it. A coordinate not given is kept. *Added in v0.4.5*
pptx.delete_shapepptx.delete_shape(p, i, shape)Deletes a shape; a relationship only it used goes too, and an image no other part uses is removed from the package. *Added in v0.4.5*
pptx.bring_to_frontpptx.bring_to_front(p, i, shape)Draws the shape on top of the others; pptx.send_to_back(p, i, shape) behind them. *Added in v0.4.5*
pptx.set_linkpptx.set_link(p, i, shape, url, [text=])Makes every occurrence of text in the shape a hyperlink to url (splitting a run where the match is only part of it; the pieces keep its formatting), or without text= all of the shape's text. Returns the number linked. pptx.links(p, i) lists the slide's links as records with shape, text and url. *Added in v0.4.5*
pptx.theme_colorspptx.theme_colors(p)The theme's colour scheme as a record of #RRGGBB strings: dk1, lt1, dk2, lt2, accent1...accent6, hlink, folHlink. pptx.theme_fonts(p) gives major (headings) and minor (body) typefaces. *Added in v0.4.5*
pptx.set_theme_colorspptx.set_theme_colors(p, [dk1=], ..., [accent1=], ..., [folHlink=])Sets colour-scheme slots ("#RRGGBB"); pptx.set_theme_fonts(p, [major=], [minor=]) sets the heading/body typefaces. Only the theme part is rewritten; everything that uses a theme colour or font follows. *Added in v0.4.5*
pptx.add_chartpptx.add_chart(p, i, kind, y, [x=], [names=], [colors=], [title=], [x_title=], [y_title=], [at=], [width=160], [height=90], [lines=], [markers=], [legend=], [x_min=], [x_max=], [y_min=], [y_max=], [x_log=false], [y_log=false], [equal_axes=false], [shape_name=])Adds a native, scalable PowerPoint chart to slide i from numbers given directly (a vector or a table column such as data.z); returns the new shape's id. kind is "scatter" (XY, both axes numeric), "line", "bar" (vertical) or "barh" (horizontal). y is a vector for one series, or several series as a parenthesised list (a, b) of vectors or a matrix with one column per series (a bracketed [[..], [..]] is flattened by Qu itself into one vector, so give names= to catch that). x= is one vector shared by all series (x values for scatter, categories for line/bar -- a list of strings gives text labels) or a list with one per series. names=/colors= go one per series (colours by name or #rrggbb, default Qu's plot palette). at=[x, y] is the top-left corner (millimetres or lengths; default: centred on the slide); width/height in millimetres or lengths. Scatter draws markers only (lines=true joins them), line charts lines only. Axis limits, log scales and equal_axes=true (one unit the same length along both axes) are scatter-only. A legend appears when there are several series or names. The numbers are stored in the chart as cached literals, not in an embedded workbook: it renders everywhere with exactly the data given, but PowerPoint's "Edit Data" has no sheet to open -- build a chart that must stay editable with xlsx.add_chart. Only the slide, its relationships, [Content_Types].xml and the new chart part change. *Added in v0.4.7*
pptx.add_nyquist_chartpptx.add_nyquist_chart(p, i, re, im, [negate=true], [name=], [color=], [title=], [x_title="Z' / Ω"], [y_title="-Z'' / Ω"], [at=], [width=150], [height=110], [lines=false], [markers=], [legend=], [shape_name=])A Nyquist plot for impedance spectroscopy on slide i: Z' along x, -Z'' up, both axes on the SAME scale with square gridlines, so a semicircle stays round. Give Z' and Z'' as two vectors, or call pptx.add_nyquist_chart(p, i, Z, ...) with one complex vector (its real part against minus its imaginary part). With negate=true (Z'' as measured, negative for a capacitive arc) -Z'' is plotted; negate=false plots im as given. The axis limits follow the data. Returns the new shape's id. Data are cached literals, as for pptx.add_chart. *Added in v0.4.7*
pptx.add_shapepptx.add_shape(p, i, kind, x=, y=, w=, h=, [fill=], [stroke=], [stroke_width=1.5], [dash=], [radius=], [text=], [size=], [bold=], [italic=], [color=], [font=], [align="center"], [name=])Adds a shape to slide i and returns its id. kind is "rect", "ellipse" ("oval") or "rounded_rect" -- placed by x, y, w, h -- or "line" / "arrow" (an arrowhead at the end), placed from (x=, y=) to (x2=, y2=) with only stroke=, stroke_width=, dash= and name= besides. Positions are millimetres from the top-left corner or lengths. fill= and stroke= take a colour name or #rrggbb, or "none"; the default is Qu's palette blue with no outline (an unfilled shape and every line get a dark outline, or they would be invisible). stroke_width is in points, dash is "solid", "dash", "dot" or "dashdot", radius (rounded rectangles) is the corner as a fraction of the shorter side, 0 to 0.5. text= puts text inside (newlines start paragraphs; size, bold, italic, color, font, align format it; the colour defaults to black or white, whichever reads on the fill). Colours are written explicitly rather than taken from the theme, so the shape looks the same in any deck. Nothing on the master, the layouts or the slide's animation timing is touched. *Added in v0.4.7*
pptx.rotate_shapepptx.rotate_shape(p, i, shape, degrees)Sets the shape's rotation to degrees clockwise (0 or 360 clears it; a negative angle turns it the other way). A placeholder positioned by its layout gets its own position first, so it does not jump. Charts, tables and other graphic frames cannot be rotated in PowerPoint and say so. *Added in v0.4.7*
pptx.align_shapespptx.align_shapes(p, i, shapes, how, [to="selection"])Lines shapes (a list of ids and/or names) up: how is "left", "right", "top", "bottom", "center" (horizontally) or "middle" (vertically). to="selection" aligns to the bounding box of the shapes themselves (two or more needed, as PowerPoint's "Align Selected Objects"); to="slide" aligns each to the slide. A rotated shape is aligned by the box it fills on the page; shapes already in place are not rewritten. *Added in v0.4.7*

Editing a workbook: xlsx

xlsx.read/xlsx.write above move whole tables and cannot change a file; these open one and edit it in place.

FunctionSignatureDescription
xlsx.open <br> *Added in v0.4.3*xlsx.open(path)Opens an existing workbook for editing in place and returns a handle (a small Model); every xlsx.* edit below changes the workbook behind it until xlsx.save_as. Everything the file holds that these functions do not touch -- other sheets, charts, formats -- is read and written back.
xlsx.new <br> *Added in v0.4.3*xlsx.new()A new workbook with one empty sheet, Sheet1. Returns a handle.
xlsx.save_as <br> *Added in v0.4.3*xlsx.save_as(wb, path)Writes the workbook to path (overwriting). Refused under --sandbox.
xlsx.discard <br> *Added in v0.4.3*xlsx.discard(wb)Releases the handle early; handles otherwise live until the run ends.
xlsx.get_cell <br> *Added in v0.4.3*xlsx.get_cell(wb, sheet, cell)The value of one cell, cell as Excel shows it ("B3"); sheet is a name or a 0-based index. Returns a number, string, boolean, or none for an empty cell. A formula cell returns the value last cached in the file, if any -- formulas are stored, not evaluated.
xlsx.set_cell <br> *Added in v0.4.3*xlsx.set_cell(wb, sheet, cell, value)Sets one cell to a number, string, boolean, or none (empty). NaN and infinity are refused -- Excel has no representation for them.
xlsx.formula <br> *Added in v0.4.3*xlsx.formula(wb, sheet, cell)The formula in a cell without its leading =, or none.
xlsx.set_formula <br> *Added in v0.4.3*xlsx.set_formula(wb, sheet, cell, formula)Stores a formula (the = is optional). Excel and LibreOffice calculate it when the file is opened; xlsx.read of a freshly written formula cell sees no value yet.
xlsx.fill_formula <br> *Added in v0.4.3*xlsx.fill_formula(wb, sheet, range, formula)Stores formula in every cell of range, shifting its relative references from the range's first cell the way Excel's fill-down does ($-anchored parts, string literals and quoted sheet names stay). Returns the number of cells written.
xlsx.get_range <br> *Added in v0.4.3*xlsx.get_range(wb, sheet, range, [numeric=false])A rectangular range ("A1:C20") as a list of rows of cell values; with numeric=true, a matrix with NaN for anything that is not a number.
xlsx.set_range <br> *Added in v0.4.3*xlsx.set_range(wb, sheet, anchor, data, [header=true])Writes a Table (its column names first, unless header=false), a matrix, a vector (one column) or a list of rows, with its top-left corner at anchor.
xlsx.used_range <br> *Added in v0.4.3*xlsx.used_range(wb, sheet)The smallest range covering every non-empty cell, e.g. "A1:D20", or none for an empty sheet.
xlsx.add_sheet <br> *Added in v0.4.3*xlsx.add_sheet(wb, name)Adds an empty sheet. xlsx.rename_sheet(wb, sheet, new) and xlsx.delete_sheet(wb, sheet) rename and remove (the last sheet cannot be removed).
xlsx.insert_rows <br> *Added in v0.4.3*xlsx.insert_rows(wb, sheet, row, [n=1])Inserts n rows before 1-based row, shifting references. Also xlsx.delete_rows, and xlsx.insert_columns/xlsx.delete_columns(wb, sheet, "C", [n]) by column letter.
xlsx.column_width <br> *Added in v0.4.3*xlsx.column_width(wb, sheet, col, width)Column width in Excel's character units (0-255); xlsx.row_height(wb, sheet, row, points) sets a row's height.
xlsx.format_cells <br> *Added in v0.4.3*xlsx.format_cells(wb, sheet, range, [bold=], [italic=], [size=], [font=], [color=], [background=], [number_format=], [align=])Formats every cell of range: colours as #rrggbb, number_format in Excel's own codes (0.00, 0.00E+00, yyyy-mm-dd), align left/center/right. Returns the number of cells formatted.
xlsx.merge <br> *Added in v0.4.3*xlsx.merge(wb, sheet, range)Merges a range into one cell.
xlsx.freeze_panes <br> *Added in v0.4.3*xlsx.freeze_panes(wb, sheet, cell)Freezes the rows above and the columns left of cell: "A2" keeps the header row in view, "B2" the header row and first column.
xlsx.define_name <br> *Added in v0.4.3*xlsx.define_name(wb, name, address)A workbook-level defined name, e.g. xlsx.define_name(wb, "Frequency", "Data!$A$2:$A$100").
xlsx.to_pdf <br> *Added in v0.4.3*xlsx.to_pdf(wb, path, [timeout=300])Converts the workbook to PDF through LibreOffice (see docx.to_pdf). Returns the PDF's size in bytes.
xlsx.add_chartxlsx.add_chart(wb, sheet, kind, y, [x=], [names=], [colors=], [title=], [x_title=], [y_title=], [at=], [width=160], [height=90], [lines=], [markers=], [legend=], [x_min=], [x_max=], [y_min=], [y_max=], [x_log=false], [y_log=false], [equal_axes=false])Adds a native Excel chart that refers to the cells, so it follows later edits in Excel/LibreOffice. kind is "scatter" (XY, both axes numeric), "line", "bar" (vertical) or "barh" (horizontal). y is a range string ("B2:B40", "Data!B2:B40") or a list of them, one series each; x= is one range shared by all series or one per series (x values for scatter, category labels for line/bar). names=/colors= go one per series (colours by name or #rrggbb, default Qu's plot palette). at= is the top-left cell (default: two columns right of the used range, row 2); width/height in millimetres or lengths. Scatter draws lines and markers by default (lines=false for points only), line charts lines only. Axis limits, log scales and equal_axes=true (one unit the same length along both axes) are scatter-only. A legend appears when there are several series or names. Returns none. Charts, conditional formats and validations are written into the saved file part by part: a workbook whose cells were not edited keeps everything else byte for byte. *Added in v0.4.5*
xlsx.add_nyquist_chartxlsx.add_nyquist_chart(wb, sheet, re, im, [negate=true], [helper=], [name=], [color=], [title=], [x_title="Z' / Ω"], [y_title="-Z'' / Ω"], [at=], [width=150], [height=110], [lines=false], [markers=], [legend=])A Nyquist plot for impedance spectroscopy: Z' (range re) along x, -Z'' up, the axes on the SAME scale with square gridlines, so a semicircle stays round. With negate=true (Z'' stored with its sign, negative for a capacitive arc) a helper column of =-Z'' formulas is written -- in column helper= (a letter), default the first free column right of the used range, with a -<header> label above it when there is a header row -- and its range is returned, e.g. "D2:D40"; with negate=false im is plotted as it is, no cell changes, and none is returned. The axis limits follow the data at save time. *Added in v0.4.5*
xlsx.conditional_formatxlsx.conditional_format(wb, sheet, range, rule, value, [value2], [fill=], [color=], [bold=])Highlights the cells of range that satisfy rule: "greater_than", "less_than", "greater_equal", "less_equal", "equal", "not_equal", "between"/"not_between" (two values, inclusive), or "contains" (text, case-insensitive). A value is a number, a string (compared as text), or a string starting with = (an Excel formula, e.g. "=$B$1"). fill= is the background, color= the font colour (names or #rrggbb); with none of fill/color/bold given it uses Excel's default light-red fill with dark-red text. Returns none. *Added in v0.4.5*
xlsx.color_scalexlsx.color_scale(wb, sheet, range, [low="#F8696B"], [mid=], [high="#63BE7B"])Colours every cell of range on a scale from its lowest value (low) to its highest (high); with mid= a three-colour scale centred on the 50th percentile. Returns none. *Added in v0.4.5*
xlsx.add_validationxlsx.add_validation(wb, sheet, range, kind, [values=], [source=], [min=], [max=], [formula=], [prompt=], [prompt_title=], [error=], [error_title=], [error_style="stop"], [allow_blank=true])Restricts what can be typed into range. kind "list" offers a drop-down from values=[...] (no commas or quotes inside a value, 255 characters in all) or from the cells of source="D2:D9" (another sheet: "Lists!A1:A5"); "whole"/"decimal" take min=, max= or both (inclusive); "custom" takes formula=, written for the range's first cell ("=B2>A2"). prompt=/prompt_title= show when a cell is selected, error=/error_title= when a value is refused; error_style "warning" or "information" lets the user keep it anyway. Keywords that do not apply to kind are errors. Returns none. *Added in v0.4.5*
xlsx.copy_sheetxlsx.copy_sheet(wb, sheet, new_name)Copies a sheet to a new one named new_name, appended after the last sheet: cells, formulas, formatting, merges, column widths, freeze panes, conditional formats, validations, and the charts, notes, pictures and tables the sheet carries (a chart on the copy reads the copy's own cells; a copied table is renamed Name_2, table names being unique). The copy is not the selected tab. Defined names scoped to the source sheet are not copied. Returns none. *Added in v0.4.7*
xlsx.hide_sheetxlsx.hide_sheet(wb, sheet, [state="hidden"])Hides a sheet: state="hidden" (Excel's Hide; the user can Unhide it), "very_hidden" (not in Excel's Unhide list -- only reachable from the VBA editor or by calling this again) or "visible" to show it. A workbook keeps one visible sheet, so hiding the last is an error; hiding the sheet the workbook opens on moves the opening tab to the first visible one. Returns none. *Added in v0.4.7*
xlsx.clearxlsx.clear(wb, sheet, range, [what="all"])Empties a range: what="contents" removes values and formulas and keeps the formatting, "formats" removes the formatting and keeps the values, "all" both. Returns the number of stored cells it touched. *Added in v0.4.7*
xlsx.move_rangexlsx.move_range(wb, sheet, range, to, [to_sheet=], [copy=false])Moves range so its top-left corner lands on cell to (on to_sheet, default the same sheet), taking values, formulas and formatting and overwriting what was there; blanks in the source blank the destination. A move keeps formulas as written; copy=true leaves the source and shifts relative references as a paste does. Formulas elsewhere that point into the moved cells are NOT rewritten. A range that cuts through a merged range is refused. Returns the number of cells moved. *Added in v0.4.7*
xlsx.sort_rangexlsx.sort_range(wb, sheet, range, by, [desc=false], [header=false])Sorts the rows of range by one or more key columns: by="C" is a column of the sheet, by=2 the second column of the range, a list (by=["B", "A"]) breaks ties by the next key, and desc is one flag or one per key. Whole rows move -- values, formulas (relative references follow the row, as in Excel's sort) and formatting -- and the sort is stable. header=true keeps the first row on top (the default is false: nothing is guessed). Order as Excel's: numbers, then text (case-insensitive), then true/false; empty cells last in either direction. A key cell holding a formula with no stored value (never calculated) is an error, and so is a range holding merged cells. Returns none. *Added in v0.4.7*
xlsx.autofilterxlsx.autofilter(wb, sheet, range, [remove=false])Puts filter buttons on the header row of range (header row plus the data below it). The filter is switched on, not applied: no row is hidden. xlsx.autofilter(wb, sheet, remove=true) takes it off. One autofilter per sheet; a range inside an Excel Table already has its own buttons. Returns none. *Added in v0.4.7*
xlsx.create_tablexlsx.create_table(wb, sheet, range, name, [header=true], [style="medium2"], [stripes=true], [total=])Turns range into an Excel Table named name (letters, digits, _ and ., starting with a letter or _, not a cell address like A1; unique in the workbook): banded rows, filter buttons, structured references. range includes the header row; header cells that are empty, numeric or repeated are rewritten as unique text (Column3, Sales2) so the cells and the table agree; header=false for data only. style is "light1"-"light21", "medium1"-"medium28", "dark1"-"dark11" (or Excel's TableStyleMedium2), or "none". total=true (or "sum", "average", "count", "min", "max") adds a totals row just BELOW range (it must be empty): the label Total under the first column and a SUBTOTAL formula under every column holding only numbers (stored, not evaluated). A table may not overlap another table, the sheet's autofilter or a merged range. Returns none. *Added in v0.4.7*
xlsx.add_commentxlsx.add_comment(wb, sheet, cell, text, [author="Qu"])Attaches a note to a cell (the red corner; the text shows on hover). A second note on the same cell replaces the first. Written into the saved file as its own parts (comments + legacy drawing), so the sheet, its charts and everything else are untouched. Returns none. *Added in v0.4.7*
xlsx.add_imagexlsx.add_image(wb, sheet, path, [at=], [width=], [height=], [alt=])Places a PNG, JPEG or GIF with its top-left corner at cell at (default: two columns right of the used range, row 2, like add_chart). With neither size given it is shown at its pixel size at 96 dpi, scaled down to at most 160 mm wide; with one of width=/height= (millimetres or lengths) the other follows the aspect ratio. It is anchored to cells with a two-cell anchor (it moves with them), the form every reader keeps, and alt= is its description for screen readers. Returns none. *Added in v0.4.7*

Data-Format Conversion (JSON / CSV / XML)

read_csv/write_csv above and save/save_all/load (see Collections, Strings & Data Frames for the json_to_value/"type"-tag shape save/load use) all read/write a FILE. The builtins below (§ data-format conversion builtins, 2026-09-01) are the same conversions as plain in-memory STRINGS instead — for building a request body, embedding data in another format's document, or converting between formats without ever touching disk. Two primitives per format (xify(value) -> str / parse_x(str) -> value), plus six pairwise converters. Four of the six are one-line compositions of those primitives — e.g. json2csv(s) is exactly csvify(parse_json(s)) — not four independent implementations. The other two, csv2json and xml2json, deliberately do not go through jsonify: they produce a plain JSON array of row objects (the shape most external JSON consumers expect) rather than jsonify's own {"type":"table", ...} envelope — see their table entries below for the exact contract. A conversion that doesn't make sense for the input's shape (a bare number has no CSV shape; a live handle like a worker or mutex has no meaning in any of these formats) is a clear, named error, not a panic or a silently wrong result.

FunctionSignatureDescription
jsonifyjsonify(value)Converts any value (any Value — number, string, Vec, Table, Record, ...) to a JSON string — exactly the save/load on-disk shape (see the link above: a {"type": ..., ...} envelope), just returned as a string instead of written to a file. Returns a string.
parse_jsonparse_json(str)jsonify's inverse. str (string) is JSON text — either a jsonify/save-style {"type": ...} envelope, or ordinary JSON from anywhere else (e.g. an HTTP API response), which is mapped in generically. Returns the reconstructed Value.
csvifycsvify(table)Converts table (Table) to CSV text — exactly write_csv's own formatting (Table::to_csv), just returned as a string instead of written to a file. Returns a string. Errors clearly on anything that isn't a Table (a bare scalar/vector has no tabular shape).
parse_csvparse_csv(str)Converts str (string, CSV text) to a Table — exactly read_csv's own parsing (Table::from_csv, the headers=true, sep=",", decimal="." defaults; use read_csv on a real file for the headers=/sep=/decimal= keyword arguments). Returns a Table.
xmlifyxmlify(value)Converts any value (any Value) to an XML string — see "The Value<->XML mapping" below. Returns a string.
parse_xmlparse_xml(str)xmlify's inverse. str (string) is XML text in xmlify's own element-naming convention. Returns the reconstructed Value.
json2csvjson2csv(str)str (string, JSON text) is converted to CSV text: exactly csvify(parse_json(str)). Returns a string.
csv2jsoncsv2json(str)str (string, CSV text) is converted to JSON. Not jsonify(parse_csv(str)) — it emits a plain JSON array of one flat {"col": value, ...} object per row (the natural shape for feeding to another JSON-consuming tool), rather than jsonify's own {"type":"table", ...} envelope. json2csv accepts either shape back, since parse_json understands both. Returns a string.
xml2jsonxml2json(str)str (string, XML text in xmlify's convention) is converted to JSON. Like csv2json, this produces the same plain array-of-row-objects shape, not jsonify(parse_xml(str))'s type-tagged envelope. Returns a string.
json2xmljson2xml(str)str (string, JSON text) is converted to XML: exactly xmlify(parse_json(str)). Returns a string.
xml2csvxml2csv(str)str (string, XML text) is converted to CSV text: exactly csvify(parse_xml(str)). Returns a string.
csv2xmlcsv2xml(str)str (string, CSV text) is converted to XML: exactly xmlify(parse_csv(str)). Returns a string.

Overloads: parse_json

Case: a jsonify/save envelope

str carries a top-level "type" string field — the tag jsonify/save attach. Returns the exact typed Value that tag names, reconstructed in full, not a generic guess from the JSON's own shape.

env = jsonify(3 + 4j)
back = parse_json(env)
print(env)          # {"type":"complex","re":3.0,"im":4.0}

print(type(back))   # complex

print(back)         # 3 + 4j

output
{"type":"complex","re":3.0,"im":4.0}
complex
3 + 4j

Case: ordinary JSON, no envelope

str is plain JSON from anywhere else — an HTTP API response, hand-written JSON, or the same envelope with its "type" tag stripped off. Mapped in generically instead: a bare object becomes a record field-for-field, so the identical re/im pair that named a Complex above comes back as a plain record once the tag naming it is gone.

env = jsonify(3 + 4j)
plain = replace(env, "\"type\":\"complex\",", "")
v = parse_json(plain)
print(plain)         # {"re":3.0,"im":4.0}

print(type(v))       # record

output
{"re":3.0,"im":4.0}
record

The Value<->XML mapping

XML had no support anywhere in Qu before this (via the quick-xml crate — see engine/crates/qu-interp/Cargo.toml's own comment for why). Every value serializes to one XML element named after its type (<num>, <vec>, <table>, ...) — the direct analogue of jsonify's own "type" tag, just moved from a JSON object key to the thing XML tags things with (an element name). A few shapes get a genuinely XML-native structure instead of a mechanical port of the JSON one:

See engine/crates/qu-interp/src/xml_ops.rs's own module doc comment for the complete variant-by-variant mapping table.

The example below builds a small two-row Table from CSV text, converts it to XML with xmlify to show the <columns>/<row> shape described above, parses it back with parse_xml to confirm the round trip preserves the data, and then runs the same CSV text through csv2json — printed here to make the point from the table above concrete: the result is a plain array of row objects, not jsonify's type-tagged envelope:

t = parse_csv("name,age\nAlice,30\nBob,25\n")
print(xmlify(t))
# <table>

#   <columns>

#     <column kind="str">name</column>

#     <column kind="num">age</column>

#   </columns>

#   <row>

#     <name>Alice</name>

#     <age>30</age>

#   </row>

#   <row>

#     <name>Bob</name>

#     <age>25</age>

#   </row>

# </table>


back = parse_xml(xmlify(t))
print(back.name[0])   # Alice


j = csv2json("product,price\nWidget,9.99\n")
print(j)               # [{"product":"Widget","price":9.99}]

output
<table>
  <columns>
    <column kind="str">name</column>
    <column kind="num">age</column>
  </columns>
  <row>
    <name>Alice</name>
    <age>30</age>
  </row>
  <row>
    <name>Bob</name>
    <age>25</age>
  </row>
</table>
    ... 2 more lines

jsonify/parse_json are the JSON side of the same pair csvify/parse_csv and xmlify/parse_xml already show above. Of the pairwise converters not shown elsewhere on this page, json2xml, xml2csv, and csv2xml are each exactly the one-line composition their own table entry says they are; xml2json is the row-object conversion csv2json just demonstrated, applied to XML input instead of CSV:

The next example chains every converter on this page against the same two-row table, in both directions, to demonstrate that the whole set forms a connected graph — CSV to JSON, JSON back to CSV, CSV to XML and back, JSON to XML and back — and that parse_json at the very end can still recover a real Table even though the JSON it's reading came from xml2json's row-object shape rather than jsonify's own envelope:

t = parse_csv("product,price\nWidget,9.99\nGadget,4.50\n")

csv_text = csvify(t)
json_text = jsonify(t)

back_from_json = json2csv(json_text)   # csvify(parse_json(json_text))

print(back_from_json)

xml_from_csv = csv2xml(csv_text)       # xmlify(parse_csv(csv_text))

csv_from_xml = xml2csv(xml_from_csv)   # csvify(parse_xml(xml_from_csv))

print(csv_from_xml)

xml_from_json = json2xml(json_text)    # xmlify(parse_json(json_text))

json_from_xml = xml2json(xml_from_json) # the row-object array, not jsonify(parse_xml(...))

parsed = parse_json(json_from_xml)      # parse_json accepts that shape too -- back to a real Table

print(nrow(parsed))                     # 2

output
product,price
Widget,9.99
Gadget,4.5

product,price
Widget,9.99
Gadget,4.5

2

See catalog/qu_format_conversion.qu for a fuller worked demo (JSON/CSV/XML round trips plus two pairwise converters on real sample data, with printed output proving correctness field-by-field).

Worked examples

The most basic file-writing pattern in Qu: open a handle in "w" mode (truncate-or-create), write one line at a time with write_line, and close the handle when done to flush it to disk. This is the shape almost every logging or report-writing script starts from. The example prints file_size afterward just to make the write's effect on disk visible:

f = fopen("log.txt", "w")
write_line(f, "run started")
write_line(f, "value = " + str(42))
close(f)
print(file_size("log.txt"))    # 23 -- "run started\n" + "value = 42\n"

output
23

Reading it back: read_line returns Nothing at EOF, but Qu today has neither a source-level nothing literal nor ==/!= support for two Str operands (compare's catch-all falls back to as_num(), which errors on a string — the same pre-existing gap noted next to contains/indexof in Collections, Strings & Data Frames), so an EOF-sentinel-comparison loop isn't expressible yet. For a known number of lines, a bounded loop works cleanly; for an unknown number, read_all is the more honest tool today:

f = fopen("log.txt", "r")
for i = 0 to 1
    print(read_line(f))
end for
close(f)

g = fopen("log.txt", "r")
print(read_all(g))
close(g)
output
run started
value = 42
run started
value = 42

Reading a whole CSV straight into a Table (no fopen needed) and working with it using the Data Frame builtins from Collections, Strings & Data Frames, then writing a filtered subset back out to a second CSV file:

The file is written here before it is read, so the example runs anywhere — including a fresh clone. It used to open a measurements.csv that no part of the repository created, which meant the block could not run, and a block that cannot run is dropped from the rendered page without the build reporting anything: the page shipped with the example missing and the build said it succeeded.

measurements = table(
    x = [-1.5, 0.5, 2.0, -0.25, 3.75],
    sensor = ["a", "b", "a", "c", "b"]
)
write_csv(measurements, "measurements.csv")

df = read_csv("measurements.csv")
print(nrow(df))
print(describe(df))
write_csv(filter(df, df.x > 0), "positive_only.csv")
print(read_all_text("positive_only.csv"))
output
5
stat         x
-----  -------
count        5
mean       0.9
std    2.03562
min       -1.5
25%      -0.25
50%        0.5
75%          2
max       3.75
x,sensor
0.5,b
2,a
    ... 1 more lines

A minimal binary I/O round trip: open a handle in "wb" mode, write a 32-bit integer followed by a 32-bit float, close it, then reopen the same file in "rb" mode and read the two values back in the same order they were written. This is the pattern every other binary example on this page builds on — the typed read_*/write_* pairs only work correctly when the read order matches the write order, since there's no type tag on disk to check against:

f = fopen("record.bin", "wb")
write_int32(f, 12345)
write_float(f, 3.5)
close(f)

g = fopen("record.bin", "rb")
n = read_int32(g)
x = read_float(g)
close(g)
print("n = {n}, x = {x}")
output
n = 12345, x = 3.5

read_all_text(path) is the one-call shortcut for "give me this whole file as a string" — no fopen/close pair needed when a script only ever wants to read a file once, in full, such as loading a small config or notes file at startup. The example below writes a two-line file the normal way, then reads the whole thing back in one call:

n = fopen("notes.txt", "w")
write_line(n, "line one")
write_line(n, "line two")
close(n)
print(read_all_text("notes.txt"))
# line one

# line two

output
line one
line two

When a file holds a run of same-typed numbers rather than one fixed-width record, read_values/read_array read all of them in a single call instead of looping over read_double/read_int32/etc. one value at a time. read_values(f, type, n) reads n values of the given type from an already-open handle (useful mid-stream, alongside other reads on the same file); read_array(path, type=) skips fopen entirely and reads a whole file as one typed array in one call. The example below writes three 64-bit doubles, checks the file's size with file_size before opening anything, then reads the same three numbers back both ways to show they agree:

f = fopen("temps.bin", "wb")
write_double(f, 20.5)
write_double(f, 21.0)
write_double(f, 19.8)
close(f)

print(file_size("temps.bin"))            # 24 -- 3 doubles, 8 bytes each


g = fopen("temps.bin", "rb")
vals = read_values(g, "f64", 3)
close(g)
print(vals)                              # [20.5, 21, 19.8]


whole = read_array("temps.bin", type="f64")
print(whole)                             # [20.5, 21, 19.8]

output
24
[20.5, 21, 19.8]
[20.5, 21, 19.8]

A file of fixed-size records — logger output, an instrument's native save format, anything with a repeating struct layout — is read with read_struct/read_structs instead of unpacking each field by hand. fields is a list of (name, type) pairs describing one record's layout, in byte order; read_struct(f, fields) reads exactly one record and returns it as a record value with one field per name, while read_structs(f, fields, n) reads n of them into a Table, one column per field, which is the more useful shape once there are enough records to want to work on them column-wise. The example below writes two (f64, u16) records back to back, then reads first one and then both, column-wise:

f = fopen("records.bin", "wb")
write_double(f, 0.0)
write_uint16(f, 12)
write_double(f, 0.5)
write_uint16(f, 15)
close(f)

fields = [["t", "f64"], ["ch", "u16"]]

g = fopen("records.bin", "rb")
one = read_struct(g, fields)
close(g)
print(one.t)                             # 0

print(one.ch)                            # 12


h = fopen("records.bin", "rb")
tbl = read_structs(h, fields, 2)
close(h)
print(nrow(tbl))                         # 2

print(tbl.ch)                            # [12, 15]

output
0
12
2
[12, 15]

Interop with MATLAB doesn't require a MATLAB installation just to read data it produced: read_mat(path) reads a .mat file directly (via the matfile crate) and hands back every saved variable as a field on one record, named after the variable, so .mat files from a lab instrument or an existing MATLAB pipeline can be consumed without leaving Qu. The example below reads a .mat file containing a single saved variable named temperature and prints its values:

Not run by the build, and it cannot be: Qu reads MATLAB files but has no writer for them, so this example cannot create its own input the way the CSV one above does. It needs a .mat produced by MATLAB or SciPy.

vars = read_mat("measurements.mat")
print(vars.temperature)                  # [20.5, 21, 19.8]

argv() and getenv(name) are how a Qu script reads its own invocation context — command-line arguments and environment variables — the same information a shell script would get from $1/$2 and $MY_VAR. Every argument after a literal -- on the command line becomes one element of argv()'s list; getenv reads one named environment variable, coming back as none (Qu's absent-value marker, composing with ??) if it isn't set. The example below assumes the script was invoked as qu run analyse.qu -- data.csv 1000:

args = argv()
print(length(args))                      # 2 -- "data.csv" and "1000"

print(args)                              # ("data.csv", "1000")


level = getenv("QU_LOG") ?? "info"
print(level)
output
0
()
info

write_report(path) bundles everything a script has printed and plotted so far — printed output, tables, and any figures produced up to that point in execution — into one standalone HTML file with nothing linked from outside it, suitable for emailing or archiving without also shipping a folder of image files. The example below computes a small sum, prints it, then writes and confirms the report file:

x = 1:10
print("sum = " + str(sum(x)))
write_report("summary.html")
print(file_exists("summary.html"))       # true

output
sum = 55
true

Running another language inline is for the case where a library or routine simply has no Qu equivalent yet: python_exec/js_exec/matlab_exec all share one contract. code (string) is the guest-language source to run. vars= (optional, a Record/Dict) arrives as ordinary variables in the guest — built with Qu's {name=value, ...} record syntax, not JSON-style {"name": value}. An injected output-path variable (_qu_output_path for Python and JavaScript, qu_output_path for MATLAB — see the note above on why that one can't take a leading underscore) is where the guest writes a JSON result, and the call always returns a record of {stdout, stderr, success, exit_code, result}. The example below runs a one-line Python snippet with no injected variables, then a second Python snippet that receives x via vars= and returns a computed result, then the same pattern once in JavaScript:

py = python_exec("result = 1 + 1\nimport json\njson.dump(result, open(_qu_output_path, 'w'))")
print(py.result)                         # 2


py2 = python_exec("import json\nresult = x * 2\njson.dump(result, open(_qu_output_path, 'w'))", vars={x=21})
print(py2.result)                        # 42


js = js_exec("const fs = require('fs'); fs.writeFileSync(_qu_output_path, JSON.stringify(1 + 1));")
print(js.result)                         # 2

output
2
42
2

matlab_exec follows the exact same contract — matlab_exec(code, [vars=]), same {stdout, stderr, success, exit_code, result} return shape, code writing its result to the injected qu_output_path variable — but actually running it requires a working local MATLAB installation with a valid license, which this environment does not currently have (the license here has expired), so no runnable example is included for it. A failed run does not panic: success comes back false and stderr carries MATLAB's own error text (a license error, in this environment's case), the same "describe the failure, don't crash" contract every other guest-language failure follows.

More functions

FunctionSignatureDescription
savesave(path, name1, [name2, ...])Writes the named variables — path (string, destination file) plus one or more variable names (strings) given explicitly as extra arguments — to a JSON file, each tagged with its own type. Returns Nothing. Unlike save_all, save only ever writes the variables it is explicitly told to; there is no implicit "the whole workspace" behavior.
loadload(path)Restores every variable a save/save_all call wrote. path (string) is the file to read. Returns Nothing; each saved variable is written back into the current workspace under its original name, overwriting any existing variable of the same name (the same "load replaces" semantics MATLAB's own load has).
save_allsave_all(path)Saves literally every current binding — every user variable plus Qu's own built-in constants (pi, e, tau, none, the Qu* escape-character constants, ...) — to path (string). Returns Nothing. There is no "scratch" filtering; use save with an explicit name list to save only specific variables.
read_all_textread_all_text(path)Reads path (string) in full. Returns the whole file's content as one string. For splitting it into lines, open a handle with fopen and loop over read_line; for a file that isn't text, read it as raw bytes instead — read_bin(f, n) on a handle opened in binary mode, or read_array/mmap_read for typed/binary data.
read_valuesread_values(f, type, n)Reads n (number, count) typed values from an already-open handle. f (file handle, opened readable, positioned wherever the caller left it) is the source. type (string, one of f64/f32/i64/u64/i32/u32/i16/u16/i8/u8/byte, with the aliases double, float, int64, uint64, int32, uint32, int16, uint16 for the first eight respectively) is the element type. Returns a Vec of up to n numbers (fewer if the file runs out first). Useful mid-stream, interleaved with other reads on the same handle; for a whole file in one call, use read_array instead.
read_arrayread_array(path, [type="f64"], [endian="little"])Reads a whole binary file as one typed array, without an explicit fopen. path (string) is the file. type (string, optional, default "f64", same type names as read_values) is the element type. endian (string, optional, default "little", or "big") is the byte order. Returns a Vec of numbers — one per element in the file. Errors if the file's byte length isn't a whole multiple of the element width, rather than silently truncating a partial trailing element.
write_arraywrite_array(path, data, [type="f64"], [endian="little"])Writes a whole Vec/Mat/Signal (or a bare number/bool) to a binary file in one call, without an explicit fopen — the write-side counterpart read_array never had. path (string) is the destination, overwritten if it exists. data is the value to write; a Mat is flattened in its own column-major storage order (the same order A -> (r, c) fills), not row-major — reading it back with read_array and reshaping recovers the original matrix, since a flat binary file carries no shape of its own. type/endian as in read_array. Returns Nothing.
read_matread_mat(path)Reads a MATLAB .mat file (via the matfile crate) without needing a MATLAB installation. path (string) is the file. Returns a record with one field per saved variable, named after the variable, each holding that variable's data (a scalar, vector, or matrix depending on what was saved). MATLAB v7.3 files (HDF5 containers) are read through the built-in HDF5 reader: numeric and logical arrays, char row vectors and scalar structs come through; cell arrays, complex, sparse and N-d variables read as <unsupported ...> text.
read_npyread_npy(path)Reads a NumPy .npy file (format versions 1-3, little- or big-endian, C or Fortran order) without NumPy. path (string) is the file. Returns a number (0-d array), a vector (1-d) or a matrix (2-d); float16/32/64 and every int/uint width become numbers, bool becomes a number 0/1 (a bool for a 0-d array; so a bool vector written with write_npy comes back as a numeric 0/1 vector, not a bool vector), complex64/128 become complex values. An array of three or more dimensions is an error naming its shape. Object (pickled) arrays are refused -- nothing is ever unpickled -- as are string, datetime and structured dtypes; an int64/uint64 value above 2^53 is an error rather than a rounded number. *Added in v0.4.7*
write_npywrite_npy(path, x)Writes a number, bool, vector, matrix or complex form of those as a version-1 .npy file NumPy can load: float64, bool or complex128, C order, bit-exact (NaN, infinities and -0.0 survive). Returns Nothing. Refused under qu run --sandbox. *Added in v0.4.7*
read_npzread_npz(path)Reads a NumPy .npz archive (stored or DEFLATE members, CRC-checked) as a record with one field per array, named without the .npy suffix; each array is converted as read_npy does. *Added in v0.4.7*
write_npzwrite_npz(path, record)Writes the fields of a record as an uncompressed .npz (what numpy.savez makes); each field is stored as write_npy would store it. Refused under --sandbox. *Added in v0.4.7*
h5readh5read(path, dataset)Reads one dataset from an HDF5 file with a built-in pure-Rust reader (no HDF5 library needed). dataset is its path inside the file, e.g. "/results/trace". Returns a number, vector or matrix (integers and floats become numbers; HDF5 stores row-major, so a 2-d dataset keeps its shape), a string for a scalar string dataset, or a list of strings for a 1-d one. Contiguous, compact and chunked storage with the deflate, shuffle and fletcher32 filters are supported. Anything else -- compound, array or reference types, other filters (szip, LZF, Blosc, ...), dense link storage, external links -- is an error that names it; datasets over 2^27 elements are refused. *Added in v0.4.7*
h5infoh5info(path)Lists what is inside an HDF5 file. Returns a list of records, one per group, dataset or link, depth-first, each with path, kind ("group", "dataset", "datatype", "softlink", "externallink"), dtype (e.g. "float64", "int32", "string[8]") and shape (a vector; empty for a scalar). *Added in v0.4.7*
read_structread_struct(f, fields)Reads one fixed-width binary record from f (file handle, opened readable). fields (list of [name, type] pairs, e.g. [["t", "f64"], ["ch", "u16"]]) describes the record's layout in byte order, using the same type names as read_values. Returns a record with one field per entry in fields, or Nothing if fewer bytes remain than a full record needs.
read_structsread_structs(f, fields, n)Reads up to n (number) fixed-width binary records from f (file handle, opened readable), using the same fields layout read_struct takes. Returns a Table with one column per field (not one row-record per call) — the more useful shape once there are enough records to work on column-wise, stopping early (with however many complete records were read) if the file runs out.
file_sizefile_size(path)Reports a file's size without opening it. path (string) is the file to stat. Returns a number: the size in bytes on disk. Worth asking before you read something you did not write.
argvargv()Takes no arguments. Returns a list of strings: the command-line arguments given after a literal -- in the invocation (e.g. qu run analyse.qu -- data.csv 1000 gives ("data.csv", "1000")).
getenvgetenv(name)Reads one environment variable. name (string) is the variable's name. Returns its value as a string, or none if it isn't set — so getenv("HOME") ?? "/tmp" is the idiom for a default.
write_reportwrite_report(path)Writes a standalone HTML report to path (string) — every figure, table, and printed line the script has produced up to this point in execution, bundled into one file with nothing linked from outside it. Returns Nothing.
json2csvjson2csv(text)Converts text (string, JSON) to CSV text. Returns a string. Exactly csvify(parse_json(text)); accepts both jsonify's type-tagged JSON and the plain row-object JSON csv2json produces.
csv2jsoncsv2json(text)Converts text (string, CSV) to JSON. Returns a string: a plain JSON array of one flat {"col": value, ...} object per row — not jsonify's type-tagged envelope. The round trip through json2csv is lossy in one direction: CSV carries no type tags, so a value that comes back is a number or string by looking at it, not by a recorded type.
csv2xml, xml2csvcsv2xml(text) / xml2csv(text)The same conversion pair for XML, and exact compositions of the primitives above: csv2xml(text) is xmlify(parse_csv(text)); xml2csv(text) is csvify(parse_xml(text)). Both take/return a string.
json2xmljson2xml(text)Converts text (string, JSON) to XML text. Returns a string. Exactly xmlify(parse_json(text)).
xml2jsonxml2json(text)Converts text (string, XML in xmlify's own tag convention) to JSON. Returns a string: the same plain array-of-row-objects shape csv2json produces, not jsonify(parse_xml(text))'s type-tagged envelope. parse_xml (and so this function) only understands the specific element/attribute conventions xmlify itself produces — arbitrary hand-written XML with its own attributes is not a supported input and errors clearly rather than being guessed at.
python_exec, js_execpython_exec(code, [vars=]) / js_exec(code, [vars=])Runs code (string, source in the guest language) as a subprocess. vars (optional, a Record) is injected into the guest as ordinary variables. The guest writes its result as JSON to an injected output-path variable (_qu_output_path), which this call reads back. Returns a record {stdout, stderr, success, exit_code, result}: captured output streams, whether the process exited cleanly, its exit code, and the parsed JSON result. For a library with no Qu equivalent yet — and a dependency to be honest about in anything published using it.
matlab_execmatlab_exec(code, [vars=])The same contract as python_exec/js_exec, run through a local MATLAB installation instead: code's result is written to an injected qu_output_path variable (no leading underscore — MATLAB identifiers can't start with one) and the call returns the same {stdout, stderr, success, exit_code, result} record. Requires a working, licensed local MATLAB install; a failure (e.g. an expired license) does not panic — it comes back as success = false with MATLAB's own error text in stderr. Returns a Record with fields stdout (a Str), stderr (a Str), success (a Bool), exit_code (a Num) and result (whatever the parsed JSON held, or none if MATLAB wrote no result).