stilo

API reference

The public API of the editor (web/src/editor/), for developers who embed the editor in a page or app, or write their own cell types. Everything below is exported by the entry point (web/src/editor/index.js, published as @onlabsorg/stilo-web/editor) unless noted. The API is young and will change before 1.0.

See also: the guide for a step-by-step introduction and the architecture for how the parts fit together.

Importing

import "@onlabsorg/stilo-web/editor";  // defines <texl-editor> and the built-in cells
import { TexlCell, registerCell } from "@onlabsorg/stilo-web/editor";

The editor is the entry point @onlabsorg/stilo-web/editor of the npm package @onlabsorg/stilo-web (npm install @onlabsorg/stilo-web). Only the package’s entry points are its interface; the files inside it may change without notice.

Importing the entry point has side effects: it registers the built-in cells and defines the custom element texl-editor (unless already defined). It also exports the built-in cell classes (TextCell, MarkdownCell, …), to extend them.

The package is plain ES modules. Use it with a bundler or dev server that resolves bare imports (e.g. Vite) and serve the page over HTTP: Texl loads a WebAssembly file. With Vite, exclude Texl from dependency pre-bundling (see the guide).

<texl-editor>

Class: TexlEditor (extends LitElement). Tag: texl-editor.

<texl-editor url="https://example.com/docs/report.texl" rows="50"></texl-editor>

The editor shows a document as a sheet of lined paper: one cell per line, with a left margin (line number and type icon) and a right margin (comment count). It owns the document: set it with value, read it back from value.

Properties and attributes

Property Attribute Type Default Description
value — string "" The document text. Setting it parses the document, names unnamed cells, resets selection and undo history, and starts a rendering pass. Reading it serialises the current cells.
url url string "untitled.texl" The URL of the document, resolved against the page URL. The document renders as the document at this URL: relative texl.import URIs resolve against its folder. It may change at any time: the editor renders again. The default puts an unsaved document in the page’s folder.
rows rows number 100 Lines on the sheet. The sheet shows more if the document has more cells.
readonly readonly (reflected) boolean false Read-only mode: the document can be viewed, selected, copied, and its comments and errors shown, but not changed. Keys, double clicks, the type menu, paste and cut that would change it do nothing, and the commands that change it (changes in editorCommands()) resolve to false. Setting it ends an edit, discarding it, and closes the type menu.
marks — object {} Marks in the right margin, by cell name in lowercase: {name: [{text, tone?, title?}]}; text is shown, tone (accent, warning, danger) colours it, title is its hover text. A click fires mark-click.
loader — function \| null null The loader of http and https URIs for the editor’s Texl engine (Texl’s addLoader): it takes a URL and returns the source, or {url, source} with the final URL, or a promise of either. Every texl.import goes through it, e.g. to send credentials. null: Texl’s own, a plain fetch. A new one renders again.
rendered — Promise<void> resolved The current rendering pass. Await it after setting value (or after a change) to read the rendered outputs. Read-only by convention.
errors — DocumentError[] [] The errors of the document, as of the last rendering (see Errors). Read-only.
selection — {line, cell} {line: 1, …} The selected line, from 1, and the name of its cell; cell is null for a line past the last cell, text before the first marker, and, when readonly, a cell read without a name (the name the editor gives it is never written, so it is no anchor for marks or comments kept elsewhere). With several lines selected, the line last moved to. Read-only.
editing — boolean false Whether a cell is in edit mode. Its edit is not in value until committed (the commit command). Read-only.
showHidden — boolean false Whether hidden cells (| hidden in their marker) are shown, greyed out, instead of out of sight. A view setting, not saved; the show-hidden command toggles it. Read-only.

The element sets tabindex="0" on itself if it has none, so it can take focus; call editor.focus() to give it the keyboard.

The editor scrolls its own lines (overflow-y: auto): give it a height (e.g. with flexbox or height: 80vh) to get a scrollbar that keeps the selected line in view.

Methods

Method Returns Description
runCommand(name) Promise<boolean> Runs an editor command by name: the same action as its key (see Commands). Resolves to true if the command ran, false if it does not apply now. Rejects for an unknown name.
renderedHtml({hidden} = {}) Promise<string> The document as rendered, once the current rendering pass is done: the HTML each cell shows (its type’s viewHtml, sanitised), in order, each in a <div class="texl-cell" data-cell="<name>" data-type="<type>">. Hidden cells are left out unless hidden is true; a cell being edited counts with its committed source. For an export or a print: equations need KaTeX’s stylesheet to look right outside the editor.
select(line, extend = false) — Selects line line (from 1), as a click on it does, and scrolls it into view; with extend, selects the lines from the anchor to it, as Shift+click does. The line is kept within the sheet. Closes the type menu; does not leave edit mode or take the focus. Fires selection-change if the line changed. A hidden line is selected too, and the hidden cells are shown (showHidden).
commands (getter) string[] The names runCommand takes, including make-<type> for every registered cell type.

Commands

The editor’s keys and runCommand run the same commands, so a page can offer them in its own menus and toolbars without faking key presses.

Name Key Does false when
edit Enter, F2 Edit the selected cell the sheet has no lines
commit Mod+Enter, in edit mode Commit the edit and leave edit mode. Marker lines outside tags in the new source make new cells not editing, or the edit is refused (inputError, or a tag that would run into a later cell): the cell stays in edit mode and shows why
discard Escape, in edit mode Discard the edit and leave edit mode not editing
insert-below Alt+Enter, Insert Insert an empty cell below the selection and select it —
insert-above Alt+Shift+Enter Insert an empty cell above the selection and select it —
move-up, move-down Alt+↑ / ↓ Move the selected cells one line at the top or bottom of the sheet, or a tag would run into a later cell (a notice says so)
delete Delete, Backspace Delete the selected cells —
copy Mod+C Copy the selected cells to the system clipboard, as Texl with markers the browser refuses the clipboard
cut Mod+X Copy, then delete the selected cells the browser refuses the clipboard
paste Mod+V Replace the selected cells with the clipboard’s the browser refuses the clipboard
undo, redo Mod+Z; Mod+Shift+Z, Mod+Y Undo or redo the last change to the cells nothing to undo or redo
cell-type Mod+/ Open the type menu on the selected line, or close it —
hide — Hide the selected cells (| hidden in their markers); the selection moves to the next line in sight no selected cell to hide (lines below the document are left out)
unhide — Unhide the hidden cells inside the selection: select the lines around them no hidden cell in the selection
show-hidden — Show the hidden cells, greyed out, or put them out of sight again —
comments Shift+F2 Fire comments-click for the selected line —
errors — Fire error-click for the selected line, with its first error —
make-<type> the type’s key, if any Change the selected line to <type> and edit it, as the type keys do the type refuses the line’s source: the line shows why (“Needs a table”)

While a cell is in edit mode, only commit and discard run; any other command resolves to false and does nothing. An open type menu is closed before a command runs (cell-type toggles it).

copy, cut and paste use navigator.clipboard, unlike the keys, which use the browser’s clipboard events. The browser allows it only after a user action, such as the click on a menu item that calls runCommand, and may ask the user before a paste.

editorCommands() (exported with the editor) lists the commands as the user sees them, in the order a list shows them, for a page that offers them in its own menus: {name, label, keys, group, cell?, changes?}. keys is the shortcut in the notation Mod+Shift+Z (Mod is Ctrl, or ⌘ on macOS), group is "Document" or "While editing a cell", cell marks a key of a cell’s own text editor (Mod+E, Shift+F2), listed for reference, which runCommand does not take, and changes a command that changes the document. The make-<type> commands follow the cell registry; their label is the type’s commandLabel.

toolbar.querySelector("#insert").onclick = () => editor.runCommand("insert-below");
commentList.onclick = (e) => {
    editor.select(Number(e.target.dataset.line));
    editor.focus();
};

Events

All events bubble and are composed.

Event detail Fired when
change none (Event) The cells changed by a user action: committed edit, insert, delete, move, paste, cut, type change, undo, redo. Not fired when value is set. Read editor.value for the new text.
selection-change {line, cell} The selected line changed. line counts from 1; cell is the name of its cell, or null (as selection). Also fired on the first render (line 1).
comments-click {line, comments} The user clicked a line’s comment icon, or pressed Shift+F2 on the selected line (also when it has no comments). comments is an array of strings: the trimmed text of each cell comment <!--[ ... ]-->.
errors-change {errors} A rendering finished. errors is the same list as the errors property. Fired after every rendering, also when nothing changed.
mark-click {line, cell, mark} The user clicked a mark in the right margin (marks). line counts from 1; cell is the cell’s name, mark the mark as given.
error-click {line, error} The user clicked a highlighted value (error is its error) or a line’s error icon (the line’s first error), or the errors command ran (error is null on a line with none). line counts from 1.
cell-menu {line, cell, x, y} A context menu was asked for on a line not being edited (a right click, the menu key, Shift+F10): the line is selected first, unless it is in the selection. cell is its cell’s name, or null; x, y the point a menu opens at (the cell’s corner for a key). Cancelable: a page that shows its own menu calls preventDefault(), and the browser’s menu does not open. Not fired while a cell is being edited, which keeps the browser’s menu.
name-conflict {conflicts} Several cells share a name (compared without case). Each conflict is {name, lines}, with lines counted from 1. Fired again only when the set of clashing names changes. The editor does not rename them.
editor.addEventListener("change", () => save(editor.value));
editor.addEventListener("comments-click", (e) => {
    showComments(e.detail.line, e.detail.comments);
});
editor.addEventListener("name-conflict", (e) => {
    for (const { name, lines } of e.detail.conflicts)
        console.warn(`"${name}" is used on lines ${lines.join(", ")}`);
});

Rendering

After value is set and after every change, the editor renders the whole document as the document at url, exactly as any other Texl host renders it, and splits the rendering into the cells’ outputs at their marker lines (see splitRendering). Each cell sees the names bound by the cells above it. Only the latest pass updates the cells; rendered is its promise, and it never rejects: if url cannot be resolved, the cells show no output. Errors in a cell never stop rendering: they show as [[Undefined]].

Errors

An error is an undefined value that a tag returned, directly or as an item of a returned tuple. An undefined value that was only assigned, or that sits inside a list or a namespace, is not one, and neither is Nothing (S7). The cell highlights each one, and the right margin shows the line’s count, with every returned value counted.

Values with the same origin and description are one DocumentError, however many lines return them. It is plain data, with no reference to the engine:

Property Type Description
key string Identifies the error; stays the same across renderings while the error stays.
description string What went wrong, in plain words. Parts between backticks are code.
rootCause string The description at the end of the chain of causes. It is the hover text of a highlighted value.
location ErrorLocation Where it was made. A value with no position, such as one from undef.from, points at the tag that returned it.
causes {description, location}[] The undefined values that caused it, outermost first. location is null for a value with no position.
lines number[] The lines that returned it, from 1.
count number How many values were returned, repeats included.

An ErrorLocation has uri (null for code run by Swan’s parse), local (whether it is this document), pos (an index in source), source (the text of that document), line (its line there, that is its cell, from 1, or null for parsed code) and textLine (the line of text within that cell, from 1, or null if the cell has only one or for parsed code). excerptAt(source, pos) gives {before, at, after}, the source line split around the position.

A value inside an attribute, such as the address of a link, shows as plain [[Undefined]]: it counts, but cannot be highlighted.

The editor creates its Texl engine on the first render, with no globals, and frees it when it leaves the page. The engine caches nothing: every pass fetches and renders the imported documents again (the browser’s HTTP cache still applies), so a changed imported document shows on the next pass.

TexlCell

Base class of all cells (extends LitElement). A cell is a view of its Texl source: the editor gives it texl and output, and the cell reports a new source with an event when an edit is committed. Subclass it to write a cell type; see Writing a cell type.

Static fields

Field Type Description
type string The type written in the marker (<!--{ name : type }-->). Required by registerCell.
label string The type’s name shown in the type menu and tooltips; the type if empty.
icon Lit html template A 24×24 SVG drawn with strokes (fill: none; stroke: currentColor are set by the editor). Shown in the left margin and the type menu.
key string The key that changes the selected line to this type and edits it ("=" for formula); empty for none. Not inherited: read as an own property. Shown in the type menu.
commandLabel string The label of its make-<type> command in editorCommands(), e.g. "Make it a formula and edit"; empty: “Change to label and edit”.
needs string What the type needs of a source, e.g. "a table"; empty if it accepts any. Shown as “Needs …” in the type menu and in the commit error.
requires {url, source} or null A document the type’s cells import: url, the imported path, and source, the tag that imports it. When a cell of the type is first written with content and no cell’s source mentions url, the editor adds a formula cell with source at the top of the document. null by default.
accepts(source) static method → boolean Whether the type can edit and show source. The base accepts any source; a type that needs a shape overrides it. White space and HTML comments around the content must not make it return false. The type menu offers the type only for cells whose source it accepts.
styles Lit css The cell’s styles: lined-paper layout, selected and edit looks. Extend it as [TexlCell.styles, css…].

Properties

Set by the editor; a cell reads them and does not change them.

Property Type Reflected Description
texl string no The cell’s Texl source (the body after its marker).
output string no The text Texl rendered from texl, with a private mark in place of each error (see renderView()).
errorMessages string[] no The hover text of the errors marked in output, by index.
mode "render" \| "edit" yes (mode attribute) Which of renderView() and renderEditor() is shown.
selected boolean yes (selected attribute) Whether the line is selected.
input any no The widget’s input while editing; not reactive. Set by fromTexl, read by toTexl. Its shape is up to the subclass.

Methods to override

Method Default Override to
fromTexl(texl) this.input = texl Read the widget’s input back from the Texl source. Called when the cell enters edit mode, before rendering.
toTexl() this.input ?? "" Produce the Texl source for the current input. Called on commit.
renderEditor() a “no editor” notice Return the editing widget (a Lit template).
static viewHtml(output, errorMessages) sanitizeOutput(output, errorMessages) of errors.js: sanitised with DOMPurify, marks shown as highlighted values Turn the output into HTML differently (as MarkdownCell does, with marked). Always pass the result through sanitizeOutput: documents are untrusted, and the marks are not meant to be seen. The editor’s renderedHtml() uses it too, so an export shows what the cell shows.
renderView() viewHtml(output, errorMessages) in a <div class="view"> Put something around the output (a box, an icon), or show it as something other than HTML. Prefer viewHtml for what the output becomes: renderedHtml() does not see renderView().
focusEditor() focuses the first textarea or input Focus your widget when it is not one of those. Called after entering edit mode.
inputError(texl) a message if the type does not accept texl, else "" Give a more precise reason (as FormulaCell does for %>). Called on commit with the new source, only if it changed.

Methods to call

Method Description
exitEdit(commit = true) Leaves edit mode. With commit, calls toTexl() and fires cell-change if the source changed; then fires cell-exit. A changed source that inputError() refuses, or commitError (a function the editor sets, for what depends on the rest of the document), is not committed: the cell stays in edit mode and shows the message below its widget. The editor calls it on Ctrl+Enter (commit) and Escape (discard); a cell may call it itself, e.g. from a “Done” button.

Events fired

These are the commit protocol between a cell and the editor. Pages do not normally listen to them; they listen to the editor’s change.

Event detail Meaning
cell-change {texl} The committed edit produced a new Texl source.
cell-exit none The cell left edit mode; the editor takes the focus back.

Keys

The editor handles Ctrl+Enter (Cmd+Enter on macOS) and Escape in edit mode, and the navigation keys outside it. A cell that handles a key itself must call preventDefault() on the keydown event: the editor ignores events that are already default-prevented.

TextCell

Type text, label “Text”. Extends TexlCell. A Texl template edited as source in a CodeMirror 6 editor and shown as HTML. Also the fallback for unregistered types: their source is shown and edited as text, and their type is kept on save.

Extension points

Method Description
languageExtensions() CodeMirror extensions for the input’s language. The default is Swan highlighting of tags (swanTags()) and the keymap for Mod+E and Shift+F2. Override to add a language, and include super.languageExtensions() to keep them.
editorExtensions() All CodeMirror extensions of the view: history, selection drawing, line wrapping, languageExtensions(), the default keymap (without Mod+Enter and Escape) and the listener that updates input. Override rarely.
import { TextCell, registerCell } from "@onlabsorg/stilo-web/editor";
import { html as htmlLanguage } from "@codemirror/lang-html";  // npm install @codemirror/lang-html

class HtmlCell extends TextCell {
    static type = "html";
    static label = "HTML";
    languageExtensions() {
        return [htmlLanguage(), super.languageExtensions()];
    }
}
registerCell(HtmlCell);

RichCell

Type rich, label “Rich text”, key r. Extends MarkdownCell: it has the same source and shows it the same way, and edits it with ProseMirror, with a toolbar. Tags show as chips with their value, from tagOutputs, a Map from a tag’s source to its output that the editor sets on every cell. New cells and empty lines are rich. accepts(source) is true only if the source can be written back with the same meaning. See Rich text.

MarkdownCell

Type markdown, label “Markdown”. Extends TextCell. Adds Markdown highlighting in the editor (tags stay highlighted as Swan; Markdown does not look inside them) and shows its output as Markdown, converted with marked and sanitised with DOMPurify. LaTeX equations in the Markdown, $...$ in the text and $$...$$ on lines of their own, are typeset with KaTeX.

TableCell

Type table, label “Table”. Extends MarkdownCell. Edits a Markdown pipe table as a grid of fields, one per table cell with its Texl source, and shows it as Markdown, equations included. Buttons above the grid insert and delete rows and columns, and align the current field’s column left, centred or right. accepts a table, or a source with only blank lines and comments (which starts a new table), with blank lines and comments before and after the table and in its rows. parseTable(source) reads a table ({rows, align, head, tail}, or null) and serializeTable(table) writes one.

FormulaCell

Type formula, label “Formula”. Extends TextCell. A source that is one tag, <% q * L ^ 2 / 8 %>, edited without the delimiters, Swan highlighted (swanExpression()), and shown as its output. accepts one tag or nothing, with white space and comments around it, which are kept. An expression containing %> is not committed. parseFormula(source) returns {before, body, after} (body is the text between the delimiters, or null without a tag), or null; serializeFormula(formula) writes it back.

DataCell

Type data, label “Data table”, key d. Extends GridCell (a MarkdownCell, as TableCell). A source that is one tag, <% loads: stilo.dataframe {columns: ["case", "Fx (kN)"], rows: [["ULS-1", 120], ...]} %> (the name and its colon are optional), edited as a name field and a grid: column names as plain text, each value as a Swan expression (an empty field is ""); shown as its output, the Markdown table of the Stilo library’s stilo.dataframe. Values that would break the row are marked as they are typed, and the cell does not commit while one is marked. accepts such a tag or a blank source (a new table), with white space and comments around the tag. requires the Stilo library: STILO_IMPORT, the tag that imports STILO_LIBRARY (~/references/stilo.texlz/index.texl). parseData(source) returns {before, after, name, columns, rows} (entries as Swan source), or null; serializeData(data) writes it back, one row per line; entryError(text) resolves to why a value cannot be an entry, or "" (the same as expressionError, below).

FormCell

Base of the cells edited as a form (not a type itself). Extends TextCell. A source that is one tag applying a function to a namespace, <% stilo.charts.line {x: [1, 2], y: [3, 4], title: "T"} %>, edited as a <texl-form> and shown as its output (sanitised HTML, like the base cell). A subclass sets:

accepts a blank source (a new form of the first kind) or such a tag whose function is one of forms, every member a field of it, each of a shape its field holds (a text or choice field a Swan text, a number field a number). An empty field writes no member; a required one, a text with " or %>, a field that is not a number, or an expression that would not parse refuse the commit. An unchanged form keeps its source as written. static readForm(source) returns {call, form, values}, or null. parseCall(source) returns {before, after, call, members} (members as [name, Swan source]), or null; serializeCall(call) writes it back, one member per line. expressionError(text) (from expression.js) resolves to why a Swan value cannot be written inside a tag’s list or namespace, or "".

ChartCell

Type chart, label “Chart”, key c. A FormCell with one kind for now, stilo.charts.line (“Line”), whose fields are x and y (required expressions that give lists), and x_label, y_label and title (text). Shown as the SVG image the Stilo library draws. requires the Stilo library, as DataCell.

<texl-form>

From web/src/editor/texl-form.js. A form: one line per field, the description on the left, the input on the right. Properties: fields, a list of {key, label, type, options?, placeholder?, required?} (type is "text", "choice" with options [{value, label}], "number" or "expression", the last in the monospaced font); values, the text of each input by key; errors, a Map from key to the reason a field is wrong (outlined, the reason as tooltip). Fires form-input with {key, value} on every change; focusField(key?) focuses a field (the first by default). ↑ and ↓ move between text boxes.

Cell registry

From web/src/editor/registry.js.

registerCell(cellClass, tagName?)

Registers a cell class under its static type and defines its custom element, texl-cell-<type> by default. Throws if the class has no type. Registering a type again maps it to the new tag; an already defined tag name is not redefined. Register cells before setting the editor’s value, or set it again afterwards: the editor picks the element for each cell when it renders.

registerCell(QuantityCell);                       // <texl-cell-quantity>
registerCell(QuantityCell, "my-quantity-cell");   // custom tag name

cellTagName(type)

Returns the tag name for a cell type, or the tag of the fallback type (text) if the type is not registered.

cellClass(type)

Returns the class registered for a type, or undefined.

cellTypes()

Returns the registered types, in registration order. This is the order of the type menu.

Rendering without an editor

renderHtml(source, {url, loader?, hidden?})

From web/src/editor/render.js. Renders the text of a document as the document at url and resolves to the HTML its cells show, the same as renderedHtml() of an editor holding it: sanitised, one <div class="texl-cell" data-cell data-type> per cell, hidden cells left out unless hidden. Imports are read with loader (as the editor’s loader) and resolve against url; a text that cannot be rendered gives cells without output. For a preview, or a document shown inside a page that is not an editor.

Document functions

From web/src/editor/document.js. Pure functions on the file format; the editor uses them, and hosts can use them to work on documents without an editor (e.g. on a server, in a preview, or to list comments).

CellData

{
    type: string;      // "text", "markdown", ...
    texl: string;      // the cell body: Texl source after the marker line
    name?: string;     // e.g. "bak7"
    marker?: boolean;  // false only for a leading cell without marker
}

parseDocument(source) → CellData[]

Splits a document into cells at marker lines <!--{ name : type }-->. Text before the first marker is a text cell with marker: false. Older markers <!--% type %--> are read too (without name). A marker line inside a tag is not a marker, so a tag always belongs to the cell it opens in.

parseDocument("Intro\n<!--{ bek4 : markdown }-->\n# Title\n");
// [ { type: "text", marker: false, texl: "Intro\n" },
//   { type: "markdown", name: "bek4", texl: "# Title\n" } ]

serializeDocument(cells) → string

Joins cells into a document; the inverse of parseDocument. The round trip is exact for documents in the current format. Every cell but the last ends with a line break.

tagSpans(source) → {start, end}[]

The tags of a source, as Texl reads them: from <% to the first %>. A <% with no %> after it is text.

spanningTag(cells) → {opens, reaches} | null

The first tag that would run from a cell into a later one, with the indices of the cell where it opens and of the first cell whose marker it swallows. parseDocument never gives such cells; changing them can. If you change cells in your own code, check them with this: the document would read differently when parsed again.

cellsFromSource(cell, texl) → CellData[]

The cells that cell becomes with the source texl: itself, and one more for each marker line outside a tag. A source that starts with a marker takes that marker’s name and type.

parseMarker(inner) → {type, name?}

Parses the text between <!--{ and }-->. Without a colon, only the type; an empty type is text.

formatMarker({type, name?}) → string

Formats a marker line: <!--{ bek4 : markdown }-->, or <!--{ markdown }--> without name.

cellName() → string

A new random name: consonant, vowel, consonant, digit (bak7), without the look-alikes l, 0 and 1.

nameCells(cells, taken?) → CellData[]

Gives a unique new name to every cell that has a marker but no name. taken lists names in use elsewhere. Existing names are kept, even when they clash. Returns cells itself when nothing needs a name.

nameConflicts(cells) → {name, lines}[]

The names used by more than one cell (compared without case) and the lines (from 1) of those cells.

isBlank(texl) → boolean

Whether a source holds nothing but white space and HTML comments (cell comments among them).

cellComments(texl) → string[]

The trimmed text of each cell comment <!--[ ... ]--> in a cell body. Other HTML comments are not cell comments.

for (const [i, cell] of parseDocument(source).entries())
    for (const comment of cellComments(cell.texl))
        console.log(`line ${i + 1}: ${comment}`);

splitRendering(doc, cells) → string[]

Splits a rendering into the outputs of its cells. doc is what engine.render returned for serializeDocument(cells), which may differ from the file’s text (e.g. line endings, or the older markers): render that, not the file. Only doc.text and doc.tags are read.

The places of the markers come from the tags’ positions, not from a search of the text, so whatever a tag outputs, marker lines included, stays content of the cell the tag is in. The leading cell without marker gets the text before the first marker. A marker inside a tag that spans cells is not in the rendering: its text goes to the last cell whose marker is, and the cell gets "". The line break that serializeDocument adds to a cell is not part of its output.

const doc = await engine.render("report.texl", serializeDocument(cells));
const outputs = splitRendering(doc, cells);

outputSpans(doc, cells) → {start, end}[]

The same split as positions in doc.text, one span per cell. A cell with no output of its own has an empty span.

Engine

createEngine(globals?, baseUrl?) → Promise<TexlEngine>

From web/src/editor/engine.js. Loads the Texl WebAssembly module on first use and returns a new TexlEngine from @onlabsorg/texl. globals is an object of names visible to every template; baseUrl is the absolute URL that relative document URLs resolve against (default: the page URL). The engine holds configuration only: each rendering starts from a new scope and fetches its imports again. Use it to render documents outside the editor with the same module the editor loaded:

import { createEngine, parseDocument, serializeDocument, splitRendering } from "@onlabsorg/stilo-web/editor";

const engine = await createEngine();
const cells = parseDocument(source);
const doc = await engine.render("docs/report.texl", serializeDocument(cells));   // imports resolve in docs/
const outputs = splitRendering(doc, cells);

See the Texl primer for the engine API.

Swan helpers

From web/src/editor/swan.js, for cells that use CodeMirror.

Export Description
swanTags() CodeMirror extension: highlights the Swan code in every <% %> tag, wherever it is (also in Markdown code blocks). Classes cm-texl-tag, cm-texl-delimiter, cm-swan-*.
swanExpression() CodeMirror extension: highlights a text that is all Swan, e.g. a formula’s expression. Classes cm-swan-*.
insertTag(view) CodeMirror command: wraps each selection (or the cursor) in <% %>.
insertComment(view) CodeMirror command: wraps each selection (or the cursor) in <!--[ ]-->.

swanTokens, findTags, TAG_OPEN and TAG_CLOSE are exported by web/src/editor/swan.js but not by the package entry point, so they are not part of the published interface.

Styling

The editor and cells use shadow DOM; style them with CSS custom properties (set on texl-editor or an ancestor) and parts. The editor does not load fonts: if the page does not load Atkinson Hyperlegible Next (e.g. from @fontsource-variable/atkinson-hyperlegible-next), the rendered text falls back to the next fonts in --texl-font.

Custom property Default Used for
--texl-paper #fff Sheet background
--texl-line #e4e6ea Rules between lines
--texl-line-height 2rem Minimum height of a cell
--texl-margin 6rem Width of each margin
--texl-margin-line #7aa2f0 The vertical margin lines
--texl-line-number #c4c8cf Line numbers
--texl-line-number-active #9aa0aa Line numbers, selected or hovered
--texl-accent #2563eb Edit bar, active menu icon, check mark
--texl-selected-bg rgb(37 99 235 / 0.05) Selected cell background
--texl-selected-ring rgb(37 99 235 / 0.35) Selected cell ring
--texl-edit-bg #f8f9fb Cell in edit mode
--texl-mono ui-monospace, monospace Font of the text editors
--texl-font "Atkinson Hyperlegible Next Variable", "Atkinson Hyperlegible Next", Verdana, sans-serif Font of the rendered text
--texl-heading-font --texl-font Font of rendered headings and table headers
--texl-font-size 0.97rem Size of the rendered text (headings scale with it)
--texl-table-inset 1em Margin of tables and figures on each side
--texl-math-size 1.08em Size of typeset equations, relative to the text
--texl-rule #1d2330 Heavier table rules (top, bottom, under the header)
--texl-text-muted #687085 List markers, quotations
--texl-comment #b7791f Comment icon and count
--texl-error #b91c1c Highlighted errors, error icon and count
--texl-error-bg rgb(220 38 38 / 0.1) Background of highlighted errors
--texl-hover-bg rgb(15 23 42 / 0.06) Hovered buttons in the margins
--texl-icon-active #4b5563 Hovered type icon
--texl-menu-bg, --texl-menu-border, --texl-menu-text, --texl-menu-icon, --texl-menu-active-bg light card Type menu
--texl-error #c2410c Why a commit was refused
Part Element
left-margin The left margin of each line
right-margin The right margin of each line
texl-editor {
    height: 80vh;
    --texl-margin: 4rem;
    --texl-accent: #0f766e;
}
texl-editor::part(right-margin) {
    background: #fafafa;
}

Keyboard

Mod is Ctrl, or Cmd on macOS. Most of these keys run an editor command, which a page can also run with runCommand.

Keys Outside edit mode
↑ / ↓ Select the line above or below
Shift+↑ / ↓, Shift+click Extend the selection
Enter, Ctrl+Enter, F2, double click Edit the selected cell
Alt+Enter, Insert Insert an empty cell below the selection
Alt+Shift+Enter Insert an empty cell above the selection
Alt+↑ / ↓ Move the selected cells
Delete, Backspace Delete the selected cells
Mod+C / X / V Copy, cut, paste cells (as Texl with markers)
Mod+Z; Mod+Shift+Z, Mod+Y Undo; redo
Mod+/ Open the type menu
Shift+F2 Fire comments-click for the selected line
=, r, t, m, T (a type’s key) Change the selected line to formula, rich text, text, Markdown or table and edit it; on a line of that type, edit it. If the type refuses the source, show why at the line
Keys In edit mode (text cells)
Mod+Enter Commit and leave
Escape Discard and leave
Mod+E Insert a <% %> tag
Shift+F2 Insert a cell comment

In the type menu: ↑ / ↓ or a type’s first letter pick, Enter or Space apply, Escape or Tab close.