SelfscribeDownloadOpen the app

02 The rule language

A rule says where something can match, what it looks like, and what it becomes. Optional words after that say how neighbours combine and how it is styled.

1. Short form (one line)

#
text
WHERE  PATTERN  ->  TARGET [attr=value ...] [slot ...] [modifiers ...] [{ css }] [as NAME]
selfscribe
~~~ selfscribe
inline  **_**             -> strong
inline  *_*               -> em
inline  `_`               -> code            verbatim
inline  [_](_)            -> a href=_2
inline  ![_](_)           -> img alt=_1 src=_2
inline  :_:               -> emoji
inline  ~~_~~             -> del
inline  ==_==             -> mark
line    # _               -> h1              fold 1
line    ## _              -> h2              fold 2
line    ### _             -> h3              fold 3
line    - _               -> li              group ul   nest
line    * _               -> li              group ul   nest
line    _#. _             -> li              group ol   nest
line    > _               -> p               group blockquote
line    | _ |             -> tr              group table  split "|" td
line    ---               -> hr
line    - [ ] _           -> li.task         group ul   input=checkbox
line    - [x] _           -> li.task.done    group ul   input=checkbox checked
line    // ! _            -> p.critical      { color: crimson; font-weight: 600 }
line    // ~ _            -> p.note          { color: steelblue }
block   ``` _ ... ```     -> code lang=_1    verbatim
block   ``` mermaid ... ``` -> mermaid       verbatim
block   ::: spoiler _ ... ::: -> details summary=_1
block   <!-- ... -->      -> hidden          verbatim
block   $$ ... $$         -> math            verbatim
word    TODO:             -> span.todo       { color: orange; font-weight: 600 }
~~~

Columns are separated by one or more spaces. -> is the only required separator (the first whitespace-delimited ->; write \-> for a literal arrow), so the pattern may contain single spaces (// ! _). Runs of spaces inside a pattern collapse to one; two literal spaces are written \ \ . After the target, attributes, slot tokens, modifiers, the { css } block and as NAME may come in any order.

A # preceded by two or more spaces and followed by a space or end of line starts a trailing comment, unless it is the first token after the keyword (so line # _ -> h1 is a heading rule) or inside quotes or braces.

2. WHERE

#
WHEREMatchesNotes
inlinea span inside a line's textmust start and end with a literal; slots are non-greedy up to the next literal and never empty
linea whole line, after indentationanchored at both ends; a trailing _ captures the rest of the line
blockan opening line, a multi-line body, a closing linepattern must contain ...
worda literal token, or a mark and one word, anywhere in text, outside verbatimat most two slots, each one word (§3); needs a literal; respects word boundaries on alphanumeric edges

Matching happens in that priority: block, then line, then inline and word inside the resulting text nodes. Inline never crosses a line boundary. Consecutive lines that no rule matches merge into one paragraph p.

3. PATTERN

#
  • Everything is literal except slots, the digit slot, ..., and ``.
  • The slot character is _ by default. _ is a capture slot, _1.._9 a numbered one.

    Slots are numbered left to right; _ alone means "the next number". At most 9 slots; two slots with no literal between them are an error.

  • _# is a digit slot: one or more ASCII digits. It is never content (_#. _ matches

    1., 2., 10.), but an attribute may read the first one as _# (value=_#, group-start=_#, D141).

  • set slot CHAR changes the slot character for the rules that follow it in the same

    file, so a Markdown-heavy file can write set slot $ and then **$**, \_\_$\_\_ becomes __$__. Attribute references use the same character (href=$2). The choice is per file; imports keep their own.

  • In a word pattern a slot matches one word (D133): letters, digits and _ (Unicode

    ones too), with -, ., : and / allowed between them, starting and ending with a letter, digit or _. A trailing ., ,, ;, :, !, ? or ) stays outside, so word @_ -> span.mention turns @9:30, into a mention of 9:30. A slot followed by a literal stops at the first place in the word where that literal matches (#_/_, _%). A word pattern has one or two slots and at least one literal, and no digit slot. It never starts right after a letter, digit or _ (email@host is not a mention), and the word is content that is not scanned for further rules.

  • ... in a block pattern separates the opening line, the body, and the closing line.

    Each space in the opening or closing segment matches zero or more spaces, so a pattern of three backticks, _, ..., three backticks means: the opening line is three backticks followed by slot 1 (may be empty, with or without a space), the body is every line up to a line that is exactly three backticks. An all-literal opening segment also allows the one-line form <!-- note -->.

  • \` escapes the next character in the pattern (so _` matches a literal underscore).
  • A pattern with no slots on a line rule matches a whole line exactly (---).
  • Longest pattern wins when two rules could match at the same position (length = count of

    literal characters). **_** beats *_*. Ties go to the rule defined last (so a document overrides an import). For inline rules the leftmost start wins first. Word rules take part on the same terms, so word @ana beats word @_ on @ana.

  • A closing literal made of one repeated character (**) slides to the end of a run of that

    character, so ***c*** is <strong><em>c</em></strong>.

  • No regular expressions in short form. See full form for the escape hatch.

4. TARGET, attributes, modifiers

#

TARGET is one word, optionally with classes: p, p.note, li.task.done.

  • If it is an allowlisted HTML element name, the HTML renderer emits that element.
  • Otherwise it is a plugin target looked up in the host registry (emoji, mermaid,

    math, csv, tsv, var, include). Unknown targets render as <div class="self-unknown" data-target="x"> around the content and add a diagnostic.

  • Two reserved targets: hidden (emit nothing) and text (emit the content unwrapped).

Attributes are name=value. A value may be a slot (href=_2), a quoted string (class="x y", style="color: _1" where _1 inside quotes is replaced by the slot text), or a bare word. A slot referenced by an attribute is consumed and not rendered as content. Unnamed slots become the node's content in order, unless bare slot tokens after the target list the content explicitly: [url]_[/url] -> a href=_1 _1 shows the URL as the link text.

Modifiers (bare words, any order, after the target):

ModifierEffect
verbatimcontent is not scanned for further rules; whitespace preserved
group Xconsecutive siblings from this rule (or rules sharing group X) are wrapped in one X; a group-NAME= attribute goes on the wrapper, from its first member (D141)
nestmore-indented following lines become children of this node (lists)
split "S" Tsplit the content on literal S, wrap each trimmed piece in T (table cells)
fold Nthis node starts a foldable section that ends at the next fold node with level <= N
foldfoldable section is the node's indented children (line rule) or body (block rule)
keepkeep the matched delimiters in the output (default is to drop them)
boundthe match may not start right after, or end right before, a letter, digit or _
urlon a word rule with a slot: the slot takes a whole URL, not one word (D141)
input=KIND [checked]prepend an input control (checkbox, text, radio)
key SHORTCUTeditor only: the shortcut applies the rule (key Ctrl+B, key Ctrl+Shift+8, D122); no effect on output
as NAMEgive the rule a name for off NAME, inspector display, style class, and full form

Style is a { ... } block containing plain CSS declarations. The renderer generates a class per rule (its as name, else self-r12 for rule 12) and emits one <style> block with an origin comment per rule. A rule's style is for its own elements: when another rule writes its as name as a class (-> div.box, group ul.box, class=box), its class is self-r12 beside the name, with an info note (D264); class NAME { … } styles every element with a class. No shorthand tokens, ever. Declarations that could fetch or escape (url(, @import, < ...) are dropped with a diagnostic.

Palettes and classes (D129, D130) keep repeated values in one place, in plain CSS:

selfscribe
palette
  accent  #7c5cff  dark #b197fc
  soft    color-mix(in srgb, var(--accent) 12%, transparent)
class pill  { padding: 0.1em 0.5em; border-radius: 99px; background: var(--soft) }
word  TODO  -> span.pill  { color: var(--accent) }
  • palette NAME VALUE [dark VALUE] names a value; rules use it as var(--NAME). The dark

    value is used on dark pages (it must be a colour). The block form takes indented entries. A later entry with the same name replaces the earlier one, imports included. Names starting ui-, syn-, font-, ed-, cm-, pg-, self- or selfp- belong to the editor and are refused.

  • class NAME { css } styles every element with that class inside the document: a group

    wrapper, a split piece, or a class several rules share. A rule's own { css } wins over it. The name may be followed by pseudos (::before, ::after, ::marker, :hover, :first-child, :last-child, :nth-child(2n+1), a pseudo-element last) and by one element inside it, a descendant or a child: class crumb::after { content: "›" }, class card h3 { … }, class card > p:first-child { … }. Nothing else may follow the name. A later class replaces an earlier one with the same name and ending. Names starting self-, cm-, ed- or pg- are refused.

  • The CSS output is, in order: the palette as custom properties on

    :where(.self-doc, .self-palette) (the dark values through light-dark()), the classes, then the rules.

5. Full form

#

The same rule as a keyed block. Same AST, so an editor can toggle between the two.

selfscribe
rule critical
  where   line
  match   // ! _
  out     p.critical
  style   color: crimson; font-weight: 600
  editor  colour crimson, icon "!"
  doc     Critical item, shows red in source and preview

rule may omit the name. Key lines are the indented lines that follow; a blank or unindented line ends the rule. out holds the target, attributes and slot tokens; modifiers are keys.

Extra keys only available in full form:

KeyMeaning
reinstead of match: a regular expression with numbered groups, inline or line only. Escape hatch, off unless the host enables it.
editorhints for the source editor: colour, icon, bold, italic, hide, key
dochuman description, shown in the inspector and wizard
group, nest, split, fold, verbatim, keep, bound, input, keysame as modifiers (input KIND [checked])

Full-form and short-form rules may be mixed freely in one block.

6. Overrides

#

A rule with the same WHERE and PATTERN as an earlier one (including imported ones) replaces it. Sameness is judged on the compiled pattern (literals plus slot positions), not the raw text, so **$** written under set slot $ replaces an imported **_**. off PATTERN, off WHERE PATTERN or off NAME disables one. The compiled rule table records, for every rule, which file and line defined it and which rule it replaced. That table is what the inspector shows with the struck-through overridden rules. Rule ids are 1-based positions in that single table, across imports and scopes.

7. What is deliberately not in v1

#
  • Regex in short form. Never.
  • Templates with named parameters (template image <img src={url}>). Planned as v1.1.
  • Expressions, conditionals, loops. Never in documents; a host plugin may do them.
  • Rules that rewrite other rules. (A rewrite rule, §8, rewrites a block's text, never a rule.)
  • CommonMark flanking rules. Use bound where intraword matches hurt.

Exact matching, tokenising and serialisation rules are in docs/01-DECISIONS.md (D11 to D39).

8. Rewrite rules (D255)

#

A rewrite rule lets a document write a block in a short notation of its own and hands the block's target the text that notation stands for, in the target's own language (flow, math, a TikZ or LaTeX block, chart, sketch, mermaid, pre).

selfscribe
~~~ selfscribe
rewrite block ``` pipeline ... ``` -> flow
  line   _1 > _2    ->  _1 -> _2 moving
  line   _1: _2     ->  node _1 "_2" :service
  first             ->  set direction=LR
~~~

``` pipeline
api: Booking
db: Sailings
api > db
```

The block is read exactly as this flow block:

text
``` flow
set direction=LR
node api "Booking" :service
node db "Sailings" :service
api -> db moving
```

The head. rewrite block PATTERN -> TARGET [attr=value ...] [modifiers] [{ css }] [as NAME] is a short-form block rule (§1) that is always verbatim. Everything a block rule may say after its target it may say too; keep has no effect and warns. Only block may follow rewrite; any other WHERE is an error and the line is skipped.

Template lines. The indented lines right under the head belong to it, like a full-form rule's keys (§5); a blank or unindented line ends them. Indented # lines are comments. Each template line is one of:

LineMeaning
line PATTERN -> TEMPLATEa body line that PATTERN matches becomes TEMPLATE
first -> TEMPLATETEMPLATE is added once before the body (several stay in order)
last -> TEMPLATETEMPLATE is added once after the body
  • PATTERN is a line pattern (§3): slots, _1.._9, _#, `` escapes, anchored at both

    ends of the body line after its indentation, trailing spaces ignored.

  • TEMPLATE is everything after the first ->, trimmed at both ends, a # included: the

    target's language may need any character. There are no escapes in a template. The slot character followed by 1..9 is replaced by that slot's text, trimmed of spaces and tabs; followed by # it is the digit slot's digits. A reference to a slot the pattern does not have warns and stays as written, so x_3 in a LaTeX template is left alone when the pattern has two slots. When the target language uses the slot character itself (LaTeX's _ for subscripts), write set slot @ before the rewrite and use @1.

  • A rewrite has at most 256 template lines; later ones warn once and are ignored.
  • An unknown line word, a missing ->, an empty or invalid pattern, or a pattern after

    first/last is an error on that template line, which is skipped.

Applying it. When the rule matches a block (as any block rule, §2, §3), each body line, with the opening line's indentation removed as for every verbatim block:

  1. A blank line stays blank.
  2. Otherwise the templates are tried in priority order: longest pattern first (D27), a tie

    going to the template written later. The first that matches gives the line: the line's own indentation, then the filled template.

  3. A line no template matches stays as written. The target's own language is never

    taken away: a person writes the lines they shortened in their notation and anything else in the target's syntax, comments included. A line that is wrong in both is reported by the target, as it would be in a plain block of the target, at the line written (below).

The output is the first lines, the body lines, then the last lines, each ended by \n. The one-line form of an all-literal pattern (<<< a to b >>>, D33) rewrites its one line, without the final \n.

No loops, bounded size. The output goes to the target only. It is never matched against rules again, a rewrite cannot name another rewrite, and one line in gives one line out, so the size is linear in the body. If the output would pass 1 MiB, the block is read as written with a warning on its opening line.

Spans and the line map. The node's span is the block as written and its text child's span is the body as written, as for any verbatim block; only the text differs. The node carries data-self-rewrite: for each line of the output, the body line it came from (1 is the first body line), or 0 for a first or last line (the opening line), space-separated. A target that reports a problem on line N of its text points the person at body line map[N-1]. The map is relative to the block, so the block's HTML does not change when lines above it do (D101).

Editing through a plugin. A rewritten block is read-only to plugin editors: a host refuses a write-back (D83) proposed from inside an element with data-self-rewrite, because the text the plugin edits is not the text written. To change the block, the person edits its lines. (Mapping a write back through the templates is not in v1.)

Targets. Any target may be named. An engine-half plugin receives the rewritten text as its node's content; one that reads its block from the source by span (data, bibliography …) would never see it, so naming such a plugin is an error and the rule is skipped. A plugin says it reads its node's text (reads_node_text, 04 §2); math and mermaid do. Client-half plugins (flow, tikz, latex, chart, sketch …) read the element's text, so they always receive the rewritten text. A peer (D80) that is a rewritten block hands other plugins its rewritten text, never its source.

Sharing. A rewrite is a block rule. It is imported with use, scoped, switched off with off or off NAME, and a later rule with the same block pattern replaces it (§6), template lines and all: to change one template, write the whole rewrite again. A notation kept in a rulebook (use notations/pipeline.self) is shared by every document that uses it. Converting between short and full form (§5) leaves a rewrite as written; it has no full form.

Not in v1. rewrite inline (a slot's text rewritten inside a line), one line becoming several, rewriting inside a line by its operators (an expression grammar, which §7 keeps out of documents), and writing a plugin's edits back through the templates.