04 Targets and plugins
A rule's output is a target name. The engine does not know what Mermaid is, and it must never learn. It knows HTML element names and it knows how to hand a node to a registered plugin.
1. Resolution order
#hidden,textreserved.- A registered plugin with that name (built-in Rust plugins, plus names the host registers
from JavaScript).
- A known HTML element name (allowlist in D43;
script,iframe,object,embed,style,link,meta,base,formare refused unless the host enablesunsafe_html). - Otherwise unknown:
<div class="self-unknown" data-target="NAME">content</div>(a<span>for inline rules) plus one diagnostic at the rule's line.
Attribute names are checked (no on*, no srcdoc ...) and URL attributes reject
javascript: and data: (except images on img src). Rejected attributes are dropped with
a diagnostic (D43).
2. Plugin interface
#A plugin is host code. Documents can only name it. Two halves:
Engine half (Rust, compiled in, optional per feature flag): runs at the end of parse
and transforms the AST node into new nodes, or into a Raw node of HTML, optionally with a
data-self-plugin attribute for the client half to hydrate.
Client half (JS, optional): runs in the browser after render, finds
[data-self-plugin=NAME] elements and enhances them (Mermaid, KaTeX, form bindings).
A plugin registered only in JS gets a generic engine marker:
<div data-self-plugin="NAME">escaped content</div> (<span> for inline rules).
A client half may also claim ordinary output by a CSS selector (the code highlighter claims
pre > code, D84); the engine output does not change.
Plugin {
name: "mermaid",
render(node, ctx) -> Nodes | Raw, // engine half, Rust
hydrate?(element, ctx), // client half, JS
editor?: { decoration?, foldable? } // hints for source mode
}
An engine half that reads its content from the node (its text child), never from the source
by span, says so (reads_node_text); only such a plugin may be the target of a rewrite rule
(02 §8, D255). A client half always reads the element's text, so it always may.
Attribute and content escaping is done by the engine before the plugin sees anything. A plugin that returns HTML is trusted host code; the document never was.
3. Built-in plugins (engine half, selfscribe-plugins crate features)
#| Target | Input | Output |
emoji | slot text smile | the emoji character from a bundled table, or the matched source text unchanged if unknown |
mermaid | verbatim body | <pre class="mermaid" data-self-plugin="mermaid"> for the client to render |
math | verbatim body | inline: <span class="self-math" data-self-plugin="math">; block: <div class="self-math self-math-display" data-self-plugin="math"> |
csv / tsv | verbatim body | a real <table> with <thead>; first row is header; delimiter from target name |
var | slot = variable name | value from host data, else set, empty if missing |
hidden | anything | nothing (the node stays in the AST for the editor) |
include | slot = path | resolver-loaded body of another .self, parsed under the current scope; its own rules block, if any, is laid over that scope for its body only, and its relative links read from its own folder (D263) |
data | verbatim body, info attribute | typed records (CSV, TSV, JSON, JSON Lines, records, or a project file), drawn as a view of themselves (§7) |
view | verbatim slot: source and options | a table, cards, board, list, calendar, timeline or form of a named source (§7) |
footref / footnote | slot = key / a note with key= | numbered references and notes, linked both ways (D87) |
citation / bibliography | @key items / a .bib path or data block name | author-year or numeric citations and a reference list (D88) |
equation / eqref | verbatim body with label= / a label | numbered display math and references to it (D89) |
numbered / ref | content with kind=, label=, caption=, name= / a label | numbered figures, tables, theorems and any kind, and references to them, equations included (D140) |
glossary / abbreviation | a definition with key= | a glossary entry (or nothing), and every use of the term marked <abbr> (D90) |
progress | a label | a bar counting the task checkboxes of its section (D91) |
An element target details with a summary attribute renders it as a <summary> child
(D86).
The input=KIND modifier is rendered by the core renderer: <input type="KIND"> prepended,
disabled unless the host enables forms. Plain-text plugin output (var, emoji) is
wrapped in a <span> only when the rule has classes or a style. Exact byte output: D45 to D49.
4. Client-side loading
#Mermaid, KaTeX and similar are loaded lazily by the JS package only when the rendered
document contains their data-self-plugin marker. The engine output is complete and static
without them (a Mermaid block is still a readable <pre>). No document can trigger a
network fetch by itself; the host decides which client plugins are installed.
Hosts may offer a catalog of client plugins the user switches on and off (D73). Enabling
is host state, never document state. embed, html and latex follow the policy in D74:
embeds load only on the user's click or for sites the user allowed, HTML runs in a sandboxed
frame with no network, and LaTeX is rendered by a local TeX installation in a restricted
mode.
5. Forms and templating
#Forms are ordinary rules in a scope plus the input= modifier and the var target:
~~~ selfscribe
scope form
line ? _ -> label input=text
line [ ] _ -> label input=checkbox
inline {{_}} -> var
~~~
@scope form
? Your name
[ ] Subscribe
Hello {{name}}
@end
Data binding (reading typed values back, mail-merge over a dataset) is host behaviour:
the JS package exposes bind(element, data) and collect(element) -> data (keyed by label
text). The document format stays static and declarative.
6. Document styles
#set style WORD ... is a variable (01 §2) that hosts read to give the whole page a look:
~~~ selfscribe
use markdown
set style dark wide numbered
~~~
| Group | Words |
| page | dark light paper |
| width and spacing | wide compact |
| type | serif sans mono justified |
| structure | numbered dropcap columns |
| looks | newspaper academic (and paper) |
| reset | none |
Words add up; in dark light paper and in serif sans mono the last one wins; a word
written with a look overrides that part of it. The engine's output does not change: hosts
wrap the document in .self-page.self-s-WORD > .self-doc and use the shared stylesheet
templates/styles.css, which works through document tokens so a rule's own { css } still
shows. What each host renders (preview, hybrid, site, CLI, print) is in D79.
The tokens a rule's { css } may read (D79, D131): --doc-bg, --doc-fg, --doc-muted,
--doc-heading, --doc-link, --doc-accent, --doc-border, --doc-code-bg, --doc-code-fg,
--doc-mark-bg, --doc-table-head, and the faces --doc-font (body), --doc-font-heading,
--doc-font-ui (a sans-serif for labels and badges) and --doc-font-mono (code).
Three more variables describe the page rather than its look (D117): `set page A4 landscape
margins wide (paper size, orientation and margins for pages, print, PDF and Word), set width
40em (the reading column, or full) and set lang en-GB` (the document's language). Like
style, they change what hosts do, never the engine's output. Two more are for editors only
(D126): set source-width full|reading|LENGTH (how wide Source mode shows the text) and `set
line-numbers on|off` (whether Source numbers the lines); a rulebook may set them for the
documents that use it.
7. Data and views
#Records live in the document as plain text, or in project files next to it, and a view shows
them. The built-in data template (use data) spells it:
~~~ selfscribe
use data
~~~
```data tasks as board by status
title, status:choice(todo|doing|done), due:date, hours:number, done:bool
Write the spec, doing, 2026-09-20, 5, no
Review fixtures, todo, 2026-09-24, 3, no
```
view: tasks as table sort due filter not done and due < 2026-10-01 sum hours
view: tasks as cards columns title, due
- A data block is
NAME [FORMAT] [from PATH] [VIEW OPTIONS]on the fence (from PATHreads aproject file, and a view can name one directly:
view: ./contacts.csv as cards); the body is CSV (default), TSV, a JSON array, JSON Lines orfield: valuerecords. An optional header gives columns types:text number date bool choice(a|b) list url. Dates are ISO 8601. Bad cells get a warning on the cell (D80). - A view is
view: SOURCEplus options:as table|cards|board|list|calendar|gantt|chart|form(
timelineisgantt),by,to(the end date of a range, D104),group,sort,filter(a small predicate language, D81),columns,page,search,title, totalscount sum avg min max, andbutton(below). as chart [bar|hbar|line|area|pie|donut]draws a total per category (D134):by COLUMNgivesthe categories (a date column by
day,week,month,quarteroryear, written after it;by monthalone is the first date column), the totals words give the values (countwhen there are none), andgroup COLUMNmakes a series per value. Filter, search and sort apply first;pagedoes not.button LABEL runs ACTION(D267), repeatable, puts a button on each record that runs thehost's action ACTION for it. LABEL is the words before
runs, or quoted text; ACTION is one word or quoted text. The engine checks only that shape and passes[label, action]pairs in the payload'sview.buttons. Its static output draws no button. The client draws them in a column at the end of a table and at the foot of each card or list line (a board's too), and not on a calendar, timeline, chart, form, map, flow, tiles or days. Each button carriesdata-self-action=ACTIONanddata-self-record, a JSON array of[column, value]pairs of the record (calculated cells included). A host that runs actions gives each cell to the action under its column's name, a run of spaces written-, andrecordascolumn: valuelines; a host that does not leaves the button inert.- The engine draws a static table, cards, board, list, calendar, timeline, chart, tiles or form, plus a JSON payload of
every record for the client half, which makes it interactive (D82). Its figures and dates follow
set currency,set datesandset langas the client's do. Edits made in a view go back to the text through the host, as one undo step (D83). view: sqlite …is reserved for a future read-only connector.
8. Encrypted blocks
#A secret block (D136) keeps part of a plain text file private. The file stays plain text;
the block's body is ciphertext, and the client plugin opens it with a passphrase. A document
adds block ` secret ... ` -> secret verbatim.
```secret
selfscribe-secret v1 aes-256-gcm pbkdf2-sha256 600000
salt: AAECAwQFBgcICQoLDA0ODw==
iv: oKGio6Slpqeoqaqr
a09uCTXTWS3rBxFLzoXZulufhWlZ16W7S8YUzjHXp/sPW8uNif1S7LtxieUvVC0l9n+6VHpP03I9
kjl7
```
Format v1. Lines are trimmed; blank lines and CR LF are ignored.
- Header, the first line:
selfscribe-secret, the versionv1, the cipheraes-256-gcm, the key derivationpbkdf2-sha256and its iteration count (decimal), separated by spaces. Readers compare the words without regard to case and refuse other values. - Fields,
name: valuelines:salt:(base64, 8 to 64 bytes; writers use 16 randombytes) and
iv:(base64, exactly 12 bytes). Readers skip fields they do not know. - Data, every other line joined: standard base64 (with
=padding) of the AES-GCM output,the ciphertext followed by the 16-byte tag. Writers wrap it at 76 characters.
Crypto.
- Key: PBKDF2-HMAC-SHA-256 over the passphrase in Unicode NFC, encoded as UTF-8, with the salt
and the iteration count of the header, 32 bytes. Writers use at least 600000 iterations; readers accept 1 to 10000000.
- Cipher: AES-256-GCM with the IV of the header, a 128-bit tag and no additional data.
- Plaintext: the block's inner text, UTF-8. Every save takes a fresh random IV. Saving an
existing block keeps its salt and count; a new block takes a new salt.
- A tag that does not verify means a wrong passphrase or changed data. Hosts say only "That
passphrase doesn't open it."
Opening a block without the app. Node 18 or later, standard library only:
node open-secret.mjs "harbour lights" < block.txt prints the example's plaintext, `The ferry
leaves at 06:40. and Locker code: 4729` on two lines.
// open-secret.mjs: prints the plaintext of a Selfscribe secret block read from stdin.
import { readFileSync } from "node:fs";
import { createDecipheriv, pbkdf2Sync } from "node:crypto";
const passphrase = process.argv.at(-1);
const lines = readFileSync(0, "utf8").split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !/^(```|~~~)/.test(l));
const [magic, version, cipher, kdf, iterations] = lines[0].split(/\s+/);
if (magic !== "selfscribe-secret" || version !== "v1" || cipher !== "aes-256-gcm" || kdf !== "pbkdf2-sha256") throw new Error("not a v1 block");
const fields = Object.fromEntries(lines.slice(1).filter((l) => /^[a-z][a-z0-9-]*\s*:/i.test(l)).map((l) => [l.slice(0, l.indexOf(":")).trim().toLowerCase(), l.slice(l.indexOf(":") + 1).trim()]));
const data = Buffer.from(lines.slice(1).filter((l) => !/^[a-z][a-z0-9-]*\s*:/i.test(l)).join(""), "base64");
const key = pbkdf2Sync(Buffer.from(passphrase.normalize("NFC"), "utf8"), Buffer.from(fields.salt, "base64"), Number(iterations), 32, "sha256");
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(fields.iv, "base64"));
decipher.setAuthTag(data.subarray(data.length - 16));
const plain = Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]);
process.stdout.write(plain.toString("utf8"));
Where the plaintext may go. A host shows it only inside the block's own drawing, keeps the key in memory only, and forgets it on Lock and after an idle time. Write-back replaces the whole body with new ciphertext, so the text and its undo history hold ciphertext only. Exports show the block as locked. Search, outlines and indexes read the text, so they see ciphertext.