Introduction
This manual teaches you to write living documents: reports, calculations and notes whose numbers compute themselves, and that use the data of other documents instead of copying it.
Three pieces work together:
| Piece | What it is |
|---|---|
| Stilo | The editor. It edits a folder of documents in your browser, the way Word edits .docx files, and renders them from the command line. |
| Texl | The document format. A Texl document is ordinary text with formulas between <% and %>, which are replaced by their values. |
| Swan | The small language inside the formulas: numbers, text, lists, functions. |
A document can hold a calculation, and the text follows when an input changes:
<!--{ bek4 : markdown }-->
# Beam check
<% L = 6, q = 12.5 %>
Span <% L %> m, load <% q %> kN/m.
<!--{ mom3 : markdown }-->
Midspan moment: **<% q * L ^ 2 / 8 %> kNm**
In Stilo, this file is two lines of a sheet:
1 Beam check
Span 6 m, load 12.5 kN/m.
2 Midspan moment: 56.25 kNm
A document can also import other documents, so a package can use the data that a library of materials or a colleague's calculation provides.
How to read this manual
- New here? Start with Getting started: install Stilo and open the sample documents.
- Using Stilo teaches the editor, one topic per page:
read it with Stilo open beside it, and try each step. It also covers the
stilocommand and the document format. - Writing documents with Texl explains how formulas fill a document: names, conditions, lists, imports.
- The Swan language describes the language of formulas, and the built-in reference lists every function.
Stilo, Texl and Swan are free software, released under the MIT license. Programmers who want to embed Texl in their own programs, or change Stilo, find the developer documentation in the repositories on GitHub.
Getting started
This page installs Stilo, opens the tutorial and the sample documents in the editor, and renders a document from the command line.
Install
You need uv, which also installs Python 3.11
or later if you do not have it. Install the stilo command from PyPI:
uv tool install stilo-cli
If uv says that its folder is not on your path, run uv tool update-shell
and open a new terminal. With Python 3.11 or later already installed,
pip install stilo-cli works too. Check it:
stilo --help
usage: stilo [-h] {init,pack,render,serve,tutor} ...
Edit and render a folder of linked Texl documents.
To update Stilo later, run uv tool upgrade stilo-cli.
Take the tutorial
The quickest way to learn Stilo is its tutorial: short lessons in the editor, which you follow by doing.
stilo tutor
Your browser opens the tutorial's index. Start with lesson 1; the twelve
lessons take 30 to 45 minutes in all. Press Ctrl+C in the terminal to stop;
the next stilo tutor opens your work as you left it. More in
stilo tutor.
Open the sample documents
Stilo's source code comes with a folder of sample documents, examples.
Get it with git (or download the code as a ZIP file
from https://github.com/onlabsorg/stilo) and serve it:
git clone https://github.com/onlabsorg/stilo.git
cd stilo
stilo serve examples
Stilo: serving /home/ada/stilo/examples at http://127.0.0.1:8010/
Open http://127.0.0.1:8010/packages/beam/beam-check.texl in your browser. You see the design report of a steel floor beam, on numbered lines: text, tables of design data and results, conclusions and recommendations. The report takes its figures from two other documents of the same package, the basis of design (span, loads, materials) and the calculation note (equations, checks, a bending-moment diagram). The navigation pane on the left lists the files of the folder.
Try it:
- Click the link Basis of design in the introduction.
- Press ↓ until line 4, 2 Structure, is selected, and press Enter to edit it. (Line 1 is hidden: it imports the Stilo library.)
- Change the span,
L = 6, toL = 7. - Press Ctrl+Enter (⌘+Enter on a Mac), then Ctrl+S to save the document.
- Press the browser's back button to return to the report. Its design data, results and conclusions follow the new span: the IPE 300 is now at 93 % of its deflection limit, and the report no longer recommends the lighter IPE 270.
Press Ctrl+C in the terminal to stop the server.
Render a document
stilo render prints a document with its formulas computed:
stilo render examples/packages/beam/beam-check.texl
The output is the document's text, with every <% %> formula replaced by
its value. The report imports the basis of design and the calculation note,
which import the steel sections and the Stilo library from the
references of their package,
examples/packages/beam/references; stilo render follows those imports
too.
Next steps
- Take the tutorial: stilo tutor.
- Learn the editor: The web editor.
- Serve your own folder: stilo serve.
- Learn to write formulas: Writing documents with Texl and The Swan language.
The web editor
The web editor is where you write documents. stilo serve starts it on a
folder; open the address it prints in your browser.
This part of the manual teaches the editor, one topic per page. It is best read with Stilo open beside it, so you can try each step:
-
Serve the sample documents, as in Getting started:
stilo serve examples -
Open http://127.0.0.1:8010/packages/beam/beam-check.texl, or press Alt+N to create a practice document of your own.
On a Mac, use ⌘ where this manual says Ctrl, and ⌥ (Option) for Alt.
The window
┌──────────────────────────────────────────────────────────────────┐
│ ☰ Stilo beam-check • [Errors] [Comments] [⋮] │ top bar
├────────────┬────────────────────────────────────────┬────────────┤
│ / │ 1 │ Beam check │ Commands │
│ ▾ library │ 2 │ Input │ File │
│ steel │ │ - Span: 6 m │ Save │
│ ▾ packages │ 3 │ Design load 2 │ … │
│ ▾ beam │ 4 │ │ │
│ beam-… │ 5 │ │ │
│ │ │ │
│ navigation │ the sheet │ right pane │
└────────────┴────────────────────────────────────────┴────────────┘
| Part | What it shows |
|---|---|
| Top bar | The name of the open document, with a dot (•) while it has unsaved changes, and a message after saving. The buttons on the right open the errors, with their number, the comments and the commands (⋮). |
| Navigation pane | The documents and other files of the folder. Click a document to open it. Double-click a folder to show only that folder; the arrow at the top goes back up. Ctrl+B shows or hides the pane. |
| The sheet | The open document, as numbered lines on paper. Each line is a cell. The left margin shows the line number and the cell's type; the right margin shows how many comments and errors a cell has. |
| Right pane | The commands, with their shortcuts (F1), the comments of a line (Alt+C), or the errors of the document. |
Your first steps
- Press ↓ to select the next line, and ↑ to go back. You can also click a line.
- Press Enter on a line: you see the text it is written with.
- Press Escape to leave the line without changes.
The next pages go further:
- Lines and cells: edit, insert, move and delete lines.
- Writing text: rich text, Markdown and equations.
- Formulas: values that compute themselves.
- Errors: what a wrong formula shows, and how to find the cause.
- Cell types: rich text, Markdown, text, formulas, tables, data tables and charts.
- Comments: notes on a line.
- Linking documents: use the values of another document, and link to documents, images and other files.
- Packages and references: a folder of documents that belong together, with the references they use, and packed packages.
- Files and folders: save, create, upload, rename, move, download and delete.
- Keyboard shortcuts: all of them, on one page.
Lines and cells
A document is a stack of cells, one per line, like the rows of a spreadsheet. A cell can hold one sentence or a whole page: its line grows to fit it. The number in the left margin is the line number; people talk about "line 3".
Edit a line
- Select a line and press Enter (or double-click it, or press F2).
- Change a word.
- Press Ctrl+Enter to keep your change, or Escape to throw it away. A click on another line keeps it too, as in Excel.
While you edit, Enter starts a new line of text inside the same cell.
Write on an empty line
The numbered lines below the document are empty. Select one, press Enter, write something and press Ctrl+Enter: it becomes part of the document, on that line. The empty lines above it become part of the document too, so your text stays where you wrote it.
Insert, move, delete
| Keys | What they do |
|---|---|
| Alt+Enter | Insert an empty line below |
| Alt+Shift+Enter | Insert an empty line above |
| Alt+↑, Alt+↓ | Move the selected lines |
| Delete, Backspace | Delete the selected lines |
| Shift+↑, Shift+↓, Shift+click | Select several lines |
| Ctrl+C, Ctrl+X, Ctrl+V | Copy, cut and paste lines |
| Ctrl+Z, Ctrl+Shift+Z | Undo and redo |
Try it: select a line, move it up with Alt+↑, then press Ctrl+Z to put it back.
- With several lines selected, the commands work on all of them.
- Pasted lines replace the selected ones, as in a spreadsheet. Copied lines keep their type, and their comments.
- A move or a paste that would make a formula run into another line does nothing, and a message says why.
- Ctrl+Z undoes changes to the lines: edits, inserts, deletes, moves, pastes and type changes. While you edit a line, Ctrl+Z undoes your typing in it.
Hide lines
Lines can be hidden, as rows in Excel: a line with intermediate steps, or one that the reader does not need. A hidden line stays in the document and still computes; it is only out of sight.
- Select the lines to hide.
- Open the commands pane (F1) and choose Hide the selected cells.
The line numbers skip the hidden lines, and a double rule shows where they are. The arrow keys pass over them.
| Command | What it does |
|---|---|
| Hide the selected cells | Hides the selected lines |
| Unhide the cells in the selection | Shows again the hidden lines between the selected ones: select the lines above and below the double rule |
| Show or hide the hidden cells | Shows all hidden lines, greyed out, or hides them again. This is a view setting; it is not saved |
The commands have no keys yet. Going to a hidden line from the Errors or Comments pane shows the hidden lines.
Line numbers move
Line numbers are positions, as in a spreadsheet: when you insert a line, the numbers of the lines below it change. Each cell also has a name in the file, which never changes, but the editor does not show it (see The document format).
Writing text
New lines are rich text: you write and format text as in Word. Bold is bold and a heading is a heading while you type, in the same look as the finished document.
Rich text
Select a line and press Enter. A toolbar appears above the line:
| Toolbar | What it does |
|---|---|
| Style menu | Normal text, Heading 1 to 3, or Code |
| B, I, U, S | Bold, italic, underline, strikethrough |
| x2, x2 | Subscript and superscript, as in fck or m2 |
| Lists and quote | A bulleted list, a numbered list, an indented quote |
| Link | A link on the selected text |
| ƒ | A formula |
| ∑ | An equation |
| Comment | A comment on the line |
Word's keys work too:
| Keys | What they do |
|---|---|
| Ctrl+B, Ctrl+I, Ctrl+U | Bold, italic, underline |
| Ctrl+=, Ctrl+Shift+= | Subscript, superscript |
| Ctrl+Alt+1, 2, 3 | Heading 1, 2, 3; Ctrl+Alt+0 for normal text |
| Ctrl+K | Add or change a link |
| Ctrl+E | Insert a formula |
| Tab, Shift+Tab | Indent or outdent a list item |
| Shift+Enter | A line break inside a paragraph |
Some characters typed at the start of a paragraph format it: # makes a
heading (## a smaller one), - a bulleted list, 1. a numbered list,
> a quote.
While you edit, the arrow keys move inside the line, and Enter starts a new paragraph in the same line. Ctrl+Enter keeps your changes and Escape throws them away, as in every line.
Formulas in rich text
A formula shows as a small grey box, a chip, with its value inside.
Point at it to see the formula; click it to change it in a small field below,
and press Enter to apply. A formula that shows nothing, as <% L = 6 %>,
shows a small ƒ. To insert one, press Ctrl+E, or type <%.
A new or changed formula shows its expression until you keep the line with Ctrl+Enter; then it shows its value.
What rich text cannot do
There are no colors, fonts or alignment, and several empty paragraphs in a row become one. Images show and stay, but cannot be inserted: write them in Markdown. A line with HTML tags or a table cannot be rich text: keep it as Markdown, or use a Table cell for the table.
Rich text has been tried in Chrome and Firefox. On Safari, it may not work as expected.
Markdown
A rich text line is saved as Markdown: a simple way to format text with ordinary characters. A Markdown line shows you those characters while you edit, and the formatted text when you leave the line. Press m on a line to edit it as Markdown, and r to go back to rich text: the text does not change.
| You write | The editor shows |
|---|---|
# Beam check | a heading |
## Input, ### Loads | smaller headings |
*italic* | italic |
**bold** | bold |
- a bullet | a bulleted list |
1. a step | a numbered list |
[OnLabs.org](https://www.onlabs.org/) | a link: OnLabs.org |
`code` | code |
> a note | an indented note |
Lists
- A line that starts with a dash is a bullet.
- Another bullet.
1. A line that starts with a number is a numbered step.
2. The next step.
Leave an empty line between a paragraph and a list.
Tables
| Section | Height (mm) | Mass (kg/m) |
|---------|------------:|------------:|
| IPE 200 | 200 | 22.4 |
| IPE 300 | 300 | 42.2 |
shows:
| Section | Height (mm) | Mass (kg/m) |
|---|---|---|
| IPE 200 | 200 | 22.4 |
| IPE 300 | 300 | 42.2 |
The columns are separated by |. The second row, with dashes, divides the
header from the rows; a colon on the right aligns a column to the right.
The columns do not need to line up in what you write. Every table spans the
full width of the text; each column takes the width its content needs, and
long text wraps inside its column.
To give a table a caption, write it between <caption> and </caption> on
the line right after the table, in a Markdown line:
| Section | Height (mm) | Mass (kg/m) |
|---------|------------:|------------:|
| IPE 200 | 200 | 22.4 |
| IPE 300 | 300 | 42.2 |
<caption>Table 1: IPE sections.</caption>
The caption shows below the table, aligned to the left. Stilo does not number tables: write the number yourself.
A Table cell lets you edit a table as a grid instead of writing these characters.
Links
A link is written as [text](address). A link to another document of the
folder, as [steel](../../library/steel.texl), opens it in the editor. A
short address like this one starts from the folder of the open document.
An image is written the same way, with ! in front:
. Links and images can point to any file
of the folder: see Links to read.
Special characters
In Markdown, subscripts and superscripts are written with HTML:
f<sub>ck</sub> shows fck, and m<sup>2</sup> shows
m2. Characters such as ², σ or γ can be typed or pasted as they are,
in every type of line.
Equations
Equations are written in LaTeX, the notation of scientific papers, between dollar signs:
The stress is $\sigma = M / W$, and the design moment is:
$$
M_{Ed} = \frac{q_d L^2}{8} = <% math.round (MEd * 10) / 10 %>\ \text{kNm}
$$
$...$ puts an equation inside a sentence; $$...$$, on lines of their own,
puts it on a line of its own, centered. A formula inside an equation shows its
value, so the equation above ends with the computed moment.
| Where | How |
|---|---|
| Rich text | Click ∑, or type $...$: the equation is set as you type. Click it to change the LaTeX, with a preview. |
| Markdown, Table | Write $...$ or $$...$$; the equation is set when you leave the line. |
Amounts of money stay text: in $5 and $10 there is no equation. An
equation's first $ has no space after it, and its last $ no space before it
and no digit after it. Write \$ for a plain dollar sign. In a table, write
\vert for a | inside an equation, since | separates the columns.
LaTeX with a mistake shows in red, with the reason when you point at it. An equation with an undefined value shows as its LaTeX, with the value highlighted.
Only the editor sets equations: the file, and the output of
stilo render, keep the LaTeX as text.
Formulas
A formula computes a value inside the text. It is written between <% and
%>:
Area: <% 3 * 4 %>
Area: 12
In the editor, a line shows the result of its formulas. Press Enter on the line to see the formulas themselves; Escape leaves it unchanged.
Write a formula
- Select a line and press Alt+Enter: an empty line appears below.
- Press Enter to edit it, and type
Area:. - Press Ctrl+E: a small field opens for the formula.
- Type
3 * 4and press Enter. The formula shows as a grey box, a chip, in the text. - Press Ctrl+Enter. The line shows Area: 12.
In a rich text line, as here, each formula is a
chip: point at it to see the formula, click it to change it. In a Markdown,
Text or Table line, Ctrl+E writes the brackets of a formula, <% %>,
with the cursor between them, around the selected text if there is any.
Names
A formula can give a value a name, and later formulas can use it. A formula that only gives names shows nothing. Several names in one formula are separated by commas:
<% L = 6, q = 12.5 %>
Span L = <% L %> m, load q = <% q %> kN/m.
The midspan moment is **<% q * L ^ 2 / 8 %> kNm**.
Span L = 6 m, load q = 12.5 kN/m.
The midspan moment is **56.25 kNm**.
A name is known on its own line and on every line below it, as in a
calculation on paper. Change L = 6 to L = 8 and press Ctrl+Enter:
every line below that uses L follows.
A name that is used before it is given, or misspelled, shows nothing: it is not an error. If a value is missing from a line, check the name, and check that it is given on a line above.
A formula can span several lines. # starts a note that runs to the end of
the line:
<%
L = 6, # span in m
q = 12.5 # load in kN/m
%>
Numbers
| Formula | Result |
|---|---|
7 + 3 * 2 | 13 |
(7 + 3) * 2 | 20 |
10 / 4 | 2.5 |
2 ^ 3 | 8 |
math.sqrt 16 | 4 |
math.round 2.567 | 3 |
math.round (2.567 * 100) / 100 | 2.57 |
math.max (3, 8) | 8 |
math.round rounds to a whole number. To keep two decimals, multiply by
100, round, and divide by 100, as in the table. The
reference of math
lists all the functions of math.
Text and choices
A formula can also give text, between double quotes, and choose between two
values with condition ? "if true" ; "if false":
<% section = "IPE 300", u = 0.85 %>
The section is <% section %>, utilization <% u * 100 %> %: **<% u <= 1 ? "adequate" ; "not adequate" %>**.
The section is IPE 300, utilization 85 %: **adequate**.
The comparisons are <, <=, >, >=, == (equal) and != (not
equal).
A formula stays on its line
A formula must close on the line where it opens. If you leave a line with a
<% that would only close at a %> on a line below, the editor keeps you on
the line and says why:
The “<%” on line 2 has no closing “%>”, so it would run into line 4: correct it, or press Escape to discard the changes.
The same goes for a %> you add below a <% left open higher up. A <% with
no %> anywhere below it is not a formula: it stays plain text.
A line that is only a formula
A line that holds one formula and nothing else can be a Formula cell: select the line and press =, as in a spreadsheet, and type the expression without the brackets. See Cell types.
When a formula is wrong
A formula that cannot be computed shows [[Undefined]], highlighted, and
the rest of the document still works:
Result: <% "a" - 1 %>
Result: [[Undefined]]
Here, the formula subtracts a number from a word. Edit the line and fix the formula. Point at the highlighted value to read the reason, or see Errors.
Learn more
A formula is a Texl tag, and the language inside it is called Swan. Writing documents with Texl explains how tags work in a document, The Swan language describes the language (lists, functions, namespaces), and the built-in reference lists every function.
Errors
A formula that cannot be computed shows [[Undefined]], and the rest of the
document still works. Here, the load is written as a text, with quotes, so it
cannot be multiplied:
<% L = 6, q = "12.5" %>
Moment: <% q * L ^ 2 / 8 %> kNm
Moment: [[Undefined]] kNm
The editor shows you where each error is:
- The value is highlighted in its line. Point at it to read the reason.
- The right margin shows a warning icon, with the number of errors on that line.
- The warning button in the top bar shows the total of the document, and opens the Errors pane.
The Errors pane
Click the warning button, a highlighted value or a number in the margin. The pane lists each error of the document:
cannot divide an undefined value by the number `8`
Moment: <% q * L ^ 2 / 8 %> kNm
Cell 1, line 2
Caused by
cannot multiply the text `"12.5"` by the number `36`
Cell 1, line 2
| Part | What it tells you |
|---|---|
| The first sentence | What went wrong. |
| The source line | The text of the formula, with the failing position marked. |
| Cell 1, line 2 | Where the error was made: the line numbered 1 on the sheet, and the second line of text inside it. A cell with one line of text shows only Cell 1. |
| Shown in cell 5 | Where the value shows, if that is another line. |
| Caused by | The earlier errors that led to this one. The last one is the origin: fix that one. |
Click an entry to select its line. Show the cell's errors, in the commands pane, opens the errors of the selected line. A double click on a highlighted value still edits the line.
An error made in an imported document names that document. Its link opens the document and selects the line.
What counts as an error
An error is an undefined value that a formula returns, alone or as an item of a list of values separated by commas:
<% bad = "a" - 1 %>Only given a name: <% 1 %>
Inside a list: <% ["a" - 1] %>
Returned: <% 1, "a" - 1 %>
Only given a name: 1
Inside a list: [[List of 1]]
Returned: 1, [[Undefined]]
Only the last line counts as an error here. A value that only gets a name, or that sits inside a list or a namespace, does not count until a formula returns it. A misspelled name is not an error either: it shows nothing (see Formulas).
An undefined value in the address of a link, or in another HTML attribute, counts too, but it cannot be highlighted there.
stilo render reports the same errors on the command line: see
stilo render.
Cell types
Every line has a type, which decides how it is edited and shown. The icon in the left margin, before the line number, shows it.
| Type | Key | Shows |
|---|---|---|
| Rich text | r | Formatted text, edited as in Word (Writing text). New lines are rich text. |
| Markdown | m | The same formatted text, written with Markdown characters, such as **bold** (Markdown). |
| Text | t | The text without Markdown formatting: **bold** stays as it is written. HTML tags, as <b>bold</b>, still work. |
| Formula | = | The result of one formula. You edit the expression alone. |
| Table | Shift+T | A table, edited as a grid. |
| Data table | d | A table of values that other lines compute with, edited as a grid. |
| Chart | c | A line chart, for example of two columns of a data table, edited as a form. |
Formulas between <% and %> work in Rich text, Markdown, Text and Table
lines.
Change the type
The quickest way is the type's key. Select a line and press =: the line
becomes a Formula cell and you are editing it, as = starts a formula in a
spreadsheet. The key is not typed into the line. On a line that already has
that type, the key just starts editing, as Enter does. With several lines
selected, the key acts on the active line alone.
To change several lines, use the menu:
- Click the icon in the left margin, or select the lines and press Ctrl+/. A small menu of the types opens, with the current one checked and each type's key.
- Pick a type with the mouse, or with ↑, ↓ and Enter. You can also press the first letter of a type.
Escape closes the menu without a change.
The text of the line stays the same: only the way it is edited and shown
changes. So changing the type loses nothing, and Ctrl+Z undoes it. Try it:
write **bold** on a line, make it Text, and the stars stay; make it Markdown
again, and the word turns bold.
Only the types that fit
Because the text never changes, a line can only take a type that fits it. In the menu, the others are greyed out with the reason, and the keyboard skips them. A type's key leaves the line as it is, and shows the reason under it:
| Type | Fits | Otherwise |
|---|---|---|
| Text, Markdown | any line | |
| Rich text | a line with simple formatting only | Needs text with simple formatting, without raw HTML or a table |
| Formula | a line that is one formula | Needs a single formula |
| Table | a line that is one Markdown table | Needs a table |
| Data table | a line that is one data table | Needs a data table |
| Chart | a line that is one chart | Needs a chart |
A rich text line cannot hold HTML tags, such as <sub>, or a table. Keep
such a line as Markdown, or put the table in a Table line.
Blank lines and comments never count against a type, and an empty line can take any type. With several lines selected, the menu offers the types that fit all of them.
Formula cells
A Formula cell holds one formula. You edit the expression alone, without
<% and %>, with its parts in color, and the line shows the result:
q * L ^ 2 / 8
In the file, it is an ordinary formula, and comments around it stay:
<!--{ mom3 : formula }-->
<% q * L ^ 2 / 8 %>
An expression cannot contain %>, which would end the formula. Ctrl+Enter
then keeps you on the line and says why; correct it, or press Escape to
discard the change.
Table cells
Press Shift+T on an empty line: it starts a new table of two columns. Each
table cell is a field of the grid, and you write formulas in it between <%
and %>.
| Keys and buttons | What they do |
|---|---|
| Tab, Shift+Tab | Go to the next or previous field. Tab in the last field adds a row, as in Word. |
| ↑, ↓ | Go to the field above or below |
| + Row, + Column | Insert a row below, or a column to the right |
| − Row, − Column | Delete the current row or column |
| Align buttons | Align the current column left, center or right, as in Word. The pressed button shows its alignment. |
| Ctrl+Enter, Escape | Keep the changes or discard them, as in other lines |
In the file, the table is an ordinary Markdown table, so it renders in any Texl tool:
<!--{ inp1 : formula }-->
<% L = 6, q = 12.5 %>
<!--{ tab1 : table }-->
| Quantity | Value |
|:---------------|---------------------------:|
| Span | <% L %> m |
| Midspan moment | <% M: q * L ^ 2 / 8 %> kNm |
<!--{ con1 : markdown }-->
The moment <% M %> kNm goes to the bending check.
<!--{ inp1 : formula }-->
<!--{ tab1 : table }-->
| Quantity | Value |
|:---------------|---------------------------:|
| Span | 6 m |
| Midspan moment | 56.25 kNm |
<!--{ con1 : markdown }-->
The moment 56.25 kNm goes to the bending check.
Table cells cannot refer to each other by position, as B2 does in a
spreadsheet. To use a value elsewhere, name it where you compute it: M: above
gives the value a name and also shows it.
An unchanged table keeps its text as you wrote it; an edited one is saved with its columns lined up. A Markdown line that holds a table can change to Table and back without loss.
Data table cells
A Data table holds values, such as a list of load cases, that other lines compute with, as a range of cells does in a spreadsheet:
Name loads
| Case | Fx (kN) | Fy (kN) |
|-------|-------------|---------|
| ULS-1 | 1.35 * Fx_k | 35 |
| ULS-2 | 1.5 * Fx_k | |
Press d on an empty line: it starts a new table of two columns and one row. While you edit it:
- Name (optional) gives the table a name, here
loads, so that other lines can use it. A name has only letters, digits and_, and does not start with a digit. - The first row holds the column names. They are plain text, so units
and symbols are fine:
Fx (kN),γG. - Every other field holds one value, written as a formula without
<%and%>: a number,120; a text, in quotes,"ULS-1"; or a calculation,1.35 * Fx_k, with the names of the lines above. An empty field stays empty. - The keys and the + Row, + Column, − Row and − Column buttons are those of a Table.
A field whose value is not a valid formula, as ULS-1 without quotes, is
outlined in red as you type, with the reason when you point at it. The line
cannot be kept until you correct it.
Outside editing, the line shows the computed table, with columns of numbers aligned right:
| Case | Fx (kN) | Fy (kN) |
|---|---|---|
| ULS-1 | 135 | 35 |
| ULS-2 | 150 |
With the name loads, the lines below use the table like this:
| You write | You get |
|---|---|
loads.column "Fx (kN)" | the values of a column, as a list |
loads.row 0 | a row, as a list; rows count from 0 |
loads.columns | the column names, as a list |
loads.rows | all the rows, as a list of lists |
The largest horizontal load is <% math.max (list.enum (loads.column "Fx (kN)")) %> kN.
The largest horizontal load is 150 kN.
list.enum turns the list into separate values, which math.max compares
(see Lists). A value that cannot be computed
shows as [[Undefined]] in its own field; the rest of the table still shows.
Such a value is not listed in the Errors pane.
A field cannot contain " in a column name, or %> anywhere. Fields cannot
refer to each other, as B2 does in a spreadsheet: compute a value on a line
above, give it a name, and use the name in the field.
Chart cells
A Chart draws a line through points, such as the bending moment along a beam or the values of two columns of a data table. Press c on an empty line: the line becomes a chart, edited as a form, one field per row, with its description on the left:
| Field | What you write |
|---|---|
| Chart type | The kind of chart, from a list. Only Line for now. |
| X values | A formula that gives a list of numbers, such as loads.column "x (m)" |
| Y values | A formula that gives a list of as many numbers, such as loads.column "M (kNm)" |
| X axis label | Plain text, without quotes. Optional. |
| Y axis label | Plain text, without quotes. Optional. |
| Title | Plain text, without quotes. Optional. |
Tab and Shift+Tab, or ↑ and ↓, move between the fields; Ctrl+Enter keeps the chart and Escape discards the changes, as in every line. A formula field that is not valid is outlined in red as you type, and X and Y values are required.
Outside editing, the line shows the chart across the width of the page, in the colors of the light or dark theme. The axes run between round numbers just below and above the values. A point whose X or Y value is not a number, as an empty field of a data table, is left out.
With the data table sections, of IPE sections with
columns h (mm) and Mass (kg/m), this chart shows the mass against the
height:
| Field | Value |
|---|---|
| X values | sections.column "h (mm)" |
| Y values | sections.column "Mass (kg/m)" |
| X axis label | h (mm) |
| Y axis label | Mass (kg/m) |
| Title | IPE sections |
The X and Y values can be any list, not only a column. The beam example
(examples/packages/beam/analysis.texl) draws its bending-moment diagram
from lists that it computes.
If the chart cannot be drawn, for example because X and Y have a different
number of values, the line shows [[Undefined]] and the
Errors pane says why.
The Stilo library
Data tables and charts need the Stilo library, a document of functions that comes with Stilo. When you write the first data table or chart of a document, the editor adds a line at the top that imports the library, and hides it. Leave that line where it is.
The library is found in the references of the
package the document belongs to, as references/stilo.texlz. In a folder
that is not a package, data tables and charts show [[Undefined]] until you
make it one with stilo init. A package made with an older
Stilo may have an older library: see
Update the Stilo library.
Lines edited by hand
A Formula, Table, Data table or Chart line whose text no longer has that shape, because the file was edited in another program, is edited as Text. You can leave it unchanged, or correct it until it has the shape.
Unknown types
A document written with a newer Stilo, or another program, may use a type that your editor does not know. Such a line is edited and shown as Text, and keeps its type when you save.
Comments
A comment is a note on a line, for you or a colleague. It is stored in the document, inside the line it is about, and moves with it.
The right margin shows how many comments a line has.
Read comments
Click the number in the right margin, or select the line and press Shift+F2. The comments pane opens on the right, with the comments of that line. Alt+C, or the comments button in the top bar, shows or hides the pane.
Each comment in the pane says which line it is on, as Cell 3. Click a comment to select its line in the document.
Write a comment
- Select a line and press Enter to edit it.
- Press Shift+F2. In a rich text line, a small field opens for the
comment; type your note and press Enter. In a Markdown or Text line,
the editor inserts the brackets of a comment,
<!--[ ]-->, with the cursor between them; type your note. - Press Ctrl+Enter.
- Span: <% L %> m
<!--[ Anna: span and loads from the client's brief, rev. B. ]-->
The note does not show in the line's text, only in the comments pane. Start a comment with your name, so that others know who wrote it.
To change or delete a comment, edit the line and change the text between the brackets, or delete the brackets with it. A rich text line does not show the brackets: press m to edit the line as Markdown, change the comment, and press r to make it rich text again.
Linking documents
A document can use the values of another one: a library of materials, the loads from a colleague's calculation, the rates of a price list. When the other document changes, yours follows.
The sample documents show how. The beam package,
examples/packages/beam, has a steel reference in its references/ folder:
steel-revA.texlz, revision A of a package of steel data. Its main document
gives the steel grade and the IPE sections (shortened here):
# Steel, revision A
<% texl.import "sections.texl" ~> (s -> bind "IPE" s.data.IPE) %>
<%
grade = {name: "S355", fy: 355}, # yield strength in N/mm²
E = 210000 # modulus of elasticity in N/mm²
%>
The basis of design of the beam, basis-of-design.texl, imports it, under
the name steel, and uses its values below:
<% texl.import("~/references/steel-revA.texlz") ~> (lib -> bind "steel" lib.data) %>
<% section = steel.IPE.IPE300 %>
- Section: <% section.name %>, steel <% steel.grade.name %>
- Section: IPE 300, steel S355
Documents can link in a chain. The design report of the same package,
beam-check.texl, imports the basis of design and the calculation note, and
takes its figures from them: change the span in the basis of design, and the
report follows.
<% texl.import "basis-of-design.texl" ~> (d -> bind "bod" d.data) %>
How it works
texl.import("...")reads the document at an address.- A short address starts from the folder of the document that imports:
basis-of-design.texlis in the same folder,../library/steel.texlgoes one folder up, then intolibrary/. - In a package,
~stands for the package folder:~/references/steel-revA.texlzreads the same reference from any folder of the package. A reference imported by its name, a folder or a packed package, gives its main document,index.texl. - The values that the imported document gives names to, as
gradeandIPE, are the members oflib.data.bind "steel" lib.datagives them, together, the namesteelin this document:steel.grade.nameis"S355". - The import must be on a line above the lines that use it.
Copy link, in the navigation pane, gives you the short address of a document, relative to the open one.
Copy the import line and change the address and the name to use another document.
The other document changes, yours follows
The imported document is read again every time the editor computes yours: after every change you make. Open the basis of design, change the span, save, and open the design report again: the moments and the checks use the new value.
A packed reference cannot change: its documents open read-only. A new
revision of it comes as a new file, as steel-revB.texlz; change the import
to use it.
An address can also be a full web address, https://..., of a document on
another server that allows it.
When an import fails
If the document cannot be read, for example because the address is wrong or the
document was moved, the formula shows [[Undefined]] and the
Errors pane says why. Correct the address. The lines that use the
imported values then follow.
To show your own text instead, write a default with |:
<% texl.import("missing.texl") ~> (doc -> doc.text | "(not found)") %>
(not found)
Links to read
A Markdown link to another document, as [basis of design](basis-of-design.texl),
does not import anything: it opens the other document in the editor when you
click it.
A link can also point to any other file in the folder, and an image can show one:
[Drawing](drawings/beam.pdf)

| A link to | Opens |
|---|---|
a .texl document on this server | in place, in the editor |
| another file, or another website | in a new tab, so your document stays open |
an e-mail address (mailto:) | in your e-mail program, as the browser decides |
A file of a kind that the browser cannot show downloads instead. A link to a file that does not exist opens an empty Stilo in the new tab.
Text shown from an imported document is part of the document showing it. So a relative link in that text starts from the folder of the document showing it, not from the folder of the imported document. In a document meant for import, use full addresses for links.
Packages and references
A package is a folder of documents that belong together, such as the calculations for one structure, with the documents of others that they use. Everything a package needs is inside its folder, so the folder works as a whole wherever you copy it: to a colleague, to a server, into git.
beam/
├─ package.texl makes this folder a package
├─ references/
│ ├─ stilo.texlz the Stilo library
│ └─ steel-revA.texlz a colleague's steel data, revision A
└─ checks/
└─ beam-check.texl
Make a package
Run stilo init in the folder:
cd beam
stilo init
It writes package.texl, which marks the folder as a package, and puts the
Stilo library into references/, as stilo.texlz. The
sample documents already have one:
examples/packages/beam.
package.texl is an ordinary document, with the package's name. You can open
it in the editor and add notes about the package.
~, the package folder
In an import, ~ stands for the package folder: the nearest folder, at or
above the document, that has a package.texl. So this line imports the Stilo
library from any document of the package, however deep in its folders:
<% texl.import "~/references/stilo.texlz/index.texl" ~> (lib -> bind "stilo" lib.data.stilo) %>
The editor adds this line, hidden, when you write the first data table or chart of a document.
A document can move to another folder of the package without a change to its imports.
Outside a package, ~ means something else: the folder that
stilo serve serves, in the editor, and your home folder,
for stilo render. Make the folder a package, and both
mean the same folder.
References
The packages that your package uses are its references: a library of
steel sections, a colleague's loads, the Stilo library. They live in the
references/ folder. There is nothing to install: to add a reference, copy
it into references/.
A reference is a package itself, either a folder or a
packed package, one file. Its main document is
index.texl. Import the reference by its name, and you get that document:
<% texl.import("~/references/steel-revA.texlz") ~> (lib -> bind "steel" lib.data) %>
This is how the basis of design of the sample beam takes its steel data.
index.texl of the steel package imports its own sections.texl, from its
own folder, and gives the sections and the steel grade to the documents that
import it. A reference that is a folder works the same way:
~/references/steel/ imports steel/index.texl. You can also import any
other document of a reference by its full address, as
~/references/stilo.texlz/index.texl above.
| Reference | What it gives |
|---|---|
references/stilo.texlz | The functions that Stilo's lines use: the data table and the chart. stilo init puts it there. |
A reference has its own package.texl, so inside it ~ is its own folder,
not yours.
Packed packages
A packed package is a whole package in one file, named *.texlz, to share
as you share a Word file. stilo pack makes one from a
package folder:
stilo pack steel -o beam/references/steel-revA.texlz
Stilo opens a packed package as a folder that cannot be changed. In the navigation pane it has its own icon and a lock; unfold it to see its documents, which open read-only, and use them as any other. Imports reach into it, also into packed packages inside it.
The file itself is like any other file: you can upload, rename, move, delete and download it. To change a packed package, change the folder it was made from, and pack it again, under a new name if it is a new revision.
The same files always give the same packed file, byte for byte, and
stilo pack prints its fingerprint (SHA-256), a code that changes when
anything inside changes. Two people with the same fingerprint have the same
package.
Behind the scenes, a .texlz file is a ZIP archive with package.texl at its
top.
Update the Stilo library
A package keeps the copy of the Stilo library that stilo init put in it,
also when you update Stilo: its documents keep working as they were. To give a
package the library of your current Stilo, delete references/stilo.texlz
and run stilo init in the package again: it adds the missing library and
leaves the rest alone.
rm beam/references/stilo.texlz
stilo init beam
Packages made with older versions
Up to Stilo 0.5, a package was called a project, marked by project.texl,
and its references were in lib/. Stilo 0.6 no longer reads those names.
Rename them once:
- Rename
project.texltopackage.texl, andproject_nameinside it topackage_name. - Rename
lib/toreferences/, and in every document replace~/lib/with~/references/in the imports.
Up to Stilo 0.6, the Stilo library was a folder, references/stilo/. It
still works. To use the library of your current Stilo, run stilo init in
the package, which adds references/stilo.texlz; then replace
~/references/stilo/ with ~/references/stilo.texlz/ in the imports, and
delete the old folder.
Good to know
- The editor hides folders named
~, and does not let you create one: in an address,~always stands for the package folder. - Only Stilo, in the editor and in
stilo render, knows this meaning of~and of packed packages. Other Texl programs read~as an ordinary folder name.
Files and folders
Save
Ctrl+S saves the document to its file. A dot (•) after the name in the top bar means that there are unsaved changes; after saving, the top bar says Saved.
A line that you are still editing is kept and saved too, as if you had pressed Ctrl+Enter. If the line refuses the edit, it stays open with its message, nothing is saved, and the top bar says Not saved: correct the cell being edited.
If the file changed on disk since you opened it (another window, or another program, saved it), Stilo does not overwrite it: the top bar says Not saved: changed on the server, reload it. Copy your changes, run Reload document from the commands pane, and apply them again.
Before you open another document with unsaved changes, Stilo asks whether to save them, in a dialog of its own. Before you close the page with unsaved changes, the browser asks.
Stilo's dialogs say on their buttons what they do, as Save, Discard, Delete or Rename. Enter answers yes, Escape no.
The navigation pane
- Click a document to open it. Documents are listed without the
.texlextension. - Other files, such as images, PDFs and spreadsheets, are listed too, greyed out, with their full name. Click one to open it in a new browser tab; a file that the browser cannot show downloads.
- Click a folder to fold or unfold it. Double-click it to show only that folder; the arrow at the top of the pane goes back up.
- A packed package (
.texlz) has its own icon and a lock. Click it to unfold it as a folder; its documents open read-only. - Right-click a document, a folder or the empty area of the tree for a menu of
commands, or use the
⋯button of a row or of the pane's header. The header also has buttons for New document and New folder. - Ctrl+B hides or shows the pane.
Each document has its own address in the browser, so you can bookmark it, and the browser's back button goes to the document you had open before.
New documents and folders
New document… (Alt+N) asks for a name, in the tree, and creates the
document in the folder you right-clicked. The header button and Alt+N use
the folder of the item you last used in the tree. The name gets .texl if it
does not have it. Stilo does not overwrite an existing document.
New folder… creates a folder the same way.
Upload files
Upload files…, in the menu of a folder or of the pane, adds files from your computer to the folder: drawings, photos, data. Pick one or several in the dialog that opens. A file whose name is already taken in the folder is not uploaded; the top bar says which ones.
A document can then show or link to the file: see Links to read.
Managing documents and folders
These commands are in the menus of the navigation pane, and in the commands pane, where they act on the item you last used in the tree. They work on other files as on documents, except Duplicate.
| Command | What it does |
|---|---|
| Rename (F2) | Changes the name of a document, file or folder, in its row of the tree. A rename cannot add or remove the .texl extension: a document stays a document. |
| Move to… | Moves a document, file or folder to a folder you choose. |
| Duplicate | Copies a document next to it, under a name you give, and opens the copy. Documents only. |
| Download | Saves a document, file or packed package on your computer, through the browser. Folders cannot be downloaded. |
| Copy link | Copies the link of a document or file, relative to the open document, ready for texl.import, a Markdown link or an image. |
| Delete (Delete) | Moves a document, a file or a folder with everything in it to the trash. |
| Open as root | Shows only this folder in the pane, as a double click does. |
| Refresh | Reads the tree again. |
| Show other files | Shows or hides the files that are not documents, and the folders that hold only such files. It is on by default, and the browser remembers it. |
Commands that do not apply to an item, in the menus and in the commands pane, are greyed out, with the reason.
F2 and Delete work on the tree only while an item of the tree has the focus; elsewhere they act on the lines of the sheet.
Links do not follow. Rename and Move to… warn you that links to the item will stop working: links and imports in other documents are not updated.
If the item holds the open document, Stilo offers to save your changes first. The document stays open at its new address, with a fresh undo history.
Read-only documents and folders
Some documents and folders cannot be changed: those inside a packed package, and those that Stilo has no permission to change on your computer. The navigation pane shows them with a lock. A read-only document opens with Read-only in the top bar, and the reason; you can read it, copy from it and import it, but not save, rename, move or delete it. Nothing can be added to a read-only folder.
Delete and the trash
Delete asks first. Nothing is erased: a document or file goes to a hidden
.trash folder at the top of the served folder, inside a folder named after
the time of the deletion. To get it back, move it out with your file manager,
as Stilo has no command for it. A deleted open document closes.
The folder of a deleted document stays, even if empty. Deleting a folder moves everything in it, documents and other files, to the trash, and the folder is gone. The question before it says how many documents and other files go with it.
Commands
F1, or the ⋮ button at the right of the top bar, opens the list of all the commands, grouped and with their shortcuts. Click a command to run it; click a group's name to fold it. The browser may ask before Paste runs from here.
Show source (Alt+U) shows the document's text, read-only, in place of the editor, with your unsaved changes. Alt+U again, the close button or any editor command goes back to the editor, with its undo history kept.
Alt+T switches between the dark and the light theme. The browser remembers your choice.
The file
Every document is a plain text file, which any text editor can open. Each
line of the sheet starts with a marker, as <!--{ bek4 : markdown }-->,
with its name and its type. The document format
describes it.
Keyboard shortcuts
On a Mac, use ⌘ instead of Ctrl, and ⌥ (Option) instead of Alt. The commands pane (F1) lists the same shortcuts, and runs a command when you click it.
Files and view
| Keys | Command |
|---|---|
| Ctrl+S | Save |
| Alt+N | New document |
| Ctrl+B | Show or hide the navigation pane |
| F1 | Show the commands |
| Alt+C | Show the comments |
| Alt+U | Show the document's text, read-only |
| Alt+T | Switch between the light and dark theme |
Reload document, which reads the document from its file again, Show the cell's errors, and the commands that hide lines have no shortcut: run them from the commands pane.
In the navigation pane
When an item of the tree has the focus:
| Keys | Command |
|---|---|
| F2 | Rename the document, file or folder |
| Delete | Delete the document, file or folder |
Lines
When no line is being edited:
| Keys | Command |
|---|---|
| ↑ / ↓ | Select the line above or below |
| Shift+↑ / ↓, Shift+click | Select several lines |
| Enter, F2, double click | Edit the selected line |
| Alt+Enter | Insert an empty line below |
| Alt+Shift+Enter | Insert an empty line above |
| Alt+↑ / ↓ | Move the selected lines up or down |
| Delete, Backspace | Delete the selected lines |
| Ctrl+C / Ctrl+X / Ctrl+V | Copy, cut and paste lines |
| Ctrl+Z | Undo |
| Ctrl+Shift+Z, Ctrl+Y | Redo |
| Ctrl+/ | Change the type of the selected lines |
| = | Make the line a Formula cell and edit it |
| R | Make the line rich text and edit it |
| T | Make the line Text and edit it |
| M | Make the line Markdown and edit it |
| Shift+T | Make the line a Table and edit it |
| D | Make the line a Data table and edit it |
| C | Make the line a Chart and edit it |
| Shift+F2 | Show the comments of the selected line |
Pasted lines replace the selected ones, as in a spreadsheet.
While editing a line
| Keys | Command |
|---|---|
| Ctrl+Enter | Keep the changes and leave the line |
| Escape | Discard the changes and leave the line |
| Enter | Start a new line of text inside the cell |
| Ctrl+E | Insert a formula, <% %>, around the selected text if there is any (Markdown, Text) |
| Shift+F2 | Insert a comment, <!--[ ]--> |
| Ctrl+Z / Ctrl+Shift+Z | Undo and redo inside the cell |
A click on another line keeps the changes of the line you are editing, as in Excel. If the line cannot be kept, it stays open and says why.
While editing rich text
| Keys | Command |
|---|---|
| Ctrl+B, Ctrl+I, Ctrl+U | Bold, italic, underline |
| Ctrl+=, Ctrl+Shift+= | Subscript, superscript |
| Ctrl+Alt+1, 2, 3 | Heading 1, 2, 3 |
| Ctrl+Alt+0 | Normal text |
| Ctrl+K | Add or change a link |
| Ctrl+E | Insert a formula |
| Shift+F2 | Add a comment |
| Tab, Shift+Tab | Indent or outdent a list item |
| Enter | Start a new paragraph |
| Shift+Enter | A line break inside a paragraph |
| ↑ / ↓ | Move inside the line |
In the field of a formula, an equation, a link or a comment: Enter applies, Shift+Enter starts a new line, Escape cancels.
While editing a table or a data table
| Keys | Command |
|---|---|
| Tab, Shift+Tab | Go to the next or previous field; Tab in the last field adds a row |
| ↑ / ↓ | Go to the field above or below |
| Ctrl+Enter | Keep the changes and leave the line |
| Escape | Discard the changes and leave the line |
While editing a chart
| Keys | Command |
|---|---|
| Tab, Shift+Tab, ↑ / ↓ | Go to the next or previous field |
| Ctrl+Enter | Keep the changes and leave the line |
| Escape | Discard the changes and leave the line |
In the type menu
| Keys | Command |
|---|---|
| ↑ / ↓, or a type's first letter | Pick a type |
| Enter, Space | Apply it |
| Escape, Tab | Close the menu |
The stilo command
stilo is Stilo's command line. It has five subcommands:
| Command | What it does |
|---|---|
stilo init | Makes a folder a package, with the Stilo library |
stilo pack | Packs a package into one file, opened read-only |
stilo serve | Serves a folder of documents with the web editor |
stilo render | Renders a document to the terminal or a file |
stilo tutor | Opens the tutorial, which teaches Stilo by doing |
stilo serve ~/reports
stilo render ~/reports/beam-check.texl -o beam-check.md
Every command takes -h (or --help) and prints its options:
stilo serve --help
Getting started installs the command.
python -m stilo works too, in an environment where Stilo is installed.
Exit status
stilo exits with status 0 when the command succeeds, 1 when it fails
(for example, a file that cannot be read, or an undefined value with
stilo render --strict), and 2 when the command line is
wrong (an unknown command or option). Errors are printed to standard error,
starting with stilo:.
stilo render missing.texl
stilo: missing.texl: could not be loaded: FileNotFoundError: [Errno 2] No such file or directory: '/home/ada/missing.texl'
stilo init
stilo init makes a folder a package: a folder of
documents that belong together, with the references they use.
stilo init beam
Stilo: /home/ada/beam is a package: package.texl, references/
It creates the folder if it does not exist, and then:
- writes
package.texl, which marks the folder as a package; - puts the Stilo library into
references/, asstilo.texlz, for the data tables and charts of the package's documents.
Without a folder, it makes the current folder a package:
cd beam
stilo init
Options
| Option | What it does |
|---|---|
folder | The folder of the package, created if missing. Default: the current folder. |
--name NAME | The name of the package, written in package.texl. Default: the folder's name. |
package.texl
package.texl is an ordinary document, which you can open in the editor and
add notes to:
# beam
This folder is a Stilo package. This file marks its home folder: in an
import, `~` stands for it, as in `~/references/stilo.texlz/index.texl`. The values below
configure the package.
<% package_name = "beam" %>
<% stilo_version = "0.7.0" %>
stilo_version is the version of Stilo that made the package.
Running it again
stilo init does not overwrite anything. In a folder that is already a
package, it leaves package.texl alone and only adds the Stilo library if
references/stilo.texlz is missing:
Stilo: /home/ada/beam is already a package: added references/stilo.texlz
If the library is there, there is nothing to do:
Stilo: /home/ada/beam is already a package, with references/stilo.texlz: nothing to do
This is how you update the Stilo library of a package.
stilo pack
stilo pack [folder] [-o FILE]
Packs a package folder into one file, a
packed package named *.texlz, to
share as one file. Stilo opens it read-only.
stilo pack steel
Stilo: packed 3 files into /home/ada/steel.texlz
sha256 12bc89180ae93bc618fb719d7d36ebd951713885467bcfd5abc0793cee2fe53a
The second line is the file's fingerprint (SHA-256): the same files always give the same packed file and the same fingerprint, and any change inside gives another one. Compare fingerprints to know whether two people have the same package.
To use the packed package in another package, put it in that package's
references/ folder and import it by its name:
stilo pack steel -o beam/references/steel-revA.texlz
<% texl.import("~/references/steel-revA.texlz") ~> (lib -> bind "steel" lib.data) %>
Arguments and options
| Argument | Default | Meaning |
|---|---|---|
folder | the current folder | The package to pack. It must have a package.texl. |
-o, --output FILE | the folder's name with .texlz, next to the folder | The file to write. An existing file is replaced. |
What goes in
Every file of the folder goes in, documents and other files, in their
folders. Left out are hidden files and folders (their names start with a
dot, as .git and the .trash of deleted files), links, and the files
that git is told to ignore.
A folder without package.texl is not packed, and stilo pack exits with
status 1:
stilo: /home/ada/notes: not a package (no package.texl)
stilo serve
stilo serve [folder] [--host HOST] [--port PORT] [--web WEB]
Serves a folder of Texl documents, and the web editor that edits them, over HTTP.
stilo serve ~/reports
Stilo: serving /home/ada/reports at http://127.0.0.1:8010/ (press Ctrl+C here to stop)
Open the address in your browser to see the folder in the editor. Press Ctrl+C in the terminal to stop the server; it says Stilo: stopped. Goodbye!
Arguments and options
| Argument | Default | Meaning |
|---|---|---|
folder | the current folder | The folder of the documents. It is the root of the server: everything under it can be read, its .texl files can be written, and its files and folders can be created, uploaded, moved and deleted. |
--host HOST | 127.0.0.1 | The address to listen on. The default accepts connections from your own computer only. |
--port PORT | 8010 | The port to listen on. Choose another one if a program already uses it. |
--web WEB | the one installed with Stilo | The built web editor. Change it only to serve another build of it. |
Addresses
Every document has one address: its path in the folder. With the server
above, ~/reports/projects/beam.texl is at:
http://127.0.0.1:8010/projects/beam.texl
- In a browser, the address of a document opens it in the editor.
- For a Texl import, the same address gives the file itself. This is how
one document imports another:
texl.import("../library/steel.texl")inprojects/beam.texlreadslibrary/steel.texlfrom the server.
The editor's navigation pane shows the whole folder. Add ?root= to an
address to show only a part of it:
http://127.0.0.1:8010/projects/beam.texl?root=projects
What is served
- Every file is listed in the navigation pane. Only
.texlfiles are documents, which the editor opens and saves. Other files (images, PDFs, data) can be uploaded, renamed, moved and deleted, and read by an import, a link or an image in a document. - A packed package (
.texlz) is shown as a folder that cannot be changed: its documents open read-only, and imports reach into it. The file itself can be uploaded, renamed, moved, deleted and downloaded. - Files and folders that Stilo has no permission to change on your computer are read-only too: the navigation pane shows them with a lock.
- For an import, the address of a folder or a packed package leads to its
index.texl. Add?downloadto the address of a file to download it. - Every other file has its own address, and comes as itself, with its real type. A file of an unknown type downloads. HTML, XML and SVG files opened by their address cannot run scripts, so a file in the folder cannot change your documents.
- Hidden files and folders (names starting with
.) are never served. This includes.trash, where deleted files go. - Names starting with
_are reserved at the top of the folder (the server uses/_apiand/_app): files and folders with such names there are not served. - Symbolic links that lead out of the folder are not followed.
Programmers who want to talk to the server from their own programs find its protocol in the Stilo repository.
Serving to other computers
The server has no accounts and no passwords: anybody who can reach it can
read, change, move and delete every document in the folder. --host 0.0.0.0 makes it
reachable from your network; do that only on a network you trust, or put
the server behind your own access control (a VPN, or a proxy that asks for
a password).
stilo serve ~/reports --host 0.0.0.0 --port 8080
stilo render
stilo render file [-o OUTPUT] [-d] [--strict]
Renders a Texl document: prints its text with every <% %> formula
replaced by its value.
Given beam.texl:
<!--{ bek4 : markdown }-->
# Beam check
<% L = 6, q = 12.5 %>
Span <% L %> m, load <% q %> kN/m.
<!--{ mom3 : markdown }-->
Midspan moment: **<% q * L ^ 2 / 8 %> kNm**
stilo render beam.texl
<!--{ bek4 : markdown }-->
# Beam check
Span 6 m, load 12.5 kN/m.
<!--{ mom3 : markdown }-->
Midspan moment: **56.25 kNm**
The cell markers, <!--{ ... }-->, stay in the output. They are HTML
comments, so they do not show when the output is read as Markdown or HTML.
A chart is written as an SVG image,
<svg ...> followed by its lines, which shows as the chart when the output is
read as Markdown or HTML. Equations stay as their LaTeX text.
Arguments and options
| Argument | Meaning |
|---|---|
file | The document to render. A folder or a packed package (.texlz) renders its index.texl. |
-o, --output OUTPUT | Writes the rendering to this file instead of the terminal. An existing file is replaced. |
-d, --debug | Numbers the undefined values in the output, and explains each one on standard error. |
--strict | Exits with status 1 if the document returned an undefined value. The output is still written. |
stilo render beam.texl -o beam.md
Imports
Relative imports resolve from the document's own folder, as in the editor,
and ~ stands for the folder of the document's
package (your home folder outside a package).
If projects/beam.texl contains:
<% texl.import("../library/steel.texl") ~> (lib -> bind "steel" lib.data) %>
then stilo render projects/beam.texl reads library/steel.texl, wherever
you run the command from. Imports into
packed packages work as in the
editor.
Errors
A formula that cannot be computed does not stop the rendering: it shows as
[[Undefined]], and the rest of the document renders. One line on standard
error, which is not part of the output, says how many there are. Given
report.texl:
<% L = 6, q = "12.5" %>
Moment: <% q * L ^ 2 / 8 %> kNm
stilo render report.texl
Moment: [[Undefined]] kNm
stilo: report.texl: 1 undefined value (use --debug to list them)
With --debug, the output numbers each value, and the same value keeps its
number. Standard error explains each one: where it was made, as
file:line:column, what went wrong, the source line with a caret under the
position, and its causes.
stilo render report.texl --debug
Moment: [[Undefined #1]] kNm
stilo: report.texl: 1 undefined value
#1 report.texl:2:22 cannot divide an undefined value by the number `8`
Moment: <% q * L ^ 2 / 8 %> kNm
^
caused by report.texl:2:14: cannot multiply the text `"12.5"` by the number `36`
An error made in an imported document points into that document, and a last line says where the value shows. As in the editor, only a value that a formula returns counts.
Undefined values do not change the exit status, unless you ask for it:
--strict exits with status 1 if there are any, which is useful in a script
that must not publish a broken document. The output is still written.
Otherwise, stilo render fails (with exit status 1) only when the file itself
cannot be read, and says why, or when the output cannot be written.
stilo tutor
stilo tutor [--dir DIR] [--reset] [--port PORT] [--no-browser]
Opens Stilo's tutorial in your browser: short lessons that teach the editor
and the stilo command by doing.
stilo tutor
Stilo: a new copy of the tutorial is in /home/ada/.local/share/stilo/tutorial
Stilo: the tutorial is at http://127.0.0.1:8010/index.texl (press Ctrl+C here to stop)
The tutorial has twelve lessons, 30 to 45 minutes in all, from your first edit to a package of your own, and two advanced lessons after them. Each lesson is a document: you read it and do its exercises in the editor. Many exercises check themselves and show ✓ Done, and the index shows how far you are.
Press Ctrl+C in the terminal to stop; Stilo says Stilo: stopped.
Goodbye! Your work stays: the next stilo tutor opens your copy as you
left it.
Your copy
The first stilo tutor copies the tutorial into a folder of your own and
makes it a package. You change your copy, never
the original, so you can try anything.
The folder depends on your computer: stilo tutor --help shows it. On
Linux it is ~/.local/share/stilo/tutorial.
--reset starts again from a fresh copy. Your old copy is not deleted: it
is renamed, with the date and time, next to the new one, and stilo tutor
says where.
stilo tutor --reset
Stilo: your old copy of the tutorial is now in /home/ada/.local/share/stilo/tutorial-old-20261110-093012
Stilo: a new copy of the tutorial is in /home/ada/.local/share/stilo/tutorial
When a newer Stilo comes with new lessons, stilo tutor says that your copy
was made by an older version and proposes --reset.
Options
| Option | Default | Meaning |
|---|---|---|
--dir DIR | your user data folder | The folder of your copy. It must be empty, missing, or a copy of the tutorial. |
--reset | Start again from a fresh copy; the old one is moved aside. | |
--port PORT | 8010 | The port to serve the tutorial on, as in stilo serve. |
--no-browser | Do not open the browser; open the address that stilo tutor prints yourself. |
The document format
A Stilo document is one Texl text file, with the extension .texl. You
can open it in any text editor, keep it in git, and render it with any Texl
tool, without Stilo. This page describes what the editor adds to a plain
Texl file: cell markers and cell comments.
<!--{ bek4 : markdown }-->
# Beam check
<% L = 6, q = 12.5 %>
<!--{ mom3 : markdown }-->
Midspan moment: <% q * L ^ 2 / 8 %> kNm
<!--[ Anna: check the load combination. ]-->
Cells
Each cell starts with a marker line, <!--{ name : type }-->, on a line
of its own. The cell's content is everything up to the next marker line. A
marker line inside a <% %> formula, for example in a text, is not a marker: it
is part of the formula.
- The type says how the editor edits and shows the cell:
rich(rich text),markdown,text,formula(a line that is one formula),table(a line that is one Markdown table),data(a data table) orchart. A type that the editor does not know is edited astext, and kept when the file is saved. | hiddenafter the type, as in<!--{ imp1 : formula | hidden }-->, marks a hidden line.- The name identifies the cell: four lowercase letters and digits, such
as
bek4. The editor gives one to every new cell, and to every marker written without a name, such as<!--{ markdown }-->. Names are unique in a document; the editor does not show them, people refer to lines by their number. - Text before the first marker is a
textcell without marker. So any Texl file opens in the editor, also one written without it.
The markers are HTML comments: they stay in the rendering of the document, where Markdown and HTML do not show them.
Older documents may use markers of the form <!--% type %-->. The editor
reads them, and writes them in the new form, with a name, when it saves.
What each type stores
Every type stores plain Texl text, so the document renders in any Texl tool:
richandmarkdownstore the same Markdown, which is why a line changes between the two without a change to its text. Equations stay as LaTeX between$signs.formulastores one<% %>tag.tablestores a Markdown table, with formulas in its fields.datastores one formula that builds the table with the Stilo library, one row per line. The name, the column names and the values are those of the editor:
<!--{ lod3 : data }-->
<% loads: stilo.dataframe {
columns: ["Case", "Fx (kN)", "Fy (kN)"],
rows: [
["ULS-1", 1.35 * Fx_k, 35],
["ULS-2", 1.5 * Fx_k, ""]
]
} %>
chartstores one formula that draws the chart with the Stilo library, one field per line. The X and Y values are formulas, the labels and the title texts:
<!--{ ch01 : chart }-->
<% stilo.charts.line {
x: sections.column "h (mm)",
y: sections.column "Mass (kg/m)",
x_label: "h (mm)",
y_label: "Mass (kg/m)",
title: "IPE sections"
} %>
A line above them in the document, hidden, imports the library:
<!--{ imp1 : formula | hidden }-->
<% texl.import "~/references/stilo.texlz/index.texl" ~> (lib -> bind "stilo" lib.data.stilo) %>
~ stands for the folder of the package. Other Texl
programs do not know this meaning of ~: stilo render does.
Formulas and names
Formulas are Texl tags, <% ... %>, anywhere in a cell. Texl computes a
document from top to bottom, so a name defined in a cell (L and q
above) is known in every cell below it, and not above it.
Writing documents with Texl describes the tags, and
The Swan language the language inside them.
Comments
<!--[ ... ]--> is a cell comment: a note about the cell it is in. It
moves with the cell, and the editor counts the comments of each cell in the
right margin. The text of a comment is free; a common habit is to start it
with your name.
Other HTML comments, <!-- ... -->, are neither markers nor cell
comments: they are text of the cell, like any other.
Rules for editing by hand
- Keep every marker on a line of its own.
- Keep cell names unique (compared without case). If two cells share a name, the editor leaves them as they are and reports the clash to the program that embeds it.
- A formula must open and close in the same cell. A
<%that only closes at a%>in a later cell makes the editor open the cells from the<%to the%>as one cell, and the file does not change. Close the formula, and they become separate cells again, with their types. A<%with no%>below it is plain text. - A marker line that you type or paste into a cell in the editor makes a new cell when you leave the cell.
Templates
A Texl template is ordinary text with tags. (In Stilo, a tag is called a
formula: the two words mean the same thing.) A tag starts with <% and ends
with %>, and contains an expression in the Swan
language. Rendering the template replaces each tag with the value of its
expression, and keeps the rest of the text as it is.
<% name = "Ada", items = 3 %>Dear <% name %>,
your order of <% items %> items has shipped.
renders as
Dear Ada,
your order of 3 items has shipped.
Templates can produce any kind of text: Markdown, HTML, configuration files, source code, e-mails. Texl does not care about the format; it only replaces the tags.
How rendering works
- The text outside the tags is copied to the output unchanged.
- The tags are evaluated in order, from the start of the template to the end.
- Each tag is replaced by its value, converted to text. A tag whose value is
Nothing, like an assignment, produces no text at all. - All the tags of a template share one set of names. A name bound in one tag is available in every later tag.
- If a tag's value is a promise, rendering waits until it resolves, then writes the resolved value.
Where templates come from
You write a template in a file with the .texl extension, usually in
Stilo, which also renders it, in the editor or with
stilo render. The program that renders a template is
called the host. Stilo is one; programmers can also render templates from
their own programs with the Texl libraries for Python, JavaScript and Rust
(see the Texl repository).
The host can also give your template data to work with, such as the name of the reader or a list of products. See Names and data.
A template that the host loads by its file name or URL is called a document. Documents can import other documents, to reuse a header or a library of functions.
What to read next
- Tags and output: how tags are written and how values become text.
- Names and data: where the names in your expressions come from.
- Conditions and repetition: optional text, lists and tables.
- Documents and imports: splitting your work into several files.
- Waiting for values: data that arrives later.
- Troubleshooting: when the output is not what you expect.
- A complete example: all of it together.
The expressions themselves are covered in The Swan language. You can write useful templates knowing only a few parts of it: literals, names, operators, conditions and functions.
Tags and output
Writing tags
A tag starts at <% and ends at the first %> that follows. Spaces inside
the tag are optional, and a tag can span several lines and contain comments:
<%
# Prices in euros
price = 12.5,
quantity = 4
%>Total: <%price * quantity%> euros
Total: 50 euros
A tag contains a single Swan expression. To do several things in one tag, separate the steps with commas (see Sequencing).
From values to text
Each tag is replaced by its value, converted to text:
| Value | Output |
|---|---|
| a text | the text itself, without quotes |
| a number | the number: 42, 3.5, -0.25 |
| a boolean | TRUE or FALSE |
Nothing | nothing at all |
| a tuple | its items, separated by , |
| a list | [[List of N]] |
| a namespace | [[Namespace of N]], or its own text |
| a function | [[Func]] |
| an undefined value | [[Undefined]] |
| a promise | its value, once it resolves |
<% "text" %> | <% 7 / 2 %> | <% 3 > 2 %> | [<% () %>] | <% 1, 2, 3 %>
<% [1, 2, 3] %> | <% {a: 1} %> | <% x -> x %> | <% "a" - 1 %>
text | 3.5 | TRUE | [] | 1, 2, 3
[[List of 3]] | [[Namespace of 1]] | [[Func]] | [[Undefined]]
The bracketed forms tell you that a value has no text form. To show the items
of a list, turn it into a tuple with list.enum, or join them with
text.join (see Conditions and repetition).
Namespaces with their own text
A namespace can say how it is written: give it a member __text__, a function
that receives the namespace and returns a text.
<% force = {value: 120, unit: "kN", __text__: f -> text.from f.value + " " + f.unit} %>
Horizontal load: <% Fx: force %>
Factored: <% 1.35 * Fx.value %> kN
Horizontal load: 120 kN
Factored: 162 kN
The tag <% Fx: force %> shows the force as text and also names it, so the
next line can still compute with Fx.value. This is how a
data table in Stilo shows as a
table and still gives its columns to other lines.
__text__ must return a text. If it returns anything else, such as a number,
the tag shows [[Undefined]].
Numbers
Numbers are written with as many digits as needed to represent them exactly, which sometimes shows the limits of floating-point arithmetic:
<% 0.1 + 0.2 %>
<% math.round ((0.1 + 0.2) * 100) / 100 %>
0.30000000000000004
0.3
Round values that come from calculations before showing them.
Tags that write nothing
A tag whose value is Nothing disappears. Assignments return Nothing, so a
tag that only binds names writes nothing:
<% greeting = "Hello" %><% greeting %>, world!
Hello, world!
Use : instead of = to bind a name and write its value:
The answer is <% answer : 6 * 7 %>. Again: <% answer %>.
The answer is 42. Again: 42.
Line breaks around tags
The text around a tag is kept exactly, including line breaks. A tag alone on a line leaves an empty line behind:
<% title = "Report" %>
# <% title %>
# Report
To avoid it, put the closing %> right before the next text, as the examples
in this manual do:
<% title = "Report" %># <% title %>
# Report
or start the next line inside the tag:
<% title = "Report"
%># <% title %>
# Report
Writing the delimiters as text
There is no escape for <% in the text of a template: it always starts a tag.
To write it, produce it from an expression:
Tags look like <% "<" + "%" %> ... <% "%" + ">" %>.
Tags look like <% ... %>.
Inside a tag, %> always ends the tag, even inside a text literal. Split it
the same way: "%" + ">".
Swan text literals cannot contain a double quote. Write quotes in the text around the tags instead:
<% name = "Ada" %>She said "<% name %>".
She said "Ada".
Unfinished tags
If a <% has no matching %>, the rest of the template, from the <% on, is
copied to the output as it is.
Names and data
The expressions in your tags use names: price, customer.name,
text.upper. A name can come from four places.
The names you bind
A tag can bind names with = or :, and every later tag of the same
template can use them. It is common to bind the values a template needs in a
first tag:
<%
company = "Acme",
year = 2026,
copyright = "© " + text.from year + " " + company
%>Contact <% company %> for details.
<% copyright %>
Contact Acme for details.
© 2026 Acme
Functions work the same way. Define them once, and call them in later tags:
<% money = n -> "$" + text.from (math.round (n * 100) / 100) %>Subtotal: <% money 19.999 %>
Tax: <% money (19.999 * 0.2) %>
Subtotal: $20
Tax: $4
Built-in names
Every template can use the built-in library:
text, list, math, time and the other namespaces, plus TRUE, FALSE,
type and a few more. The engine adds the texl
namespace, which imports other documents.
Data from the host
The program that renders your template can bind globals: names with the data the template needs. Which globals exist depends on the host, so a template usually documents what it expects, for example in a comment at the top:
<%
# Expects:
# customer {name, email}
# orders a list of {id, total}
%>
Values from the host become Swan values: texts become Text, numbers
Numb, lists List, records namespaces, and functions Swan functions.
Stilo passes no globals of its own: in Stilo, data comes from the document
itself or from the documents it imports.
Names from other documents
A document can import another document and use the names it binds. See Using a library.
Missing names
A name that is not bound anywhere is Nothing, which writes nothing. This is
handy for optional data, but it also hides typos. Give optional names a
default with ;:
Hello, <% reader ; "guest" %>!
Hello, guest!
Scopes of templates and documents
Each rendering of a template gets its own scope for the names it binds, below the globals and the built-ins. Binding a global or built-in name in a template hides it for the rest of that template only.
An imported document is rendered in a scope of its own, below the globals and
the built-ins, not below the scope of the template that imports it: it cannot
read the importer's names, and the importer sees its names only through the
document's data (see
Each document has its own names).
Document-wide names
bind binds a name in the global scope of
the document, wherever it is called from: inside a function, or in the
callback of a promise. That is how a document makes a library available to its
later tags (see Using a library). A name bound
with bind is not visible in other documents, nor in later renderings. Like
the names bound with =, it is part of the document's data.
Conditions and repetition
Texl has no special tags for conditions or loops. A tag is an expression, so you use Swan's conditional operators and mapping to decide what to write.
Optional text
condition ? text writes text when the condition is true, and nothing
otherwise. condition ? text ; other writes other when it is false:
<% stock = 0, vip = TRUE %>Status: <% stock > 0 ? "in stock" ; "sold out" %><% vip ? " (priority shipping)" %>
Status: sold out (priority shipping)
Chain conditions for more cases:
<% size = n -> n < 10 ? "small" ; n < 100 ? "medium" ; "large" %><% size 5 %>, <% size 50 %>, <% size 500 %>
small, medium, large
Optional paragraphs
A text literal can span several lines, so a condition can produce a whole paragraph:
<% overdue = TRUE %>Thank you for your order.
<% overdue ? "
Your payment is overdue. Please pay within
seven days to avoid a late fee.
" %>
Best regards
Thank you for your order.
Your payment is overdue. Please pay within
seven days to avoid a late fee.
Best regards
Remember that Swan text cannot contain " and that %> ends the tag. For
longer optional parts, or parts with tags of their own, put them in a separate
document and import it conditionally.
Repeating text for each item
To write something for each item of a list:
- turn the list into a tuple with
list.enum; - map a function that makes the text for one item over the tuple, with
=>; - join the results with
text.join.
<%
fruits = ["apples", "pears", "plums"],
nl = "
"
%>Shopping list:
<% text.join nl (list.enum fruits => (f -> "- " + f)) %>
Shopping list:
- apples
- pears
- plums
Binding the line break to a name, like nl here, keeps the tags readable.
Without text.join, the items would be written separated by commas, the way
tuples are rendered.
The items are often namespaces, and the function picks their members. Numbers
must be converted with text.from before they are joined to text:
<%
nl = "
",
orders = [{id: "A-1", total: 25}, {id: "B-7", total: 140}],
row = o -> "| " + o.id + " | " + text.from o.total + " |"
%>| Order | Total |
|-------|-------|
<% text.join nl (list.enum orders => row) %>
| Order | Total |
|-------|-------|
| A-1 | 25 |
| B-7 | 140 |
text.template writes the same row
more simply. You write the row as text, with the names of the members
between braces, and it fills them in, numbers included:
<%
nl = "
",
orders = [{id: "A-1", total: 25}, {id: "B-7", total: 140}],
row = text.template "| {id} | {total} |"
%>| Order | Total |
|-------|-------|
<% text.join nl (list.enum orders => row) %>
| Order | Total |
|-------|-------|
| A-1 | 25 |
| B-7 | 140 |
Empty lists
list.enum [] is Nothing, so an empty list writes nothing. To write a
message instead, test the size:
<% items = [] %><% list.size items == 0 ? "No items." ; text.join ", " (list.enum items) %>
No items.
Filtering
A function that returns Nothing for some items drops them, because
Nothing disappears from tuples:
<%
orders = [{id: "A-1", total: 25}, {id: "B-7", total: 140}],
big = o -> o.total > 100 ? o.id
%>Large orders: <% list.enum orders => big %>
Large orders: B-7
Totals
Swan has no loop and no built-in sum, but a short recursive function does the job:
<%
sum = xs -> list.size xs == 0 ? 0 ; xs 0 + sum (list.tail 1 xs),
totals = [25, 140, 60]
%>Total: <% sum totals %>
Total: 225
The recursion stops at the empty list, because the right side of ; is
evaluated only when it is needed. See
Evaluation order.
Reusable helpers
Collect the helpers you use often in a first tag, or in a library document that every template imports (see Using a library):
<%
nl = "
",
bullets = items -> text.join nl (list.enum items => (i -> "- " + text.from i)),
plural = (n, word) -> text.from n + " " + word + (n == 1 ? "" ; "s")
%><% plural (3, "file") %> changed:
<% bullets ["README.md", "main.rs", "lib.rs"] %>
3 files changed:
- README.md
- main.rs
- lib.rs
Documents and imports
A document is a template with a location: a file in your folder, or a URL. A document can import other documents, to reuse pieces of text (partials) or collections of functions (libraries).
Importing a document
texl.import(uri) loads the document at uri, renders it, and returns a
promise of a namespace with five members:
| Member | Content |
|---|---|
uri | the full location of the document |
source | its template text |
data | a namespace with the names its tags bound |
text | its rendered text |
tags | a list that describes each of its tags, in order |
Because the result is a promise, you use it with ~>:
texl.import(uri) ~> (doc -> ...) applies the function to the document once
it is loaded. The tag waits for the result before rendering continues.
Inserting a partial
Suppose partials/footer.texl contains:
Questions? Write to help@example.com.
This template inserts it:
Thank you for your order.
<% texl.import("partials/footer.texl") ~> (doc -> doc.text) %>
Thank you for your order.
Questions? Write to help@example.com.
The extra empty line is the line break at the end of the footer file, followed
by the line break after the tag. Use text.trim_tail to drop the first one:
Thank you for your order.
<% texl.import("partials/footer.texl") ~> (doc -> text.trim_tail doc.text) %>
Thank you for your order.
Questions? Write to help@example.com.
Each document has its own names
An imported document renders in its own scope. It sees the built-in names and
the host's globals, but not the names of the template that imports it, so it
renders the same whoever imports it. With partials/header.texl containing:
== <% title ; "Untitled" %> ==
the title of the importer does not reach it:
<% title = "Monthly report" %><% texl.import("partials/header.texl") ~> (doc -> text.trim_tail doc.text) %>
== Untitled ==
To produce a piece of text with data from the importer, write a function in a library, and call it with the data (see the next section).
Within one rendering, each document is loaded and rendered only once: later imports of it, even through a different relative path, return the same promise. The next rendering loads it again, so it sees the changes made to the document in between.
Using a library
A library is a document that binds functions and renders nothing. Suppose
lib/format.texl contains:
<%
# Formatting helpers. This document renders nothing.
plural = (n, word) -> text.from n + " " + word + (n == 1 ? "" ; "s"),
money = n -> "$" + text.from (math.round (n * 100) / 100)
%>
Its functions are in the data member of the document. Bind that namespace to
a global name with bind, and use it in the
following tags:
<% texl.import("lib/format.texl") ~> (lib -> bind "fmt" lib.data) %>You ordered <% fmt.plural (3, "book") %> for <% fmt.money 41.5 %>.
You ordered 3 books for $41.5.
This works because the import tag returns a promise, and rendering waits for
it: by the time the next tag runs, the callback has bound fmt.
For a single use, call the function inside the callback instead:
<% texl.import("lib/format.texl") ~> (lib -> lib.data.plural (1, "book")) %>
1 book
Locations
The uri of texl.import is resolved against the location of the importing
document, the way links work in a web page:
uri | Refers to |
|---|---|
footer.texl | a file in the same folder as the importing document |
partials/footer.texl | a file in a subfolder of that folder |
../shared/footer.texl | a file in a sibling folder |
/shared/footer.texl | a path from the root: the root of the web site on the web, the root of the file system for local files |
https://example.com/a.texl | a full URL (on the web) |
file:///home/me/a.texl | a full file URL (local files) |
A template that a program renders from a string resolves relative locations against the location the program gives it.
Imports inside an imported document are resolved against its location, not the location of the first template. So a partial can import its own neighbors with simple relative paths.
Missing documents
If a document cannot be loaded, the promise resolves to an
Undefined value, so a broken import shows instead of
silently rendering nothing:
Thank you for your order.
<% texl.import("missing.texl") ~> (doc -> doc.text) %>
Thank you for your order.
[[Undefined]]
Give a fallback with |. The fallback ; does not work here, because it only
replaces Nothing:
<% texl.import("missing.texl") ~> (doc -> doc.text | "(not found)") %>
(not found)
undef.inspect tells why. For a
failed load, op is "document.load", lhv is the full location of the
document and rhv is the reason, and description says it in plain words,
such as cannot load `https://example.com/a.texl`: HTTP status 404.
A failed load is not remembered, so a later import of the same document tries again.
Import cycles
A document that imports itself, directly or through other documents, would
wait for itself forever. Instead, the import that closes the cycle returns
Undefined, not a promise:
<% me = texl.import("cycle.texl") %>[<% me %>]
[[[Undefined]]]
(The example is rendered as the document cycle.texl.) In a chain where a
imports b and b imports a, the import of a in b returns Undefined,
and b renders without it.
What a document can see
A document is rendered:
- with the built-in names and the host's globals;
- with its own
texlnamespace, which imports relative to its own location.
It does not see the names of the template that imported it. bind and
label bind names in the global scope of the document, where every tag of the
document sees them but no other document does. Its data contains the names
its own tags bound, with =, :, bind or label, plus texl. It is taken
when the rendering ends and, like every namespace, it does not change
afterwards.
Waiting for values
Some values are not available right away: an imported document has to be loaded, and a host function may have to fetch data from a server. Such values are promises.
Tags that return a promise
When a tag's value is a promise, rendering stops at that tag until the promise resolves, writes the resolved value, and then continues with the rest of the template. You do not have to do anything special:
<% 20 ~> (n -> n + 1) %> is a promise of 21.
21 is a promise of 21.
Promises usually come from:
texl.import, which loads a document;- functions provided by the host, for example one that fetches data from a server.
Transforming the value
Use ~> to apply a function to the value before it is written. If a host
function fetch_rate returned a promise of an exchange rate, you would write:
1 EUR = <% fetch_rate "USD" ~> (rate -> text.from (math.round (rate * 100) / 100)) %> USD
Using the value in later tags
The function after ~> can bind the value to a global name with bind. The
tag waits for the promise, so the name is bound before the next tag runs:
<% 42 ~> (n -> bind "answer" n) %>The answer is <% answer %>.
The answer is 42.
This is the usual way to load a library.
Several promises
Rendering only waits for a tag whose value is a promise. A tuple that
contains promises is written right away, and a promise that is still pending
is written as [[Pending Promise]]:
<% promise.create (), 1 %>
[[Pending Promise]], 1
To wait for several promises, nest the callbacks, so that the tag returns a single promise:
<% texl.import("a.texl") ~> (a -> (texl.import("b.texl") ~> (b -> a.text + b.text))) %>
Or import them in separate tags, one after the other.
Promises never fail
A promise always resolves. When the work behind it cannot be done, for example
when a document cannot be loaded, the promise resolves to an
Undefined value. Use | to show a fallback, as
; only replaces Nothing.
An error made along the way is kept too. A function after ~> that fails gives a
promise of an Undefined value, and the tag shows it:
<% 1 ~> (x -> x - "a") %>
[[Undefined]]
Troubleshooting
Texl never stops with an error. When something goes wrong, the output shows it in one of the ways below.
The output contains [[Undefined]]
An operation in the tag was invalid. Find out which one by inspecting the
value with undef.inspect. Its
description says what went wrong in plain words:
<% e = undef.inspect ("Total" + 10) %><% e.description %>
cannot add the text `"Total"` and the number `10`
Here the sum of a text and a number is invalid. The fix is
"Total" + text.from 10.
pos tells where the error is, counted in bytes from the start of the
document, and uri tells which document it is in. An error made by a built-in
function points to its call.
A tag with a syntax error cannot inspect itself. A stray bracket or an unknown
character makes the whole tag [[Undefined]], and none of it runs, so the names
it binds stay unbound. To read the error, give the code to parse in another
tag:
<% e = undef.inspect (parse "(2 + 3)) * 4" {}) %><% e.description %>
unexpected `)`
The most common causes are:
- mixing types:
"Total: " + 10, or a number given to a text function; - a missing argument, which makes it
Nothing:add 3instead ofadd (3, 4); - calling the wrong value:
f g xinstead off (g x)(see pitfalls); - a syntax error, such as a missing or extra bracket, or a single-quoted text;
- a document that cannot be loaded: a wrong address in
texl.import(see Missing documents).
A value is missing
If a tag writes nothing where you expected a value:
- Check the spelling. A misspelled name is
Nothing, andNothingwrites nothing. - Check that the name is bound before the tag. Tags run in order, and a name bound in a later tag is not yet available.
- Check the host's globals. Is the data you expect actually passed to the template?
- Check
?conditions.cond ? valuewrites nothing when the condition is false.
Give optional names a default to make missing values visible:
<% customer.name ; "MISSING NAME" %>.
The output contains [[List of N]], [[Namespace of N]] or [[Func]]
The tag's value is a list, a namespace or a function, which have no text form.
- For a list, write its items:
list.enum items, ortext.join ", " (list.enum items). - For a namespace, pick a member:
customer.name. - For a function, you probably forgot to call it:
today ()instead oftoday.
The output contains [[Pending Promise]]
A promise inside a tuple, or inside another value, was not ready when the tag was written. Only a promise returned by the tag itself is awaited. See Several promises.
Values are separated by commas
The tag's value is a tuple, which is written as its items separated by , .
Often this is a sequence of steps whose intermediate values are not Nothing:
use = rather than : for the intermediate steps. To join items with another
separator, use text.join.
Unexpected empty lines
A tag alone on its line leaves the line break behind. See Line breaks around tags.
"recursion too deep"
A recursive function never reaches the case that stops it, or it calls itself more than a few hundred times. Check that the condition that ends the recursion is reached for every input. See Evaluation order and Recursion.
Part of the template is copied as it is
A <% without a matching %> makes the rest of the template plain text. A
%> inside a text literal ends the tag early. See
Writing the delimiters as text.
A complete example
This example renders an invoice in Markdown. It uses most of what the previous chapters describe: data in a first tag, a library, a partial, repetition and a condition.
The files
invoice/
├── invoice.texl
├── lib/
│ └── money.texl
└── partials/
└── letterhead.texl
invoice.texl
The main document. Its first tag binds the data; in a real application the host would pass it as globals. The next two tags import the library and the letterhead.
<%
# The data of the invoice. A real application would pass it as globals.
number = "2026-042",
date = time.from_string "2026-10-16",
customer = {name: "Ada Lovelace", city: "London"},
items = [
{what: "Analytical Engine manual", qty: 1, price: 120},
{what: "Punched cards (box)", qty: 3, price: 15.5},
{what: "Bernoulli tables", qty: 2, price: 40}
],
nl = "
"
%><% texl.import("lib/money.texl") ~> (lib -> bind "money" lib.data)
%><% texl.import("partials/letterhead.texl") ~> (doc -> doc.text) %>
# Invoice <% number %>
Date: <% text.head 10 (time.to_string date) %>
Bill to: <% customer.name %>, <% customer.city %>
<%
amount = item -> item.qty * item.price,
row = item -> "| " + item.what + " | " + text.from item.qty + " | "
+ money.format item.price + " | " + money.format (amount item) + " |"
%>| Item | Qty | Price | Amount |
|------|----:|------:|-------:|
<% text.join nl (list.enum items => row) %>
**Total: <% money.format (money.sum [list.enum items => amount]) %>**
<% list.size items > 2 ? "Thank you for being a loyal customer!" ; "Thank you!" %>
lib/money.texl
A library: it binds two functions and renders
nothing. sum is recursive.
<%
# Formats an amount with two decimals: 15.5 -> "$15.50"
format = n -> (
cents = math.round (n * 100),
rest = cents % 100,
"$" + text.from ((cents - rest) / 100) + "." + (rest < 10 ? "0" ; "") + text.from rest
),
# Adds up the numbers in a list
sum = numbers -> list.size numbers == 0 ? 0 ; numbers 0 + sum (list.tail 1 numbers)
%>
partials/letterhead.texl
A partial: plain text to insert at the top.
**Babbage & Co.** · 12 Dorset Street, London
Rendering it
With stilo render:
stilo render invoice/invoice.texl -o invoice.md
invoice.md contains:
**Babbage & Co.** · 12 Dorset Street, London
# Invoice 2026-042
Date: 2026-10-16
Bill to: Ada Lovelace, London
| Item | Qty | Price | Amount |
|------|----:|------:|-------:|
| Analytical Engine manual | 1 | $120.00 | $120.00 |
| Punched cards (box) | 3 | $15.50 | $46.50 |
| Bernoulli tables | 2 | $40.00 | $80.00 |
**Total: $246.50**
Thank you for being a loyal customer!
How it works
- The data tag binds
number,date,customer,itemsandnl, a line break used to join the rows. Each%>is placed right before the next text, so that the tags leave no empty lines (see Line breaks around tags). - The library is imported with
texl.import, and itsdatais bound to the global namemoneywithbind. Rendering waits for the import, so the later tags can callmoney.formatandmoney.sum. - The letterhead is inserted with its
text. It ends with a line break, which separates it from the title. - The table rows are produced by mapping
rowover the items and joining the results with line breaks. See Repeating text for each item. - The total maps
amountover the items, puts the results in a list, and adds them up withmoney.sum. - The closing line depends on a condition.
The imports use paths relative to invoice.texl, so they resolve the same
way whatever the current folder is.
The Swan language
Swan is the language you write inside Texl tags. It is small, dynamically
typed and expression-oriented: a Swan program is a single expression, and
evaluating it always produces a value. There are no statements, no keywords
and no exceptions. An invalid operation does not stop the program; it produces
an Undefined value instead.
This part of the manual describes the language. To learn how Swan fits into a template, start with Templates.
A quick tour
name = "Swan" # bind a name
"Hello, " + name + "!" # => "Hello, Swan!"
double = x -> x * 2 # define a function
double 21 # => 42
(1, 2, 3) => double # => (2, 4, 6)
[10, 20, 30] 1 # => 20
point = {x: 3, y: 4} # a namespace
point.x # => 3
math.sqrt (point.x ^ 2 + point.y ^ 2) # => 5
age = 20
age >= 18 ? "adult" ; "minor" # => "adult"
"hello" - 1 # => Undefined
Reading the examples
Each example block is a short session. The lines run in order, and names bound
on one line are available on the next. When a line ends with # =>, the text
after the arrow is the value of that line, written in Swan notation:
| Value | Written as |
|---|---|
| numbers | 42, 3.14, inf |
| text | "hello" |
| booleans | TRUE, FALSE |
| nothing | () |
| tuples | (1, 2, 3) |
| lists | [1, 2, 3] |
| namespaces | {x: 3, y: 4} |
| functions | Func |
| promises | Promise(42) |
| undefined values | Undefined |
A template shows some of these values differently. For example, a list renders
as [[List of 3]]. See Tags and output.
Trying Swan
The quickest way to evaluate Swan expressions is a template. Save this as
try.texl:
<% double = x -> x * 2 %><% double 21 %>
and render it with stilo render:
stilo render try.texl
42
Or open it in the Stilo editor, which shows the result of every line as you type.
Contents
- Syntax: comments, names and literals.
- Values and types: the ten types, truth values and comparison.
- Operators: every operator, its precedence and its meaning.
- Tuples: comma-separated values, and how operators work on them.
- Lists, text and namespaces: the collection types.
- Names and scopes: binding names, destructuring, scopes.
- Conditions and logic:
?,;,&,|and!. - Functions: definition, application, closures, composition.
- Promises: values that arrive later.
- Undefined values: how Swan reports errors.
- Common pitfalls: surprises worth knowing in advance.
- Built-in library: every built-in name.
Syntax
A Swan program is one expression, made of operands (names, literals and bracketed groups) joined by operators. This chapter describes the operands; Operators describes the rest.
Whitespace and comments
Spaces, tabs and line breaks separate tokens and are otherwise ignored, so an expression can span several lines.
A comment starts with # and runs to the end of the line:
x = 10 # bind 10 to x
x + 1 # => 11
Names
A name starts with a letter or _ and continues with letters, digits and _.
Names are case-sensitive.
total = 1
_tmp = 2
item2 = 3
Total = 4
total # => 1
Swan has no keywords. TRUE, FALSE and the built-in namespaces are ordinary
names bound in the global scope, so you can shadow them (but you rarely want
to). A name that is not bound evaluates to Nothing, not to an error:
not_bound_anywhere # => ()
Numbers
A number literal is a sequence of digits, with an optional fraction and an optional exponent. All numbers are 64-bit floating-point values.
42 # => 42
3.14 # => 3.14
1.5e3 # => 1500
2E-2 # => 0.02
A number cannot start or end with a dot, and cannot contain _. A negative
number is the - operator applied to a positive literal.
.5 # => Undefined
1_000 # => Undefined
-0.5 # => -0.5
Text
A text literal is enclosed in double quotes. It can span several lines.
"hello" # => "hello"
greeting = "Dear reader,
welcome."
text.size greeting # => 23
Text literals have no escape sequences: a backslash is an ordinary character, and a literal cannot contain a double quote. Single quotes do not delimit text.
"a\nb" # this is the four characters a, \, n, b
text.size "a\nb" # => 4
'single' # => Undefined
In a template, write quotes and other special characters in the text around the tags instead.
Brackets
| Brackets | Meaning |
|---|---|
( ... ) | Grouping. () alone is Nothing, the empty value. |
[ ... ] | A list of the values inside. |
{ ... } | A namespace of the names bound inside. |
(1 + 2) * 3 # => 9
() # => ()
[1, 2, 3] # => [1, 2, 3]
{a: 1, b: 2} # => {a: 1, b: 2}
Syntax errors
Swan never rejects a program with an error message of its own. A syntax
error anywhere in an expression, such as a missing closing bracket, a
misplaced operator, a stray ) or an unknown character such as @, makes
the whole expression Undefined, and none of it runs, not even its
assignments.
(1 + 2 # => Undefined, missing closing `)`
1 + * 2 # => Undefined, unexpected `*`
2 + 1e3 ) 1 # => Undefined, unexpected `)`
(1 @ 2) # => Undefined
x = 5, x + (2 + # => Undefined, and x is not bound
This holds inside brackets too, and in a part that would never be evaluated,
as in TRUE | (1 +. In a template each tag is read on its own, so a syntax
error spoils only its own tag.
See Undefined values to find out what went wrong.
Values and types
Every Swan value has one of ten types. The type function returns the name of
a value's type as text.
| Type | Example | Description |
|---|---|---|
Nothing | () | The absence of a value. It is also the empty tuple. |
Bool | TRUE, FALSE | A truth value. |
Numb | 42, 3.14 | A 64-bit floating-point number. |
Text | "hello" | A sequence of Unicode characters. |
Tuple | 1, 2, "three" | Two or more values separated by commas. |
List | [1, 2, 3] | An ordered sequence of values, indexed from 0. |
Namespace | {x: 1, y: 2} | A set of named values. |
Func | x -> x * 2 | A function, defined in Swan or built in. |
Promise | promise.create() | A value that may arrive later. |
Undefined | "a" - 1 | The result of an invalid operation. |
type 42 # => "Numb"
type "hello" # => "Text"
type [1, 2] # => "List"
type (x -> x) # => "Func"
type math.sqrt # => "Func"
type ("a" - 1) # => "Undefined"
type works item by item on tuples, like most functions. So type (1, "a")
is ("Numb", "Text"), and type () is (), not "Nothing".
type (1, "a") # => ("Numb", "Text")
type () # => ()
All values are immutable, namespaces included (see Namespaces), except promises: a promise receives its value once (see Promises).
Truth values
Conditions (?, &, |, !) convert their operand to a truth value. These
values are false:
FALSE0""(empty text)[](empty list){}(empty namespace)Nothing- every
Undefinedvalue - a pending promise
Every other value is true, including every function. A tuple is true if at least one of its items is true.
bool.from 0 # => FALSE
bool.from "0" # => TRUE
bool.from [] # => FALSE
bool.from (x -> x) # => TRUE
bool.any (0, "", 3) # => TRUE
A promise is false while it is pending and true once it is resolved, whatever its value:
p = promise.create ()
bool.from p # => FALSE
promise.resolve p 0
bool.from p # => TRUE
Equality
== and != compare values by content. Values of different types are never
equal.
1 == 1 # => TRUE
"a" == "a" # => TRUE
[1, [2]] == [1, [2]] # => TRUE
{x: 1} == {x: 1} # => TRUE
1 == "1" # => FALSE
- Two namespaces are equal if they have the same names with equal values, and were created in the same scope.
- A function is never equal to anything, not even to itself.
- Two promises are equal only if they are the same promise.
Equality between tuples works item by item and gives a tuple of truth values. To compare two sequences as a whole, compare them as lists:
(1, 2) == (1, 3) # => (TRUE, FALSE)
[1, 2] == [1, 3] # => FALSE
Order
<, <=, > and >= compare two values of the same type:
- numbers by value;
- text alphabetically, by Unicode code point (so
"Z" < "a"); - booleans with
FALSE < TRUE; - lists item by item; when one list is a prefix of the other, the shorter one comes first.
Nothing is less than every other value. Comparing values of different types,
or of an unordered type (functions, namespaces, promises), gives Undefined.
2 < 10 # => TRUE
"apple" < "banana" # => TRUE
"Z" < "a" # => TRUE
[1, 2] < [1, 2, 0] # => TRUE
() < -1000 # => TRUE
1 < "2" # => Undefined
Numbers
Numbers follow the IEEE 754 rules. Dividing by zero does not fail: it gives an
infinity, or "not a number" (NaN) for 0 / 0.
7 / 2 # => 3.5
1 / 0 # => inf
0.1 + 0.2 # => 0.30000000000000004
Use math.round, math.floor and the other math
functions to get whole numbers.
Converting values
| To | Use |
|---|---|
Text | text.from |
Numb | numb.from |
Bool | bool.from |
List | [value] (a tuple becomes the items of the list) |
Tuple | list.enum, text.enum, nspace.enum |
text.from 42 + "!" # => "42!"
numb.from "41" + 1 # => 42
[(1, 2, 3)] # => [1, 2, 3]
list.enum [1, 2, 3] # => (1, 2, 3)
Operators
Precedence
Operators with a higher precedence bind tighter. Use parentheses whenever the order is not obvious.
| Precedence | Operators | Meaning | Associativity |
|---|---|---|---|
| highest | +x -x !x $x | prefix operators | |
| 30 | x.y | subcontexting | left |
| 28 | f x | function application | left |
| 27 | x ^ y | power | right |
| 26 | x * y x / y x % y | product, division, modulo | left |
| 25 | x + y x - y | sum, subtraction | left |
| 24 | == != < <= > >= | comparison | left |
| 23 | x & y x | y | logical and, or | left |
| 22 | x ? y | conditional | left |
| 21 | x ; y | alternative | left |
| 15 | x -> y | function definition | right |
| 14 | f >> g g << f | composition | left |
| 13 | x => f | mapping | right |
| 13 | p ~> f | then | left |
| 12 | x = y x : y | assignment, labelling | left |
| lowest | x , y | pairing | left |
Some consequences:
double = x -> x * 2
double 2 + 3 # => 7, because application binds tighter than +
double (2 + 3) # => 10
2 ^ 3 ^ 2 # => 512, because ^ is right-associative
-2 ^ 2 # => 4, because prefix - binds tighter than ^
-(2 ^ 2) # => -4
x = 1, 2 # => 2, because , binds looser than =
x # => 1
Prefix operators bind tighter than everything, even . and application. Wrap
the operand in parentheses when it is more than a name or a literal:
-math.PI # => Undefined, because it means (-math).PI
-(math.PI) # => -3.141592653589793
Arithmetic
| Operator | Numbers | Text | Lists | Booleans |
|---|---|---|---|---|
x + y | sum | concatenation | concatenation | logical or |
x - y | subtraction | |||
x * y | product | logical and | ||
x / y | division | |||
x % y | remainder | |||
x ^ y | power |
Both operands must have the same type. Any other combination gives
Undefined. Swan never converts types implicitly.
12 + 2 * 3 # => 18
7 % 3 # => 1
-7 % 3 # => -1, the sign of the left operand
"Te" + "xl" # => "Texl"
[1, 2] + [3] # => [1, 2, 3]
"Total: " + 10 # => Undefined
"Total: " + text.from 10 # => "Total: 10"
Prefix -x negates a number. Prefix +x returns x unchanged, whatever its
type.
Comparison
==, !=, <, <=, > and >= compare two values and return TRUE or
FALSE. See Equality and Order for the
rules. Chained comparisons do not work: a < b < c compares a boolean with
c. Write a < b & b < c instead.
Logic and conditions
| Operator | Result |
|---|---|
!x | FALSE if x is true, TRUE if it is false. |
x & y | x if x is false, otherwise y. |
x | y | x if x is true, otherwise y. |
x ? y | y if x is true, otherwise Nothing. |
x ; y | x unless x is Nothing; then y. |
In all four, y is evaluated only if it is needed. &, | and ? test x
as a whole, even when it is a tuple: they do not work item by item.
Together, ? and ; make an if-else: cond ? then ; else. See
Conditions and logic.
Functions
| Operator | Result |
|---|---|
x -> y | A function with parameters x and body y. |
f x | f applied to x. Lists, text and namespaces can be applied too. |
f >> g | A function that applies f, then g to the result. |
g << f | The same function: g after f. |
x => f | f applied to each item of the tuple x. |
See Functions.
Names and namespaces
| Operator | Result |
|---|---|
x = y | Binds the name(s) x to y, and returns Nothing. |
x : y | Binds the name(s) x to y, and returns y. |
ns.x | Evaluates the expression x inside the namespace ns. |
$x | The value of the name x in the outermost scope that binds it. |
See Names and scopes and Namespaces.
Tuples and promises
| Operator | Result |
|---|---|
x , y | A tuple of the items of x followed by the items of y. |
p ~> f | A promise of f applied to the value of the promise p. |
Operators on tuples
All binary operators except ,, ;, =, :, ->, => and ~> work item by
item when an operand is a tuple. The prefix operators - and ! do too.
(1, 2) + (10, 20) # => (11, 22)
-(1, 2) # => (-1, -2)
A single value counts as a tuple of one item. It is not repeated to match the other operand, so use mapping to apply the same operation to every item:
(1, 2, 3) * 10 # => (10, Undefined, Undefined)
(1, 2, 3) => (x -> x * 10) # => (10, 20, 30)
See Operations on tuples for the details.
Tuples
A tuple is a sequence of values separated by commas.
1, 2, "three" # => (1, 2, "three")
(1, "b") # => (1, "b")
Tuples are how Swan passes several arguments to a function, returns several results, and applies an operation to many values at once.
Tuples are flat
A tuple never contains another tuple or Nothing. When you build one, nested
tuples are flattened and Nothing items are dropped:
(1, (2, 3)) # => (1, 2, 3)
(1, (), 2) # => (1, 2)
There are no tuples of one item and no empty tuples: a single value is a
tuple of one item, and Nothing is the empty tuple.
(5) # => 5
((), ()) # => ()
A trailing comma is a syntax error:
(1, 2,) # => Undefined
To nest sequences, use lists, which keep their
structure: [[1, 2], [3]] is a list of two lists.
Sequencing
Because Nothing items disappear, a tuple whose items are assignments acts
like a sequence of steps. The assignments return Nothing, so only the last
value remains:
x = 10, y = 5, x + y # => 15
This is the usual way to write a multi-step computation in one expression.
Operations on tuples
Most operators work item by item on tuples:
(10, 20) + (1, 2) # => (11, 22)
(1, 2) == (1, 3) # => (TRUE, FALSE)
!(0, 1) # => (TRUE, FALSE)
When the two tuples have different lengths, the shorter one is padded with
Nothing. Most operations between a value and Nothing are undefined:
(1, 2) + (10, 20, 30) # => (11, 22, Undefined)
A single value is a tuple of one item, so it is combined with the first item only:
(1, 2, 3) * 10 # => (10, Undefined, Undefined)
The conditions ?, &, | and ; are the exception: they look at their left
side as a whole. See Conditions on tuples.
To apply the same operation to every item, map a function over the tuple with
=>:
(1, 2, 3) => (x -> x * 10) # => (10, 20, 30)
Tuples and functions
A tuple passed to a function becomes its arguments:
add = (a, b) -> a + b
add (3, 4) # => 7
Built-in functions that take one value, such as math.sqrt or text.upper,
are applied to each item of a tuple:
math.sqrt (4, 9, 16) # => (2, 3, 4)
text.upper ("a", "b") # => ("A", "B")
Applying a tuple of functions applies each of them:
(math.floor, math.ceil) 2.5 # => (2, 3)
Working with items
Tuples have no indexing of their own. Put the tuple in a list to count or pick
items, and use list.enum to turn a list back
into a tuple:
t = (10, 20, 30)
[t] 1 # => 20
list.size [t] # => 3
list.enum (list.reverse [t]) # => (30, 20, 10)
How tuples render
In a template, a tuple renders as its items joined by ", ":
<% 1, 2, "three" %>
1, 2, three
To join items with another separator, use
text.join.
Lists, text and namespaces
Lists
A list is an ordered sequence of values, written in square brackets.
nums = [10, 20, 30]
nums # => [10, 20, 30]
[] # => []
The brackets enclose an expression, usually a tuple, and the list contains its
items. Since tuples are flat, a tuple inside the brackets adds its items
directly, and Nothing adds nothing. A list inside a list stays a single item:
[1, (2, 3)] # => [1, 2, 3]
[1, (), 2] # => [1, 2]
[[1, 2], [3]] # => [[1, 2], [3]]
Getting items
Apply a list to a number to get the item at that position. Positions start
at 0. A position that is negative, fractional or past the end gives Nothing.
nums = [10, 20, 30]
nums 0 # => 10
nums 2 # => 30
nums 10 # => ()
nums (0, 2) # => (10, 30)
Combining and transforming
+ concatenates lists. The list namespace has functions
to measure, search and slice them.
nums = [10, 20, 30]
nums + [40] # => [10, 20, 30, 40]
list.size nums # => 3
list.find 20 nums # => 1
list.head 2 nums # => [10, 20]
list.reverse nums # => [30, 20, 10]
Lists are values: no operation changes a list. To process each item, turn the
list into a tuple with list.enum, map a function over it, and put the result
back in brackets:
prices = [5, 12, 20]
[list.enum prices => (p -> p * 2)] # => [10, 24, 40]
Text
Text values support + (concatenation) and comparison. Applying a text to a
number gives the character at that position, starting at 0. Positions count
Unicode characters, not bytes.
word = "swan"
word 0 # => "s"
word (1, 2) # => ("w", "a")
word 10 # => ()
"sw" + "an" == word # => TRUE
The text namespace has functions to measure, search,
slice, split and join text.
text.size "héllo" # => 5
text.upper "texl" # => "TEXL"
text.split "," "a,b,c" # => ("a", "b", "c")
Namespaces
A namespace is a set of named values, written in curly braces.
point = {x: 3, y: 4}
point # => {x: 3, y: 4}
The braces enclose an expression, which Swan evaluates in a new scope. Every name bound during that evaluation becomes a member of the namespace. The members can use the members defined before them, and the names around the namespace:
scale = 10
box = {width: 2, height: width * 3, area: width * height * scale}
box.area # => 120
You can bind members with : or =. Inside the braces, the separators are
just the comma operator, so any expression works, including definitions of
functions:
counter = {start = 1, next = n -> n + 1}
counter.next counter.start # => 2
Reading members
There are two ways to read a member:
ns.nameevaluatesnameinside the namespace. The right side can be any expression, and it can use all the members.ns "name"looks up the member called"name". The key is a text value, so it can be computed.
point = {x: 3, y: 4}
point.x # => 3
point.(x * y) # => 12
point "y" # => 4
key = "x"
point key # => 3
point "z" # => ()
The two differ for names that are not members. ns "name" only sees the
members of the namespace, while ns.name also sees the names of the place
where it is evaluated, like any other expression there. Members hide those
names:
point = {x: 3, y: 4}
scale = 10
point "scale" # => ()
point.(x * scale) # => 30
type point.math # => "Namespace"
x = 1
point.x # => 3
A namespace is just its members. It does not remember where it was created,
so ns.name does not see the names around that place:
make = () -> (secret = 1, {x: 2})
p = make()
p.secret # => ()
Reading a member of Nothing gives Nothing, so a chain of . stops safely
at the first missing link:
config = {}
config.server.port # => ()
Namespaces are immutable
A namespace cannot change after it is created: its members are the names bound
inside its braces, and nothing else. Binding a name inside a namespace with
. gives an undefined value and binds nothing. This also holds for the
built-in namespaces, such as text and math, so the built-ins work the
same everywhere:
point = {x: 3}
type (point.(y = 4)) # => "Undefined"
point # => {x: 3}
type (text.(size = 0)) # => "Undefined"
text.size "abc" # => 3
To get a namespace with more members, create a new one. Inside its braces,
. gives access to the members of the old one:
point = {x: 3}
point3d = point.{x: x, y: 4}
point3d # => {x: 3, y: 4}
A function call inside . still works as usual: its parameters and the names
its body binds are in its own scope, not in the namespace.
Inspecting namespaces
The nspace namespace lists and counts the members:
point = {x: 3, y: 4}
nspace.enum point # => ("x", "y")
nspace.size point # => 2
Namespaces as text
A namespace written into a template shows as [[Namespace of N]]. A member
named __text__ changes that: it is a function, and the text it returns, when
applied to the namespace, is the namespace's text:
kN = v -> {value: v, unit: "kN", __text__: q -> text.from q.value + " " + q.unit}
text.from (kN 120) # => "120 kN"
(kN 120).value * 1.35 # => 162
nspace.size (kN 120) # => 3, __text__ is a member like the others
The function receives the namespace as its argument, so one function serves
every namespace made by kN. It must return a text: anything else makes the
conversion Undefined. A template shows the namespace
the same way.
Names that start and end with two underscores, such as __text__, are
reserved for members with a special meaning like this one. Do not use them
for anything else.
Namespaces as modules
Namespaces group related functions, like the built-in math and text
namespaces:
geometry = {
square = side -> side * side,
circle = radius -> math.PI * radius ^ 2
}
geometry.square 3 # => 9
Names and scopes
Binding names
= binds a name to a value and returns Nothing. : does the same but
returns the value.
x = 10 # => ()
x # => 10
y : 20 # => 20
y # => 20
= is handy in a sequence of steps, where the Nothing disappears (see
Sequencing). : is handy when you want to keep the
value, for example to show it in a template and remember it at the same time.
Binding a name again replaces its value in the current scope. The left side of
= and : must be a name, a tuple of names, or (). Anything else gives
Undefined and binds nothing.
1 = 2 # => Undefined
Assignments do not chain: a = b = 1 and a : b : 1 give Undefined. Write
a = 1, b = 1 instead.
Destructuring
A tuple of names binds each name to the matching item:
(a, b) = (1, 2)
a # => 1
b # => 2
(a, b) = (b, a)
a # => 2
When there are more names than items, the extra names are bound to Nothing.
When there are more items than names, the last name receives all the remaining
items:
(first, rest) = (1, 2, 3)
first # => 1
rest # => (2, 3)
(p, q, r) = (1, 2)
r # => ()
The same rules apply to function parameters.
Unbound names
A name that is not bound anywhere evaluates to Nothing. This is not an
error, so a misspelled name silently gives Nothing. The
alternative operator turns that into a default
value:
title ; "Untitled" # => "Untitled"
title = "Report"
title ; "Untitled" # => "Report"
Scopes
A scope is a table of names. Each scope (except the outermost) has a parent, and looking up a name searches the scope itself, then its parent, and so on.
New scopes are created by:
- function calls: the body of a function runs in a new scope, whose parent is the scope where the function was defined;
- namespaces: the expression inside
{ }runs in a new scope, whose parent is the current scope. When it is done, the names bound in that scope become the members of the namespace; - subcontexting:
ns.exprevaluatesexprin a new scope whose names are the members of the namespacens, and whose parent is the current scope. Namespaces are immutable, soexprcannot bind names in it.
Binding a name always affects the current scope. Inside a function, =
creates a local name, even when an outer scope has the same name:
count = 0
increment = () -> (count = count + 1, count)
increment() # => 1
count # => 0
The outermost scopes hold the built-in names. Your code runs in a scope below them, so you can reuse a built-in name without changing the built-in.
Global names: bind and label
bind and label bind names in the global scope, the scope where top-level
code runs, wherever they are called from: inside a function, a namespace or
ns.expr. They never change a namespace. They take the name as text, which
makes them useful inside functions and in promise callbacks:
remember = v -> bind "last" v
remember 42
last # => 42
label "answer" 42 # => 42
answer # => 42
bind name value returns Nothing, like =. label name value returns the
value, like :. Both accept a tuple of names. See
Root names.
Lifting: $name
$name reads name from the outermost scope that binds it, skipping the
nearer bindings that hide it:
x = 1
f = () -> (x = 2, (x, $x))
f() # => (2, 1)
The operand of $ must be a name or a tuple of names.
Conditions and logic
Swan has no if statement. Conditions are written with two operators: ?
picks a value when a condition holds, and ; supplies an alternative when
there is no value.
Conditional: ?
cond ? value returns value if cond is true, and Nothing otherwise.
value is evaluated only if cond is true. See
Truth values for what counts as true.
TRUE ? "yes" # => "yes"
FALSE ? "yes" # => ()
"" ? "yes" # => ()
Alternative: ;
value ; other returns value, unless value is Nothing; then it
evaluates and returns other.
() ; "fallback" # => "fallback"
"value" ; "fallback" # => "value"
; only reacts to Nothing. Other false values, and Undefined values, are
returned as they are:
FALSE ; 5 # => FALSE
0 ; 5 # => 0
"" ; "empty" # => ""
If-else
cond ? a ; b combines the two: if cond is true, ? gives a and ;
keeps it; otherwise ? gives Nothing and ; replaces it with b.
age = 20
age >= 18 ? "adult" ; "minor" # => "adult"
Chain them for several cases. The conditions are tested from left to right:
grade = score -> score >= 90 ? "A" ; score >= 80 ? "B" ; "C"
grade 95 # => "A"
grade 85 # => "B"
grade 70 # => "C"
If the chosen value is itself Nothing, ; treats it as missing and moves on
to the alternative:
TRUE ? () ; "fallback" # => "fallback"
Evaluation order
The right side of ?, ;, & and | is evaluated only when it is needed.
The other side is never evaluated, so an assignment there does not happen:
x = 1
FALSE ? (x = 2) # => ()
x # => 1
This is also what stops a recursion. The recursive call can be on either side
of ;:
fact = n -> n <= 1 ? 1 ; n * fact (n - 1)
fact 5 # => 120
fact2 = n -> n > 1 ? n * fact2 (n - 1) ; 1
fact2 5 # => 120
And, or
a & b returns a if a is false, and b otherwise. a | b returns a if
a is true, and b otherwise. They return one of their operands, not
necessarily a boolean. b is evaluated only when it is the result.
TRUE & "hello" # => "hello"
0 & "hello" # => 0
0 | "world" # => "world"
"name" | "world" # => "name"
| is a convenient way to replace any false value, including 0, "" and
Undefined, with a default:
count = 0
count | "none" # => "none"
("a" - 1) | "error" # => "error"
& and | have the same precedence and associate to the left. When you mix
them, add parentheses.
Not
!x returns FALSE if x is true, and TRUE if it is false.
!TRUE # => FALSE
!0 # => TRUE
!"hello" # => FALSE
Like other operators, ! works item by item on tuples, so !() is (), not
TRUE.
Testing for Nothing
x == () does not test for Nothing, because == works item by item and
Nothing has no items. Put the value in a list instead: the list is empty
exactly when the value is Nothing.
x = ()
[x] == [] # => TRUE
[0] == [] # => FALSE
To replace Nothing with a default, use ;.
Conditions on tuples
Unlike most operators, ?, & and | do not work item by item on tuples.
They test their left side as a whole, and a tuple is true if at least one of
its items is true:
(FALSE, 0, 1) ? "yes" # => "yes"
(FALSE, 0) ? "yes" # => ()
(TRUE, FALSE, TRUE) ? (1, 2, 3) # => (1, 2, 3)
To filter a tuple, map it with a function that returns Nothing for the items
to drop:
nums = (5, 12, 8, 30)
nums => (n -> n > 10 ? n) # => (12, 30)
Functions
Defining functions
params -> body creates a function. Functions are values: you bind them to
names, pass them to other functions and return them from functions.
double = x -> x * 2
double 21 # => 42
The parameters can be:
- a name:
x -> x * 2; - a tuple of names:
(a, b) -> a + b; (), for a function that ignores its argument:() -> "hello".
The body is any expression. It is evaluated each time the function is called, not when it is defined.
-> binds looser than most operators, but tighter than ,, = and :.
Wrap the body in parentheses when it contains one of them:
f = x -> (y = x * 2, y + 1)
f 3 # => 7
Calling functions
Write the function, then its argument. Parentheses around the argument are only needed when it is more than a name or a literal:
double = x -> x * 2
double 5 # => 10
double(5) # => 10
double (2 + 3) # => 10
double 2 + 3 # => 7
Pass several arguments as a tuple, and no argument as ():
add = (a, b) -> a + b
add (3, 4) # => 7
hello = () -> "hello"
hello() # => "hello"
Arguments bind to parameters like a destructuring
assignment: missing arguments are Nothing, and the
last parameter collects any extra arguments.
first = (head, tail) -> head
first (1, 2, 3) # => 1
rest = (head, tail) -> tail
rest (1, 2, 3) # => (2, 3)
Application is left-associative: f g x means (f g) x, which applies f to
g. To apply f to the result of g x, write f (g x):
text.upper text.trim " hi " # => Undefined
text.upper (text.trim " hi ") # => "HI"
The same applies to a negative argument: f -1 is a subtraction. Write
f (-1).
Closures
A function remembers the scope where it was defined, and its body can use the names of that scope. It sees their current values when it runs:
rate = 2
convert = amount -> amount * rate
convert 10 # => 20
rate = 3
convert 10 # => 30
A function that returns a function makes a closure over its own parameters:
multiplier = factor -> (x -> x * factor)
triple = multiplier 3
triple 5 # => 15
The names a function binds while running are local to that call.
Recursion
A function can call itself through the name it is bound to:
fact = n -> n <= 1 ? 1 ; n * fact (n - 1)
fact 10 # => 3628800
The recursion stops because the right side of ? and ; is evaluated only
when it is needed. See Evaluation order.
A function can call itself a few hundred times: about 300 times in the web
editor, about 600 in stilo render. Deeper than that, or in a recursion
that never stops, the result is Undefined, described as "recursion too
deep".
count = n -> n == 0 ? 0 ; 1 + count (n - 1)
count 100 # => 100
count 1000 # => Undefined, recursion too deep
Currying
A function with several parameters can also be written as a function that takes the first parameter and returns a function that takes the next one. This lets you supply the arguments one at a time:
add = a -> b -> a + b
add 3 4 # => 7
increment = add 1
increment 10 # => 11
Most built-in functions with two parameters are curried this way, for example
text.find needle haystack and math.pow exponent base.
Mapping
items => f applies f to each item of the tuple items:
double = x -> x * 2
(1, 2, 3) => double # => (2, 4, 6)
(4, 9, 16) => math.sqrt # => (2, 3, 4)
With a tuple of functions, each function is applied to each item:
(1, 2) => (x -> x + 1, x -> x * 10) # => (2, 10, 3, 20)
Results that are Nothing are dropped, so => also filters:
(1, 5, 12, 3) => (n -> n > 4 ? n) # => (5, 12)
=> is right-associative: x => f => g means x => (f => g). To map twice,
add parentheses or compose the functions:
double = x -> x * 2
inc = x -> x + 1
((1, 2) => double) => inc # => (3, 5)
(1, 2) => (double >> inc) # => (3, 5)
To map over a list, turn it into a tuple first, and put the result back in a list if you need one:
[list.enum [1, 2, 3] => (x -> x * x)] # => [1, 4, 9]
Composition
f >> g is a function that applies f, then g. g << f is the same
function, written in the other direction ("g after f"):
inc = x -> x + 1
double = x -> x * 2
(inc >> double) 3 # => 8
(double << inc) 3 # => 8
(inc << double) 3 # => 7
Other callable values
Lists, text and namespaces can also be applied to an argument. This is how you read their items:
| Value | Argument | Result |
|---|---|---|
| a list | a number n | the item at position n |
| a text | a number n | the character at position n |
| a namespace | a text k | the member named k |
[10, 20, 30] 1 # => 20
"swan" 0 # => "s"
{a: 1} "a" # => 1
Applying a tuple of functions applies each of them to the argument:
(math.floor, math.round, math.ceil) 2.5 # => (2, 3, 3)
Applying any other value, such as a number, gives Undefined.
Evaluating code at run time
parse compiles a text into a function, which
evaluates the code in the namespace you apply it to:
area = parse "width * height"
area {width: 3, height: 4} # => 12
Promises
A promise stands for a value that may not be available yet, such as a document that is still loading. It starts pending and later resolves to a value.
Promises usually come from texl.import, which loads a
document, or from functions that the host provides. You can
also create them yourself with the promise namespace.
Swan promises are simple:
- A promise resolves at most once. Later attempts are ignored.
- A promise never fails. An
Undefinedvalue is not a failure: a promise holds it like any other value, and the function you give to~>receives it.
Using a value that arrives later
Swan code cannot stop and wait. Instead, you give the promise a function to
apply to its value. p ~> f returns a new promise, which resolves to f
applied to the value of p:
p = promise.create()
q = p ~> (x -> x * 2)
promise.resolve p 21
q # => Promise(42)
If p is already resolved, f runs immediately. Otherwise it runs when p
resolves. Several functions can wait on the same promise.
To chain several steps, write them one after the other. ~> is
left-associative, so p ~> f ~> g means (p ~> f) ~> g: g is applied to the
result of f:
p = promise.create()
q = p ~> (x -> x + 1) ~> (x -> x * 10)
promise.resolve p 1
q # => Promise(20)
A value that is not a promise is treated as an already resolved promise:
3 ~> (x -> x + 1) # => Promise(4)
A tuple of promises gives a tuple of new promises, and a tuple of functions gives one new promise per function.
Keeping the result
The function you pass to ~> runs later, possibly after the rest of the
expression. To make its result available to later code, bind it globally with
bind:
p = promise.create()
p ~> (v -> bind "result" v)
promise.resolve p "done"
result # => "done"
Promises in templates
When a tag of a template returns a promise, rendering waits until the promise resolves and writes its value. This is how a template uses an imported document:
<% texl.import("header.texl") ~> (doc -> doc.text) %>
The next tags run only after the promise resolves, so they can use what the callback bound. See Waiting for values.
Truth value
As a condition, a promise is false while it is pending and true once it is
resolved, whatever its value. So p ? x tests whether p has resolved, not
its value. To test the value, use it inside ~>:
p = promise.create ()
p ? "resolved" ; "pending" # => "pending"
q = p ~> (v -> v ? "yes" ; "no")
promise.resolve p FALSE
p ? "resolved" ; "pending" # => "resolved"
q # => Promise("no")
Undefined values
When an operation makes no sense, such as subtracting a number from a text,
Swan does not stop. The operation returns an Undefined value, which records
what went wrong, and the evaluation continues.
"hello" - 1 # => Undefined
type ("hello" - 1) # => "Undefined"
In a template, an undefined value renders as [[Undefined]].
Where they come from
- Operators applied to the wrong types:
"a" + 1,-"a",TRUE < 1. - Applying a value that cannot be applied:
5 3. - Built-in functions given the wrong arguments:
text.size 42. - Math results that are not numbers:
math.sqrt (-1). - Syntax errors:
(1 + 2,1 + * 2,2 + 3 ) 1. - A recursion that goes too deep, or never stops: "recursion too deep".
- Binding something that is not a name:
1 = 2. - Binding a name inside a namespace:
math.(pi = 3). undef.from, which wraps any value in an undefined value.texl.importof a document that cannot be loaded.- A function provided by the program that runs Texl (the host), when it fails.
An unbound name is not undefined: it is Nothing.
How they spread
Most operations with an undefined operand give an undefined result, so an error early in an expression usually shows in its final value:
("hello" - 1) + 5 # => Undefined
text.upper ("hello" - 1) # => Undefined
A few operations handle them like other values:
- An undefined value is false, so
?,&,|and!treat it as such. ;does not replace it, because it is notNothing.- A tuple keeps it as one of its items.
!("hello" - 1) # => TRUE
("hello" - 1) | 0 # => 0
("hello" - 1) ; 0 # => Undefined
(1, "a" - 1, 3) # => (1, Undefined, 3)
So | is the way to replace an undefined value with a default.
Finding out what went wrong
undef.inspect turns an undefined value into
a namespace that describes it:
err = undef.inspect ("hello" - 1)
err.type # => "BinaryOperation"
err.op # => "subtraction"
err.lhv # => "hello"
err.rhv # => 1
description gives the error in plain words, here: cannot subtract the number
1 from the text "hello". The other members depend on type:
type | Cause | Other members |
|---|---|---|
UnaryOperation | a prefix operator or a built-in function | op, val, pos |
BinaryOperation | a binary operator, an application or a failed load | op, lhv, rhv, pos |
Termination | the expression ended before its bracket was closed | expected, pos |
Token | a character or token in the wrong place | token, pos |
Name | a name was expected | pos |
Value | created with undef.from | val |
HostError | a function of the host failed | error, pos |
op names the operation, such as "sum", "application", "text.size" or
"document.load". error is the text of the host's error.
pos is the position of the error, counted in bytes from the start of the
document, and uri is the document it is in. An error inside a function
imported from another document points into that document. An error made by a
built-in function points to its call. In code run with parse, pos counts
from the start of that code, and there is no uri. A value made with
undef.from has no position.
When an operand is itself undefined, undef.inspect describes it too, so you
can follow the chain back to the original error.
Creating undefined values
A function can return an undefined value to signal that its input was invalid.
undef.from wraps any value, such as a message,
into one:
safe_div = (a, b) -> b == 0 ? undef.from "division by zero" ; a / b
safe_div (1, 0) # => Undefined
(undef.inspect (safe_div (1, 0))).val # => "division by zero"
Common pitfalls
Each of these follows from the rules in the previous chapters, but they surprise most people at least once.
The comma binds loosest
x = 1, 2 binds 1 to x, then makes a tuple of Nothing and 2. Put a
tuple in parentheses to bind it:
x = 1, 2
x # => 1
x = (1, 2)
x # => (1, 2)
The same goes for function bodies: f = x -> a, b is (f = x -> a), b. Write
f = x -> (a, b).
Function bodies with = or :
A body that binds names must be in parentheses, because = binds looser than
->:
f = x -> y = x # => Undefined, and nothing is bound
f = x -> (y = x, y * 2)
f 4 # => 8
Application is left-associative
f g x applies f to g, then applies the result to x. Wrap the inner call
in parentheses:
type promise.create () # => Undefined
type (promise.create ()) # => "Promise"
Negative arguments
f -1 subtracts 1 from f. Write f (-1):
text.head -2 "swanky" # => Undefined
text.head (-2) "swanky" # => "swan"
Prefix operators bind tightest
-x.y means (-x).y, and !f x means (!f) x. Add parentheses:
-(math.PI) # => -3.141592653589793
!(bool.from 0) # => TRUE
A single value is not repeated over a tuple
(1, 2, 3) * 2 multiplies only the first item. Map a function instead:
(1, 2, 3) => (x -> x * 2) # => (2, 4, 6)
Comparisons on tuples give tuples
(1, 2) == (1, 2) is (TRUE, TRUE), not TRUE. Compare lists, or reduce
with bool.all:
[1, 2] == [1, 2] # => TRUE
bool.all ((1, 2) == (1, 2)) # => TRUE
; only replaces Nothing
FALSE ; 5 is FALSE, and an undefined value is not replaced either. Use |
to replace every false value:
FALSE ; 5 # => FALSE
FALSE | 5 # => 5
Conditions do not work item by item
?, & and | test a tuple as a whole, so ? does not filter a tuple:
(TRUE, FALSE) ? (1, 2) # => (1, 2)
Map the tuple instead. See Conditions on tuples.
Assignments do not chain
a = b = 1 and a : b : 1 give Undefined. Write a = 1, b = 1.
Text has no escapes
"\n" is a backslash and an n, and a text literal cannot contain ". Write
line breaks directly inside the quotes.
Unbound names are Nothing
A misspelled name gives Nothing, which renders as empty text. If a value is
unexpectedly missing, check the spelling first.
Mapping associates to the right
x => f => g means x => (f => g). Add parentheses around each step, or
compose: x => (f >> g).
Joining requires text
text.join takes a tuple of text values. Convert numbers first, and turn lists
into tuples:
text.join ", " (1, 2) # => Undefined
text.join ", " ((1, 2) => text.from) # => "1, 2"
text.join ", " (list.enum ["a", "b"]) # => "a, b"
Built-in library
Every Swan program starts with these names already bound:
| Name | Contents |
|---|---|
| Root names | TRUE, FALSE, type, parse, bind, label |
bool | Converting and combining truth values |
numb | Converting values to numbers |
text | Measuring, searching, slicing, splitting, filling in text |
list | Measuring, searching and slicing lists |
nspace | Inspecting namespaces |
math | Mathematical constants and functions |
time | Timestamps and calendar dates |
promise | Creating and resolving promises |
undef | Creating and inspecting undefined values |
In a template, the engine also binds texl, which imports other
documents, and the host can bind its own names (see
Names and data).
Reading the reference
Each entry starts with a signature that shows how to call the function and what it returns:
text.find needle haystack -> Numb
This reads: apply text.find to needle, then apply the result to
haystack, and you get a number. The description says what types the
arguments must have.
Curried functions
Functions with two parameters are curried: they take the first argument and return a function that takes the second. You can call them in one go, or keep the intermediate function:
text.find "l" "hello" # => 2
find_l = text.find "l"
find_l "world" # => 3
The first argument is the one you are most likely to fix in advance, such as
the separator of text.split or the exponent of math.pow. Note that
text.find ("l", "hello") passes a single tuple, not two arguments, and does
not work.
Tuples
Unless an entry says otherwise, functions are applied to each item of a tuple
argument and return a tuple of results. A Nothing argument gives Nothing.
text.upper ("a", "b") # => ("A", "B")
text.find ("l", "o") "hello" # => (2, 4)
text.upper () # => ()
Functions that reduce a tuple to one value, such as bool.all and math.max,
say so in their entry.
Errors
A function given an argument of the wrong type returns Undefined. The
undefined value names the function in its op member.
text.size 42 # => Undefined
(undef.inspect (text.size 42)).op # => "text.size"
Root names
These names are bound directly in the global scope.
TRUE, FALSE
TRUE -> Bool
FALSE -> Bool
The two boolean values. They are also available as bool.TRUE and
bool.FALSE.
TRUE & FALSE # => FALSE
type
type value -> Text
Returns the name of the type of value: "Bool", "Numb", "Text",
"List", "Namespace", "Func", "Promise" or "Undefined".
Like other functions, type is applied to each item of a tuple, so it never
returns "Tuple" or "Nothing": type (1, "a") is ("Numb", "Text"), and
type () is ().
type 42 # => "Numb"
type [1, 2] # => "List"
type text.size # => "Func"
type (1, "a") # => ("Numb", "Text")
parse
parse source -> Func
Compiles the Swan expression in the text source and returns a function. The
function takes a namespace and evaluates the expression inside it, so the
expression can use the members of the namespace and the built-in names, but
not the other names of the program. Like any expression inside a namespace,
it cannot bind names there.
The source is parsed once, when parse is called. A syntax error does not
make parse fail: the function returns Undefined when it runs. A source
that is not text gives Undefined, and so does applying the function to
something other than a namespace.
area = parse "width * height"
area {width: 3, height: 4} # => 12
area 42 # => Undefined
bind
bind name value -> Nothing
Binds name to value in the global scope, wherever it is called from, and
returns Nothing. name is a text, or a tuple of texts to bind several names
at once, following the rules of destructuring.
bind is how a function, or a callback waiting on a promise, makes a value
available to the rest of the program. It binds the name in the global scope
even when it is called inside a namespace: it never changes a namespace. In a
template, the global scope is the scope of the document, where its tags run.
f = () -> bind "seen" TRUE
f()
seen # => TRUE
bind ("a", "b") (1, 2)
a + b # => 3
label
label name value -> value
Like bind, but returns value instead of Nothing, the way :
differs from =.
label "answer" 42 # => 42
answer # => 42
bool
Converting and combining truth values. See Truth values for the rules.
bool.TRUE, bool.FALSE
bool.TRUE -> Bool
bool.FALSE -> Bool
The two boolean values, the same as the root names TRUE and FALSE.
bool.TRUE == TRUE # => TRUE
bool.from
bool.from value -> Bool
Returns the truth value of value: FALSE for FALSE, 0, "", [], {},
undefined values and pending promises, TRUE for everything else.
bool.from 0 # => FALSE
bool.from "no" # => TRUE
bool.from (0, 1) # => (FALSE, TRUE)
bool.any
bool.any items -> Bool
Returns TRUE if at least one item of the tuple items is true. It reduces
the whole tuple to one value, so bool.any () is FALSE.
bool.any (0, "", 3) # => TRUE
bool.any (0, "") # => FALSE
bool.all
bool.all items -> Bool
Returns TRUE if every item of the tuple items is true. It reduces the
whole tuple to one value, so bool.all () is TRUE.
bool.all (1, "a") # => TRUE
bool.all (1, 0) # => FALSE
bool.all ([1, 2] == [1, 2], 3 > 2) # => TRUE
numb
Converting values to numbers.
numb.from
numb.from value -> Numb
Converts value to a number:
- a number is returned unchanged;
TRUEis1andFALSEis0;- a text is read as a number literal, which may have a sign, a fraction and an
exponent. The text must contain nothing else, not even spaces.
"inf"and"NaN"are not numbers.
Any other value, and a text that is not a number, gives Undefined.
numb.from "42" # => 42
numb.from "-1.5e3" # => -1500
numb.from TRUE # => 1
numb.from " 42" # => Undefined
numb.from "NaN" # => Undefined
numb.from (text.trim " 42") # => 42
numb.from ("1", "2") # => (1, 2)
text
Measuring, searching, slicing, splitting, joining and filling in text. Positions and lengths count Unicode characters, not bytes, and start at 0.
text.from
text.from value -> Text
Converts value to text, the way a template renders it:
| Value | Text |
|---|---|
| a text | the text itself |
| a number | the number, such as 42 or 1.5 |
| a boolean | TRUE or FALSE |
| a list | [[List of N]] |
| a namespace | [[Namespace of N]], or the text its __text__ member returns |
| a function | [[Func]] |
| undefined | [[Undefined]] |
A promise gives Undefined. Use text.from to build text out of numbers,
since + does not mix types.
A namespace with a __text__ member, a function, gives the text that the
function returns when it is applied to the namespace (see
Namespaces as text). If it does not
return a text, text.from returns Undefined.
text.from 42 # => "42"
text.from 42 + "!" # => "42!"
text.from (1, TRUE) # => ("1", "TRUE")
text.size
text.size string -> Numb
Returns the number of characters in string.
text.size "hello" # => 5
text.size "héllo" # => 5
text.size "" # => 0
text.enum
text.enum string -> Tuple
Returns the characters of string as a tuple of one-character texts.
text.enum "abc" # => ("a", "b", "c")
text.lower
text.lower string -> Text
Returns string with every letter in lower case.
text.lower "TeXL" # => "texl"
text.upper
text.upper string -> Text
Returns string with every letter in upper case.
text.upper "TeXL" # => "TEXL"
text.trim
text.trim string -> Text
Returns string without the white space (spaces, tabs, line breaks) at its
start and end.
text.trim " padded " # => "padded"
text.trim_head
text.trim_head string -> Text
Returns string without the white space at its start.
text.trim_head " padded " # => "padded "
text.trim_tail
text.trim_tail string -> Text
Returns string without the white space at its end. It is handy to remove the
final line break of an imported document.
text.trim_tail " padded " # => " padded"
text.find
text.find needle haystack -> Numb
Returns the position of the first occurrence of the text needle in the text
haystack, or -1 if there is none.
text.find "l" "hello" # => 2
text.find "lo" "hello" # => 3
text.find "z" "hello" # => -1
text.rfind
text.rfind needle haystack -> Numb
Returns the position of the last occurrence of the text needle in the text
haystack, or -1 if there is none.
text.rfind "l" "hello" # => 3
text.head
text.head n string -> Text
Returns the first n characters of string. A negative n returns all the
characters except the last -n. A fractional n is truncated toward zero.
text.head 3 "swanky" # => "swa"
text.head (-2) "swanky" # => "swan"
text.head 10 "swan" # => "swan"
text.tail
text.tail n string -> Text
Returns the characters of string from position n on, that is, all but the
first n. A negative n returns the last -n characters. A fractional n
is truncated toward zero.
text.tail 4 "swanky" # => "ky"
text.tail (-3) "swanky" # => "nky"
Combined with text.rfind, it extracts the end of a path:
path = "docs/guide/intro.texl"
text.tail (text.rfind "/" path + 1) path # => "intro.texl"
text.split
text.split separator string -> Tuple
Splits string at every occurrence of the text separator and returns the
parts as a tuple. If separator does not occur, the result is string
itself.
text.split "," "a,b,c" # => ("a", "b", "c")
text.split ", " "red, green" # => ("red", "green")
text.split "," "abc" # => "abc"
text.join
text.join separator items -> Text
Joins the texts of the tuple items, putting separator between them. Every
item must be a text; otherwise the result is Undefined. items is taken as
a whole, so text.join returns a single text.
text.join "-" ("a", "b", "c") # => "a-b-c"
text.join "" ("a", "b") # => "ab"
text.join ", " ((1, 2) => text.from) # => "1, 2"
text.join ", " (list.enum ["x", "y"]) # => "x, y"
To join with line breaks, put a real line break between the quotes, since Swan text has no escapes:
<% text.join "
" ("first", "second") %>
first
second
text.template
text.template template -> Func
Returns a function that fills in template: applied to a namespace, it
returns the text of template with every {name} replaced by the member
name of the namespace.
line = text.template "{item}: {qty} pcs at {price} EUR"
line {item: "Bolt M16", qty: 40, price: 0.85} # => "Bolt M16: 40 pcs at 0.85 EUR"
- Each value is written as a tag writes it, without
text.from: numbers as0.85,TRUE, a tuple with its items separated by commas, a namespace by its__text__member. - A name that the namespace does not have gives an empty text, not an error.
{{and}}give a literal brace. Any other brace, as in{ a },{a.b}or{}, stays as it is written: a placeholder is a name, not a calculation.- Applied to a tuple of namespaces, the function returns a tuple of texts, one for each.
- Applied to anything other than a namespace, it returns
Undefined.
greet = text.template "Dear {name},"
greet {name: "Anna"} # => "Dear Anna,"
greet {} # => "Dear ,", no name, empty text
greet ({name: "Anna"}, {name: "Marco"}) # => ("Dear Anna,", "Dear Marco,")
text.template "{{name}}" {name: "Anna"} # => "{name}"
list
Measuring, searching and slicing lists. All the functions return new values; none changes a list.
list.size
list.size items -> Numb
Returns the number of items in the list items.
list.size [10, 20, 30] # => 3
list.size [] # => 0
list.enum
list.enum items -> Tuple
Returns the items of the list items as a tuple. An empty list gives
Nothing, and a list of one item gives that item. Use it to map a function
over the items of a list.
list.enum [10, 20, 30] # => (10, 20, 30)
list.enum [5] # => 5
list.enum [] # => ()
[list.enum [1, 2, 3] => (x -> x * 2)] # => [2, 4, 6]
list.reverse
list.reverse items -> List
Returns a list with the items of the list items in reverse order.
list.reverse [1, 2, 3] # => [3, 2, 1]
list.find
list.find item items -> Numb
Returns the position of the first item of the list items that is equal to
item, or -1 if there is none. Positions start at 0.
list.find 20 [10, 20, 30, 20] # => 1
list.find 99 [10, 20, 30] # => -1
list.find [1] [[1], [2]] # => 0
list.rfind
list.rfind item items -> Numb
Returns the position of the last item of the list items that is equal to
item, or -1 if there is none.
list.rfind 20 [10, 20, 30, 20] # => 3
list.head
list.head n items -> List
Returns the first n items of the list items. A negative n returns all
the items except the last -n. A fractional n is truncated toward zero.
list.head 2 [1, 2, 3, 4] # => [1, 2]
list.head (-1) [1, 2, 3, 4] # => [1, 2, 3]
list.head 10 [1, 2] # => [1, 2]
list.tail
list.tail n items -> List
Returns the items of the list items from position n on, that is, all but
the first n. A negative n returns the last -n items. A fractional n is
truncated toward zero.
list.tail 1 [1, 2, 3, 4] # => [2, 3, 4]
list.tail (-2) [1, 2, 3, 4] # => [3, 4]
nspace
Inspecting namespaces.
nspace.enum
nspace.enum ns -> Tuple
Returns the names of the members of the namespace ns, as a tuple of texts
sorted by Unicode code point (so capital letters come first). An empty
namespace gives Nothing.
nspace.enum {b: 2, a: 1, C: 3} # => ("C", "a", "b")
nspace.enum {} # => ()
Combine it with namespace application to list the values:
ns = {x: 1, y: 2}
ns (nspace.enum ns) # => (1, 2)
nspace.size
nspace.size ns -> Numb
Returns the number of members of the namespace ns.
nspace.size {x: 1, y: 2} # => 2
nspace.size {} # => 0
math
Mathematical constants and functions. They take and return numbers. A result
that is not a number, such as the square root of a negative number, is
Undefined.
Constants
math.PI -> Numb
math.E -> Numb
math.INF -> Numb
math.INFINITY -> Numb
math.PI is π, math.E is Euler's number e, and math.INF and
math.INFINITY are positive infinity. For negative infinity, write
-(math.INF).
math.PI # => 3.141592653589793
math.E # => 2.718281828459045
-(math.INF) # => -inf
Rounding
math.round x -> Numb
math.floor x -> Numb
math.ceil x -> Numb
math.trunc x -> Numb
math.abs x -> Numb
math.round rounds to the nearest whole number, and halfway cases away from
zero. math.floor rounds down, math.ceil rounds up, and math.trunc drops
the fraction. math.abs returns the absolute value.
math.round 2.5 # => 3
math.round (-2.5) # => -3
math.floor (-1.5) # => -2
math.ceil 1.2 # => 2
math.trunc (-1.7) # => -1
math.abs (-3) # => 3
To round to a number of decimals, scale first:
math.round (math.PI * 100) / 100 # => 3.14
Powers and logarithms
math.sqrt x -> Numb
math.exp x -> Numb
math.ln x -> Numb
math.log2 x -> Numb
math.log10 x -> Numb
math.pow exponent base -> Numb
math.log base x -> Numb
math.sqrt is the square root, math.exp x is e to the power x, and
math.ln, math.log2 and math.log10 are the logarithms in base e, 2 and
10.
math.pow and math.log are curried, and take the fixed part first:
math.pow exponent base is base ^ exponent, and math.log base x is the
logarithm of x in base base.
math.sqrt 16 # => 4
math.sqrt (-1) # => Undefined
math.log10 1000 # => 3
math.pow 2 5 # => 25
square = math.pow 2
(1, 2, 3) => square # => (1, 4, 9)
math.log 2 8 # => 3
Trigonometry
math.sin x -> Numb
math.cos x -> Numb
math.tan x -> Numb
math.asin x -> Numb
math.acos x -> Numb
math.atan x -> Numb
math.atan2 x y -> Numb
math.hypot x y -> Numb
The trigonometric functions and their inverses work in radians.
math.atan2 x y is the angle of the point (x, y) from the positive x
axis, between -π and π. math.hypot x y is the distance of the point
(x, y) from the origin.
math.sin 0 # => 0
math.cos math.PI # => -1
math.atan2 1 1 # => 0.7853981633974483
math.hypot 3 4 # => 5
Hyperbolic functions
math.sinh x -> Numb
math.cosh x -> Numb
math.tanh x -> Numb
math.asinh x -> Numb
math.acosh x -> Numb
math.atanh x -> Numb
The hyperbolic functions and their inverses.
math.cosh 0 # => 1
math.max, math.min
math.max numbers -> Numb
math.min numbers -> Numb
Return the largest and the smallest item of the tuple numbers. They reduce
the whole tuple to one value. Every item must be a number, and the tuple must
not be empty; otherwise the result is Undefined. If an item is NaN, not a
number, so is the result.
math.max (1, 5, 2) # => 5
math.min (1, 5, 2) # => 1
math.max (list.enum [3, 9]) # => 9
math.max () # => Undefined
math.max (1, 0 / 0) # => NaN
time
Timestamps and calendar dates. A timestamp is a number: the seconds elapsed since 1 January 1970 at 00:00 UTC, possibly with a fraction. Every date is in UTC.
time.now
time.now () -> Numb
Returns the current time as a timestamp. The argument is ignored.
time.now () > 1700000000 # => TRUE
time.to_date
time.to_date timestamp -> Namespace
Returns the calendar date of timestamp as a namespace with the members
year, month (1 to 12), day (1 to 31), hour, minute and second.
second keeps the fraction of the timestamp.
time.to_date 1780000000 # => {day: 28, hour: 20, minute: 26, month: 5, second: 40, year: 2026}
(time.to_date 0).year # => 1970
time.from_date
time.from_date date -> Numb
Returns the timestamp of the date described by the namespace date, which can
have the members year, month, day, hour, minute and second.
Missing members default to year 0, month 1, day 1 and 00:00:00, so always give
at least the year. A member beyond its range rolls over: month 13 is January
of the next year, and day 32 of January is February 1.
time.from_date {year: 2026, month: 1, day: 1} # => 1767225600
time.from_date {year: 1970} # => 0
time.from_date {year: 2026, month: 1, day: 32} # => 1769904000, 2026-02-01
time.to_string
time.to_string timestamp -> Text
Returns timestamp as an ISO 8601 text with milliseconds, such as
2026-05-28T20:26:40.000Z.
time.to_string 0 # => "1970-01-01T00:00:00.000Z"
time.to_string 1780000000.5 # => "2026-05-28T20:26:40.500Z"
time.from_string
time.from_string string -> Numb
Reads an ISO 8601 date and returns its timestamp. string is a date
YYYY-MM-DD, optionally followed by T (or a space) and a time HH:MM or
HH:MM:SS, with an optional fraction of a second and an optional final Z. A
missing time is midnight. Time zone offsets are not supported: the time is
always UTC. A text in another format, or with a field out of range, such as
month 13 or hour 25, gives Undefined.
time.from_string "2026-05-28" # => 1779926400
time.from_string "2026-05-28T20:26:40Z" # => 1780000000
time.from_string "28/05/2026" # => Undefined
time.from_string "2026-13-01" # => Undefined
time.week_day
time.week_day timestamp -> Numb
Returns the day of the week of timestamp, from 0 (Sunday) to 6 (Saturday).
time.week_day 0 # => 4
time.week_day 1780000000 # => 4
time.week_number
time.week_number timestamp -> Numb
Returns the ISO 8601 week number of timestamp, from 1 to 53. ISO weeks start
on Monday, and week 1 is the week that contains the first Thursday of the
year.
time.week_number 1780000000 # => 22
time.week_number (time.from_string "2027-01-01") # => 53
promise
Creating and resolving promises. To use the value of a
promise, use the ~> operator.
promise.create
promise.create () -> Promise
Returns a new pending promise. The argument is ignored.
p = promise.create ()
p # => Promise(pending)
promise.resolve
promise.resolve p value -> Nothing
Resolves the promise p with value, runs the functions waiting on p, and
returns Nothing. If p is already resolved, nothing happens. A tuple or an
undefined value is stored as it is.
If p is not a promise, the result is Undefined.
p = promise.create ()
q = p ~> (x -> x * 2)
promise.resolve p 21
p # => Promise(21)
q # => Promise(42)
promise.resolve p 99
p # => Promise(21)
undef
Creating and inspecting undefined values.
undef.from
undef.from value -> Undefined
Returns an undefined value that carries value, for example a message that
explains the error. The whole argument is wrapped, even a tuple. Its
description is Custom undefined value: , followed by a short value as you
would write it, or by its type for any other value.
err = undef.from "not found"
type err # => "Undefined"
(undef.inspect err).val # => "not found"
(undef.inspect (undef.from {a: 1})).description # => "Custom undefined value: a namespace"
undef.inspect
undef.inspect u -> Namespace
Returns a namespace that describes the undefined value u. Its type member
names the kind of error, and description gives the error in plain words. The
other members depend on the type:
type | Members | Meaning |
|---|---|---|
UnaryOperation | op, val, pos | operation op failed on the operand val |
BinaryOperation | op, lhv, rhv, pos | operation op failed on lhv and rhv |
Termination | expected, pos | the expression ended before the closing bracket expected |
Token | token, pos | a token is in the wrong place |
Name | pos | a name was expected |
Value | val | created by undef.from |
HostError | error, pos | a function of the host failed, with the text of its error |
In a document, pos is the position of the error in bytes from the start of
the document, and uri is the location of that document; an error made by a
built-in function has the position of its call. In code run with parse, pos
counts from the start of that code and there is no uri. A value made by
undef.from has neither. Operands that are themselves undefined are described
in the same way. If u is not undefined, the result is Undefined.
e = undef.inspect ([1] - 1)
e.type # => "BinaryOperation"
e.description # => "cannot subtract the number `1` from a list"
e.op # => "subtraction"
(e.lhv, e.rhv) # => ([1], 1)
(undef.inspect (text.size 1)).(op, val) # => ("text.size", 1)
texl
The texl namespace is bound by the Texl engine in every template. It is not
available in plain Swan.
texl.import
texl.import uri -> Promise
Loads the document at uri, renders it, and returns a promise of a namespace
that describes it:
| Member | Type | Content |
|---|---|---|
uri | Text | The full URI of the document |
source | Text | The template source |
data | Namespace | The names the document's tags bound |
text | Text | The rendered text |
tags | List | One namespace per tag, in the order of the source |
Each item of tags describes one tag, also a tag that writes nothing:
| Member | Content |
|---|---|
start | where the tag starts in source, in bytes |
end | where it ends in source, just after %> |
out_start | where its output starts in text, in bytes |
out_end | where its output ends in text |
value | the value that the tag wrote |
If the document cannot be loaded, the promise resolves to an Undefined value
with the operation "document.load", which says why (see
Missing documents). If the
import would close a cycle (a document importing itself, directly or through
other documents), texl.import returns Undefined instead of a promise.
A relative uri is resolved against the URI of the importing document, and
the fragment (#...) is ignored. The document renders in its own scope: it
does not see the names of the importer. Within one rendering, each document is
loaded and rendered at most once: importing it again, even through a different
relative path, returns the same promise. A load that failed is tried again.
If the server answers with a redirect to another address, the document is the
one at that final address: it is its uri, and its own relative imports start
from there. Imports through different addresses that lead to the same
document share it, and a document that imports itself through another address
is a cycle like any other.
texl.import exists only in documents. In a context created by a host
program to keep names across renders, texl has no import.
<% texl.import("partials/header.texl") ~> (doc -> doc.text) %>
See Documents and imports for the details.