Qu

Quickstart

This chapter is the on-ramp: install Qu, run your first script, then one short, runnable example per domain — syntax, matrices, plotting, signal processing, data, machine learning, concurrency. Every snippet below has been run against the reference interpreter and its printed output is the actual output, not a mockup. For real depth on any one of these topics, this chapter hands off to Book 1, Book 2, and Book 3, plus the Standard Library Reference and the language specification — this walkthrough deliberately stays shallow so it stays fast.

1. Install and run

Each release carries a prebuilt qu command-line binary per platform (.zip, .tar.gz, and .deb on Linux) plus Qu Studio installers. Whether qu then works from an ordinary terminal depends on which package you installed:

Packagequ on your PATH afterwards?
Qu Studio Windows setup (Qu Studio_<version>_x64-setup.exe)Yes, from 0.4.6 (earlier setups claimed to but did not) — adds its install folder (which holds the bundled qu.exe) to *your user's* PATH; the uninstaller removes exactly that entry. Open a new terminal afterwards.
Qu Studio .msi, macOS .dmg, Linux .AppImage / .deb / .rpmNo — qu is bundled for Studio's own use only. Install the command-line build too, or add the folder yourself.
Command-line Windows setup (qu-<version>-windows-<arch>-setup.exe)Yes — see below; adds qu to your user PATH, no admin needed.
Command-line .zip / .tar.gzNo — unpack it and put the folder on PATH yourself.
Command-line .debYes — installs qu into /usr/bin.

Both Windows setups (from 0.4.6) have a Components page:

ComponentDefaultWhat it does
Add qu to the PATHonadds just the install folder to your user PATH (the rest of it is left exactly as it was); untick it to run qu by its full path or from the Start menu instead
Jupyter kerneloninstalls qu-jupyter.exe and registers the "Qu" kernel, so it appears in JupyterLab, Notebook and VS Code's Jupyter extension (Jupyter itself: pip install jupyterlab); the uninstaller unregisters it
Offline documentationoffthe whole reference and guides (~25 MB) in docs\ beside qu.exe; help(name) then names the local page
Editor pluginsper editorVS Code, Sublime Text and Notepad++ syntax and run commands -- each ticked only if that editor is installed
Start menu shortcutsona Qu folder (Qu Studio's own folder for the Studio setup) with Qu CLI (REPL), Start Jupyter (Qu) and Qu Documentation
Desktop shortcutsoffQu CLI (REPL) and Start Jupyter (Qu) on the desktop (Studio: alongside its own desktop shortcut)

For a silent install the same choices are switches: /NOPATH, /WITHDOCS, /NOJUPYTER, /NOPLUGINS, /NOSHORTCUTS, /DESKTOP (the last two are the command-line setup's; Studio follows its own shortcut options). The .zip and .tar.gz archives carry the same pieces -- qu-jupyter, docs/, editors/ -- for a manual setup: qu-jupyter install registers the kernel (--system for every user, qu-jupyter uninstall to remove it).

On Windows, from a release (releases after 0.4.4): download qu-<version>-windows-x86_64-setup.exe (or -arm64-setup.exe for Windows on ARM) and run it. It installs qu.exe for your user only — no administrator prompt — into %LOCALAPPDATA%\Programs\Qu and adds that folder to your user PATH, leaving the rest of the PATH exactly as it was. Open a new terminal and qu --version works. Switches:

qu-<version>-windows-x86_64-setup.exe /S                  silent, per-user
qu-<version>-windows-x86_64-setup.exe /S /D=C:\Tools\Qu   silent, chosen folder (/D= must be last)
qu-<version>-windows-x86_64-setup.exe /ALLUSERS           machine-wide (Program Files, system PATH; asks for admin)
qu-<version>-windows-x86_64-setup.exe /S /WITHDOCS /DESKTOP   silent, with offline docs and desktop shortcuts

To uninstall, use *Settings → Apps* ("Qu … (command line)"), or run uninstall.exe /S from the install folder. It removes the files it installed and its own PATH entry, and nothing else. The plain .zip is still there if you would rather put qu.exe somewhere yourself.

From source, on any platform: you need a working Rust toolchain (rustup.rs) and a clone of this repository:

git clone <this repository>
cd Qu
cargo build --manifest-path engine/Cargo.toml -p qu-cli

That builds a qu binary (engine/target/debug/qu, or use cargo run as shown below to build-and-run in one step). Two ways to use it:

Run a script. Save this as hello.qu:

print("Hello, Qu!")
output
Hello, Qu!
cargo run --manifest-path engine/Cargo.toml -p qu-cli -- run hello.qu
Hello, Qu!

Or start the REPL for interactive, line-at-a-time exploration:

cargo run --manifest-path engine/Cargo.toml -p qu-cli -- repl
qu> print(1 + 1)
2
qu>

A line that doesn't end in ; echoes its result automatically (ans = ... for a bare expression). :vars lists everything currently bound, :clear resets the session, :quit/:exit (or Ctrl+D) leaves — type :help inside the REPL for the full list. The rest of this chapter uses qu run <file> for every example; every one of them works pasted into the REPL too.

Or run a script, then keep going. Give repl a file and it runs the file first, then leaves you at the prompt with everything the script defined still in place (like python -i). With hello.qu extended to also set msg = "hi":

qu repl hello.qu
Hello, Qu!
qu> print(msg)
hi
qu>

Top-level variables and function definitions carry over. If the script fails (a runtime error, or a file that cannot be read), qu repl prints the error and exits with status 1 rather than giving you a prompt. This is the quickest way to load your data and setup once, then try things against it.

qu test -- run your tests (*new in v0.4.7*)

qu test                       # ./tests/**/*.qu plus test_*.qu / *_test.qu here
qu test path/to/dir file.qu   # explicit files; directories are searched recursively
qu test --filter sum          # only test functions whose name contains "sum"
qu test --fail-fast           # stop at the first failure
qu test --json                # one JSON document on stdout, for CI tooling
qu test --timeout 10          # kill a test running longer than 10 s (default 60; 0 = no limit)

A test is a top-level function with no parameters whose name starts with test_. It passes if it returns and fails if it raises an error. Qu has no assert builtin; the idiom is error(...):

function test_sum()
  if sum([1, 2, 3]) != 6
    error("sum([1,2,3]) was not 6")
  end if
end function

Each test runs in its own child qu process with a fresh interpreter (the file's top-level code is re-run for each test), so nothing leaks from one test or file into the next, and a test that hangs is killed alone and reported FAILED (timeout) while the run continues. With --timeout 0 the tests of a file share one in-process interpreter instead: top-level code runs once (fixtures, helpers), then each test_ function in source order. A file that defines no test_ function is run as a script and passes if it finishes without an error.

Every test prints PASS/FAIL with file:line and its name and time; a failure also shows the error, where it happened (at file:LINE in test_x() and the call chain) and whatever the test printed. The last line is test result: N passed, M failed. The exit status is 0 if everything passed, 1 if anything failed and 2 if no tests were found.

qu fmt -- tidy source files (*new in v0.4.7*)

qu fmt                  # reformat every .qu under the current directory, in place
qu fmt src/ tool.qu     # specific files or directories
qu fmt --check          # change nothing; list files that would change; exit 1 if any
qu fmt --stdin          # read source on stdin, write the formatted text to stdout

The formatter is deliberately conservative. It works from the token stream, so comments, strings, raw strings and {...} interpolations are copied byte for byte, and it only changes whitespace:

Line endings are kept per line (a \r\n file stays \r\n). Lines inside a multi-line string literal are never touched. qu fmt is idempotent and checks its own output (same tokens, only whitespace changed) before it writes a file, refusing with exit status 2 if that ever fails.

Editor plugins -- qu editors (*new in v0.4.9*)

Highlighting, "run this file" and live syntax errors for Qu are available for VS Code, VSCodium, Cursor, Windsurf, Notepad++, Sublime Text, Vim and Neovim, and the Qu kernel for Jupyter. The qu binary carries the plugin files and installs them itself; nothing else is needed.

qu editors detect                 # which editors qu finds, how, and where each plugin goes
qu editors install                # install into every detected editor
qu editors install --editor vscode,nvim --dry-run   # only these; print, change nothing
qu editors status                 # installed? version? is qu itself on PATH?
qu editors check                  # validate the plugin files; exit 0 only if healthy
qu editors uninstall              # remove exactly what install wrote

detect looks in the Windows registry, PATH and the usual folders (and finds portable copies by their data/, Data/ or doLocalConf.xml folder), and qu editors detect vscode exits 0 if VS Code is found and 1 if not, so a script can branch on it. install --editor all writes to every default location even for editors that are not installed. Files you edited are saved as .bak before they are replaced, and --dry-run prints what would happen. Restart the editor afterwards.

The editor extension runs qu, so it must find it: the VS Code setting qu.executablePath (default qu) is a bare name looked up on PATH or a full path. qu editors status says whether qu is on PATH and prints the path to use when it is not. In VS Code, Qu: Run File (Ctrl+Alt+R) runs the file and turns the at file.qu:LINE in f() lines of a runtime error into entries in the Problems panel. Notebooks in VS Code also need Microsoft's Jupyter extension; status prints the command (code --install-extension ms-toolsai.jupyter) but never runs it. qu editors install --editor jupyter registers the Qu kernelspec using the qu-jupyter binary that ships next to qu, and check verifies that kernel can start. JetBrains, Zed, Helix and Emacs have no plugin yet (see editors/README.md); those with an LSP client can still use the language server described next.

Language server -- qu lsp (*new in v0.4.12*)

qu lsp is a Language Server Protocol server. An editor starts it, sends it the text you are editing, and gets back what it needs to show:

The VS Code extension (qu editors install) starts it for you. In any other editor with an LSP client, tell the client to run this command for *.qu files:

qu lsp          # speaks LSP on stdin/stdout; not meant to be run by hand

For Neovim that is, in init.lua:

vim.api.nvim_create_autocmd('FileType', {
  pattern = 'qu',
  callback = function(args)
    vim.lsp.start({
      name = 'qu-lsp',
      cmd = { 'qu', 'lsp' },
      root_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(args.buf)),
    })
  end,
})

editors/README.md has the same for Helix, Sublime Text (LSP package), Kate and JetBrains IDEs (LSP4IJ), and says which were tested: the server and the VS Code extension are, but the configurations for the other editors, including the Neovim one above, have not been run inside the editor yet. The server works on one file at a time (nothing is resolved across imports), reports the parser's first error rather than all of them, and does not rename, find references or format (qu fmt formats).

qu run flags for running untrusted or unattended scripts

qu run <file.qu> takes a few flags for running a script you don't fully trust or don't want to babysit — useful for a script from someone else, a CI job, or anything you want a hard ceiling on:

  qu: killed: exceeded --max-time 30s (ran 30.4s)

  qu: killed: exceeded --max-memory 512MB (used ~520MB)

Enforcement is a background thread polling wall-clock time and process memory every 25ms, not a hard allocator-level ceiling or a cooperative check inside the interpreter's own loop — chosen specifically because it also catches a single slow *native* operation (a huge matrix op, say), not just a runaway Qu-level loop. That polling interval is the real precision bound: a run can overshoot either limit by up to ~25ms (and, for memory, by however much one single large allocation adds between two polls) before getting killed.

  qu profile
    wall-clock time : 0.842s
    peak RSS        : 61 MB

    function                       calls   total time   time %
    train_epoch                       50      0.701s     83.3%
    forward                          500      0.098s     11.6%
    load_batch                        50      0.015s      1.8%

Sandbox/profiling as part of the program, not just CLI flags

--sandbox/--profile above apply to the whole process, set once before the script starts. sandbox_mode(on), profiling_mode(on), and profile_stats() are the same two underlying controls exposed as builtins, so a script can turn either on for just the section it cares about instead of all-or-nothing for the whole run:

function load_and_process(path)
    profiling_mode(true)
    data = read_csv(path, headers=true)
    result = data.sort_by("value")
    profiling_mode(false)
    print(profile_stats())     # a real Table: function / calls / seconds


    sandbox_mode(true)
    try
        touch("audit.log")     # denied -- sandboxed for this section only

    catch err
        print("blocked: {err.message}")
    end
    sandbox_mode(false)

    return result
end function

profile_stats() returns a Table the script decides what to do with — print it, filter it, save it — rather than the CLI's external report string. --max-time/--max-memory have no in-script equivalent yet: they're enforced by an external OS-level watchdog thread in qu-cli started before the interpreter runs at all, so an in-script max_time(...)/max_memory(...) would need the watchdog to poll a value the interpreter can update mid-run rather than a fixed constant set at startup — a real design question, not yet built (see BACKLOG.md).

2. Core syntax in one script

x = 5
y = 2.5
print("x + y = {x + y}")

for k = 1 to 5
    print("k = {k}")
end for

n = 0
total = 0
while n < 5
    total = total + n
    n = n + 1
end while
print("total = {total}")

if total > 5 then
    print("total is big")
else
    print("total is small")
end if

square(v) := v ^ 2
print("square(6) = {square(6)}")

function greet(who)
    return "hello, " + who
end function
print(greet("Qu"))

r = 0 to 10 step 2
print("r = {r}")
output
x + y = 7.5
k = 1
k = 2
k = 3
k = 4
k = 5
total = 10
total is big
square(6) = 36
hello, Qu
r = [0, 2, 4, 6, 8, 10]
x + y = 7.5
k = 1
k = 2
k = 3
k = 4
k = 5
total = 10
total is big
square(6) = 36
hello, Qu
r = [0, 2, 4, 6, 8, 10]

Notes on what just happened:

Book 1 goes much deeper here: type explicit mode, unit literals (5 kHz), complex numbers, logical/mask indexing, and save/load.

3. Vectors and matrices

a = [1, 2, 3]
b = [10, 20, 30]
print("a + b = {a + b}")
print("a .* b = {a .* b}")

# zero-based indexing -- a MATLAB user's #1 surprise

print("a[0] = {a[0]}")

M = [1, 2; 3, 4]
print("M = {M}")
print("M[0,1] = {M[0,1]}")
print("M*M = {M*M}")

# solve A*x = b for x, using left division

A = [4, 7; 2, 6]
rhs = [1; 1]
x = A \ rhs
print("x = {x}")
print("A*x = {A * x}")
output
a + b = [11, 22, 33]
a .* b = [10, 40, 90]
a[0] = 1
M = [1, 2; 3, 4]
M[0,1] = 2
M*M = [7, 10; 15, 22]
x = [-0.1; 0.2]
A*x = [1; 1]
a + b = [11, 22, 33]
a .* b = [10, 40, 90]
a[0] = 1
M = [1, 2; 3, 4]
M[0,1] = 2
M*M = [7, 10; 15, 22]
x = [-0.1; 0.2]
A*x = [1; 1]

The one fact worth memorizing before anything else: A[0,1] reads row 0, column 1 — zero-based, like Python/NumPy, not one-based like MATLAB. The other MATLAB-familiar convention that *does* carry over: bare * is matrix multiplication at a 2-D boundary (not elementwise — use .* for that), and A \ b solves A*x = b exactly like MATLAB's own backslash. Book 1 §6–7 covers orientation, transpose spellings, and logical indexing; Book 2 §2 covers the rest of the linear-algebra floor (inv, det, svd, qr, lu, eig, chol).

4. Plotting

x = 0 to 10 step 0.1
y = sin(x)
plot(x, y)
xlabel("x")
ylabel("sin(x)")
title("First plot")
grid on
savefig("quickstart_plot.svg")
print("saved quickstart_plot.svg")
output
· plot: figure 1 (101 points)
· savefig quickstart_plot.svg
  note: this figure uses screen styling and may not hold up in print -- call theme("publication") before saving for a paper (said once per session)
  note: fonts render using whatever is installed on the viewer's machine (none are embedded) -- pass embed_fonts=true (fontfamily preset only) or export .tikz for guaranteed appearance
saved quickstart_plot.svg
-1.0 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1.0 0 1 2 3 4 5 6 7 8 9 10 First plot x sin(x)
saved quickstart_plot.svg

savefig picks the output format from the file extension. .svg and .pdf are both real, implemented vector backends today (.html embeds the same SVG in a minimal page, .tikz/.tex emits LaTeX source) — they share one draw-command list, so they never visually disagree with each other. Full-figure .png is the one format not implemented yet (it needs a real rasterizer); raster .png export for actual image data (save_image) is a separate, already-working feature. See Plotting for the full chart-type list (stem/scatter/bar/hist/heatmap/spectrogram/... ) and subplot layout.

5. Signal processing: filtering a noisy signal

fs = 1000
n = 0 to 999
t = n / fs
clean = sin(2 * pi * 5 * t)
noisy = clean + sin(2 * pi * 120 * t)

lp = butter(4, "low", 30, fs)
filtered = filtfilt(lp, noisy)

err_noisy = rms(noisy - clean)
err_filtered = rms(filtered - clean)
print("rms error before filtering = {err_noisy:.4f}")
print("rms error after filtering  = {err_filtered:.4f}")
output
rms error before filtering = 0.7071
rms error after filtering  = 0.0350
rms error before filtering = 0.7071
rms error after filtering  = 0.0266

butter(order, kind, cutoff, fs) designs a digital Butterworth filter as a cascade of second-order sections; filtfilt runs it forward then backward for zero phase distortion (the right choice for offline analysis). sosfilt is the single-pass, causal alternative, and filter_init/ filter_next thread filter state one sample at a time for streaming use. See Book 2 §1 for FFT, spectrograms, EMD/VMD, and the rest of the DSP toolbox.

6. Working with data

Save this as sensors.csv:

temp,humidity,pressure,label
21.5,45.2,1012.1,ok
22.1,46.0,1011.8,ok
35.0,20.1,1009.5,warn
21.8,45.5,1012.0,ok
36.2,19.5,1008.9,warn
22.0,45.8,1012.3,ok
34.5,21.0,1009.8,warn
21.6,45.1,1012.2,ok
35.8,20.4,1009.1,warn
22.3,46.2,1011.9,ok

The block below writes that same file before reading it, so the page you are looking at really did run this. Without it the example opens a file the build does not have, fails, and is dropped from the page — leaving a quickstart whose output a newcomer cannot see.

write_csv(table(
    temp     = [21.5, 22.1, 35.0, 21.8, 36.2, 22.0, 34.5, 21.6, 35.8, 22.3],
    humidity = [45.2, 46.0, 20.1, 45.5, 19.5, 45.8, 21.0, 45.1, 20.4, 46.2],
    pressure = [1012.1, 1011.8, 1009.5, 1012.0, 1008.9, 1012.3, 1009.8, 1012.2, 1009.1, 1011.9],
    label    = ["ok", "ok", "warn", "ok", "warn", "ok", "warn", "ok", "warn", "ok"]
), "sensors.csv")

df = read_csv("sensors.csv")
print("rows = {nrow(df)}, cols = {ncol(df)}")
print(head(df, 3))

numeric = drop(df, "label")
c = corrmat(numeric)
print(c.matrix)
c.plot()
savefig("quickstart_corrmat.svg")

scaled_temp = standardize(df.temp)
print("standardized temp[0] = {scaled_temp[0]:.4f}")
print("mean(standardized) = {mean(scaled_temp):.4f}, std(standardized) = {std(scaled_temp):.4f}")
output
rows = 10, cols = 4
temp  humidity  pressure  label
----  --------  --------  -----
21.5      45.2    1012.1  ok   
22.1        46    1011.8  ok   
  35      20.1    1009.5  warn 
[1, -0.997357, -0.991317; -0.997357, 1, 0.983511; -0.991317, 0.983511, 1]
· savefig quickstart_corrmat.svg
  note: fonts render using whatever is installed on the viewer's machine (none are embedded) -- pass embed_fonts=true (fontfamily preset only) or export .tikz for guaranteed appearance
standardized temp[0] = -0.8275
mean(standardized) = -0.0000, std(standardized) = 1.0000
temp, temp: 1 1 temp, humidity: -0.997 -0.997 temp, pressure: -0.991 -0.991 humidity, temp: -0.997 -0.997 humidity, humidity: 1 1 humidity, pressure: 0.984 0.984 pressure, temp: -0.991 -0.991 pressure, humidity: 0.984 0.984 pressure, pressure: 1 1 temp humidity pressure temp humidity pressure First plot
rows = 10, cols = 4
table(3 rows x 4 cols: temp, humidity, pressure, label)
[1, -0.997357, -0.991317; -0.997357, 1, 0.983511; -0.991317, 0.983511, 1]
standardized temp[0] = -0.8275
mean(standardized) = -0.0000, std(standardized) = 1.0000

A Table prints as a compact one-line summary rather than a full grid — use print(select(df, "temp", "humidity")) for a subset, or print(describe(df)) for pandas-style summary statistics, when you want to actually see values. drop(df, "col", ...) returns a new table with those columns removed (Qu tables are immutable, like everything else); corrmat(df) returns a model(...) with a .matrix field, and doubles as a plottable heatmap via .plot(). standardize/normalize/ robust_scale/quantile_normalize are one-shot scalers; fit_scaler(X, method=...) plus .transform/.inverse_transform is the fit-once/ reuse-on-new-data version for a real train/test split. See Collections, Strings & Data Frames and File I/O for the rest of the Table API.

7. Machine learning: train, predict, check accuracy

n_per_class = 60
c0x = normal(0, 0.6, n_per_class, seed=1)
c0y = normal(0, 0.6, n_per_class, seed=2)
c1x = normal(4, 0.6, n_per_class, seed=3)
c1y = normal(4, 0.6, n_per_class, seed=4)

Xc0 = hstack(reshape(c0x, n_per_class, 1), reshape(c0y, n_per_class, 1))
Xc1 = hstack(reshape(c1x, n_per_class, 1), reshape(c1y, n_per_class, 1))
Xc = vstack(Xc0, Xc1)             # (120, 2)


n = 2 * n_per_class
idx = 0 to n - 1
y = floor(idx / n_per_class)      # 0 for the first 60 rows, 1 for the last 60


function one_hot(labels, rows, k)
    m = zeros(rows, k)
    for i = 0 to rows - 1
        m[i, labels[i]] = 1
    end for
    return m
end function

Y = one_hot(y, n, 2)

net = mlp_classifier(2, [8], 2, seed=42)
trained = net.fit(Xc, Y, epochs=200, lr=0.1, loss="cross_entropy")

function accuracy(model, X, Ytrue, rows)
    logits = model.predict(X)
    correct = 0
    for i = 0 to rows - 1
        if argmax(logits[i, :]) == argmax(Ytrue[i, :]) then
            correct = correct + 1
        end if
    end for
    return correct / rows
end function

acc = accuracy(trained, Xc, Y, n)
print("training accuracy = {acc:.4f}")
output
training accuracy = 1.0000
training accuracy = 1.0000

mlp_classifier(in_dim, hidden_dims, n_classes, seed=]) builds a dense+ReLU stack ending in raw ("softmax-ready") logits; .fit(X, Y, epochs=, lr=, loss="cross_entropy") trains it with one-hot Y, and .predict(X) runs inference (dropout off, untracked). Two classes drawn from well-separated Gaussian blobs is an easy problem — 100% training accuracy just confirms the whole pipeline actually works end to end, not that the model is magic. For classical (non-neural) ML with the same fit/predict/score protocol, see kmeans_model, ols_model, tree_model, knn_model, and the rest of [Statistics & Machine Learning; Book 3 §2 covers the model-zoo and pipeline story in more depth.

8. Concurrency: spawn and join

heavy(n) := n * n

w = spawn("heavy", 7)
result = join(w)
print("result = {result}")
output
result = 49
result = 49

spawn("fn_name", args...) runs a user-defined function on its own OS thread (only a function you defined can be spawned, never a builtin); join(w) blocks for its result. parallel for and pmap are the shared-nothing loop/pipeline-stage equivalents for "apply this to every element"; mutex/semaphore opt in to real shared state when you need it. See Book 3 §4 and §5 for timers (every/after), parallel for, and real serial-port I/O.

Opening .qu files

A .qu file is a "Qu script". The installers register the type so that the usual desktop gestures work:

Making Qu Studio the default. The installers never take over a .qu association another program already holds. Windows protects that choice (it is signed per user, and no installer may overwrite it), so if .qu already opens elsewhere, do it once yourself: right-click a .qu file, *Open with > Choose another app > Qu Studio > Always*. If nothing handled .qu before, the Studio installer makes itself the default.

Double-click never runs a script. A script can do whatever you can, so opening a file only opens it. To run one, use *Run with Qu* from the right-click menu (Windows command-line install), Qu Studio's run command, or qu run file.qu.

Qu Studio: opening files

Qu Studio opens files three ways, and every way adds a tab (or focuses the tab that already holds the file) -- opening never replaces what you are editing.

The SVG viewer draws the file with scripts, foreignObject and event handlers removed (an SVG can never run code in Studio). Scroll to zoom, drag to pan, Fit (key 0) fits the window, 100% (key 1) shows actual size, and View source opens the SVG as text in the editor.

The PDF viewer uses the web view's built-in PDF support (Windows and macOS). On Linux the web view has none, so the pane shows a notice with an Open in system viewer button instead. Files over 200 MB (viewers) or 50 MB (text) are refused with a message.

PDF page rendering needs PDFium

Everything in import pdf that reads or edits a document's structure, text, pages, bookmarks, annotations and attachments is built in. pdf.render, which turns a page into an image, is the one exception: it uses Google's PDFium, which Qu loads when you first call it rather than shipping it.

1. Download the build for your platform from github.com/bblanchon/pdfium-binaries (pdfium-win-x64.tgz, pdfium-linux-x64.tgz, pdfium-mac-arm64.tgz, ... -- the plain ones, not the v8 ones). 2. Unpack it and copy bin/pdfium.dll (Windows), lib/libpdfium.so (Linux) or lib/libpdfium.dylib (macOS) next to the qu program -- for the Windows installers that is the install folder, beside qu.exe. Or set the QU_PDFIUM environment variable to the file or its folder. 3. import pdf and img = pdf.render("report.pdf", page=1, dpi=120).

Without the library the call stops with an error that says exactly this. Nothing else in import pdf needs it.

Annotations are editable from Qu itself: pdf.add_annotation takes type= ("Text" for a note, "Square", "Highlight", "Underline", "StrikeOut", "Squiggly", ...), rect=, text= and an optional color=[r, g, b]; pdf.annotations lists them and pdf.remove_annotation removes one. They return the new file as bytes, so save with bytes_write(path, ...). Pages are counted from 1.

Where to go from here

Text with braces, quotes and backslashes

An ordinary string treats {...} as interpolation, so JSON, CSS and JavaScript need one of these spellings:

You wantWriteResult
a literal { or }"config={{a:1}}"config={a:1}
a backslash with no escape processingr"C:\temp\new"C:\temp\new
text with braces AND double quotes (JSON, CSS)r"""[{"a":1},{"a":2}]"""the text exactly as written
a double quote inside an ordinary string"say \"hi\""say "hi"

r"..." ends at the first "; r"""...""" (new in v0.4.8) ends at the next three quotes, so it can hold quotes, braces and backslashes. So parse_json(r"""[{"a":1}]""") works without escaping anything. (r'...' is not a raw string: after a variable r, ' is the transpose.) In a run of four or more quotes the closing three are the last three, as in Python, so r"""say "hi"""" ends in a literal ". A string that is never closed (either form) is an error at the line and column where it opened, not a silent swallow of the rest of the file.

Where did my script fail?

A runtime error from qu run names the file and line, the function it was in and every call up to the top level:

qu: runtime error: cannot apply a numeric operation to string

  at nested.qu:2 in inner()
  called from nested.qu:6 in outer()
  called from nested.qu:8 (top level)

Inside catch e, e.message stays the bare message; e.file is the script, e.line the failing line, e.stack the function chain and e.trace the multi-line text above.

qu run --watch script.qu runs the script again every time you save it (a run still going is stopped first; only the script file itself is watched, not the files it imports). qu run --dry-run script.qu runs it but skips every call that writes or deletes files (write_text, write_csv, remove_file, ...) and prints dry-run: skipped write_text(path) on stderr for each, so a script that publishes to a share can be rehearsed first. --dry-run does not stop processes or network calls; use --sandbox for those.

Lists

xs[i] = value replaces one element of a list. append(list, other) adds other as ONE element (nesting); extend(list, other) adds its elements (concatenation). for row in table walks a table's rows as records.

Scientific notation and formatted numbers

You wantWriteResult
typeset, for titles and labelssci(1.2345e-45) or "{x:.2sci}"1.23 × 10⁻⁴⁵
the same for LaTeX / MathJaxsci(x, 3, style="tex") or "{x:.2tex}"1.23 \times 10^{-45}
C's %e"{x:.3e}" or sprintf("%.3e", x)1.235e+05
C's %g (significant digits)"{x:.3g}" or sprintf("%.3g", x)1.23e-05
padded, aligned columnssprintf("%-10s %8.3f", name, v)alpha 3.142

sprintf(fmt, ...) returns the string and printf(fmt, ...) prints it with no newline added (write \n yourself), the way C does. Conversions: %d %i %u %f %e %E %g %G %s %c %x %X %o %% with the flags - + space 0 #, a width and a .precision. sci(x) counts *significant* digits (3 gives 1.23), while {x:.2sci} counts digits after the point, like {x:.2e}.