# Text

Patterns (`re`), full-text search (`search`), text to a tree (`syntax`), and
what is built on the tree: `Highlight`, `Markdown`, the `editor`. HTML from
elsewhere cleaned, shown and read as text (`html`, `htmlframe`). Also font
files (`font`): a line laid out by the font itself, and its outlines. Back
to the [map](README.md).

```mote
// docs: whole
state text = "Ship 2 doors to 90210 by 2026-11-15"
derive numbers = re.all(text, r"\d+").map(m => m.text)
derive date = re.replace(text, r"(\d+)-(\d+)-(\d+)", "$3/$2/$1")

column gap=8 padding=16
  input value=text
  text `numbers: ${numbers.join(", ")}`
  text date color=dim
```

## Mental model

Four tools, by how they run:

- **`re`** is Mote's own regular expressions: JavaScript's syntax and its
  answers, run by an engine in Rust (`batteries/re`, as wasm) where it is
  called, the same on the page and on the back end, in time that grows only
  in step with the text. It does not wait and cannot fail by type: it
  works in a derive or a binding. A fn that uses `re` stays on the main
  thread.
- **`search`**, **`syntax`** and **`font`** are batteries: Mote's own Rust,
  compiled to wasm, run in a worker. Every call waits and can fail, so they
  go in an action, a task or a resource ([reactivity.md](reactivity.md)).

**What they cost a page.** None of the four is in the page of a build. Each
is a file beside it (`assets/syntax.<hash>.wasm`: 153 KB, 61 KB gzipped;
`re` 156 and 60; `search` 45; `font` 73), fetched once, when something first
needs it, and kept by the browser for good. A battery is fetched by its
first call, so a page that never calls `syntax.parse` never downloads it. `re`
cannot wait where it is called, so it is fetched before the code that can
call it runs: when a component that runs a pattern is first drawn (it is
drawn the moment the engine arrives), or, where the page's own top-level
lines run one, as the page loads, which then starts when it is here. A
route with `Markdown` on it fetches `syntax` and `re` when it is first
shown; the other routes fetch nothing. If a file cannot be fetched (offline,
and not installed), the call fails with kind `offline` and the next call
tries again. `mote build --single` carries them inside the one file
instead. How: [internals.md](internals.md#batteries).

All four work in a `server fn` too (but `font.use`, which is the page's).

## Patterns

A pattern is a regular expression, written as text. `r"\d+"` is a **raw
string**: nothing in it is an escape, so a pattern's backslashes stay as
written. A raw string cannot hold a `"`; for those use `"…"` with `\\` for
each backslash.

| Call | Gives |
|---|---|
| `re.test(text, pattern)` | Whether it matches anywhere: a bool. |
| `re.find(text, pattern)` | The first match, or `none`. |
| `re.all(text, pattern)` | Every match, a list (after an empty match the search goes on a character later). |
| `re.at(text, pattern, i)` | A match that starts exactly at `i`, or `none` (a tokeniser's step). |
| `re.from(text, pattern, i)` | The first match at or after `i`, or `none`. |
| `re.replace(text, pattern, "with $1")` | The text with every match replaced. `$1` to `$99` a group, `$<name>` a named one, `$&` the whole match, `` $` `` and `$'` the text before and after it, `$$` a dollar. |
| `re.replace(text, pattern, m => …)` | The same, each match replaced by what the fn gives for it (a match, below). |
| `re.split(text, pattern)` | The pieces between matches: `string[]`. A group in the pattern puts what it matched between the pieces (`""` for one that took no part). |
| `re.escape(text)` | The text as a pattern that matches it exactly. |
| `re.check(pattern)` | `none` if the pattern can be used, else why not: for a pattern someone types. |

**A match** is `{text, at, end, groups, group, named}`: what matched, where
it starts and ends, each group's text (`""` if it took no part), the number
of the first group that did (0 if none), and the named groups' texts by
name. Where the pattern is written out, `named` has exactly its names:
`re.find(s, r"(?<year>\d{4})")?.named?.year` is a `string`, and `.day` is an
error when the program is built.

**Flags** are a last argument: `"i"` any case, `"m"` `^` and `$` at each
line, `"s"` `.` takes a line end, `"u"` strict syntax (below), `"y"` only
where the search starts. Several go together: `"iu"`.
`re.test("HELLO", "hello", "i")`.

**Letters of any language: `\p{…}`.** `\p{L}` is any letter, `\p{Lu}` an
upper-case one, `\p{N}` a digit of any script, `\p{sc=Greek}` a letter of
one script (`scx=` for the characters scripts share), `\p{Emoji}` an emoji,
`\P{L}` anything but a letter, `\u{1F600}` one character by its number. A
pattern that uses any of these is read with `"u"` whether or not the flag is
given; with `"u"`, said or implied, a needless escape (`\-` outside a
class, `\:`) is an error, not a letter. A character is always whole: `.`
takes `"😀"` as one, with `"u"` or without.

```text
re.all("naïve café", r"\p{L}+").length      // 2
re.test("é", r"^\w$")                       // false: \w is ASCII's; write \p{L}
re.find("ok 😀", r".$")?.text                // "😀"
re.test("ſ", r"s", "iu")                    // true: with "u", case is Unicode's folding
```

What `\p{…}` knows: every general category (`L`, `Lu`, `Ll`, `Lt`, `Lm`,
`Lo`, `M`, `N`, `Nd`, `P`, `S`, `Z`, `C`, … and their long names, as
`Letter`), every script by its short and long name, and the binary
properties `Alphabetic`, `White_Space`, `Uppercase`, `Lowercase`, `Cased`,
`Emoji`, `Emoji_Presentation`, `Extended_Pictographic`, `Emoji_Modifier`,
`Emoji_Modifier_Base`, `Emoji_Component`, `Regional_Indicator`, `ID_Start`,
`ID_Continue`, `XID_Start`, `XID_Continue`, `Math`, `Dash`, `Hex_Digit`,
`ASCII_Hex_Digit`, `Ideographic`, `Diacritic`, `Any`, `ASCII`, `Assigned`
and the rest of JavaScript's but `Changes_When_…` and `Grapheme_Base`.
Unicode 17, from the tables `tools/re-tables.mjs` writes.

**What `re` does not run.** A backreference (`\1`, `\k<name>`), a lookahead
(`(?=…)`, `(?!…)`) and a lookbehind (`(?<=…)`, `(?<!…)`): they are what can
make a pattern take time that grows exponentially with the text, so a
pattern from anyone is safe to run. Write what they meant another way:

| Instead of | Write |
|---|---|
| `(?<![a-z])word` | `(?:^\|[^a-z])(word)`, and read the group |
| `\d+(?=px)` | `(\d+)px`, and read the group |
| `^(?!.*admin)` | `!re.test(text, r"admin")` |
| `^(.)\1+$` (one character, again) | `s.split("").every(c => c == s[0])` |

**A pattern written out is read when the program is built.** A wrong one is
an error there, with the caret at its character:

```text
app.mote:4:28: error[H300]: this pattern is wrong at its character 1: a `(` that is never closed (add `)`, or write `\(` for the character)
app.mote:5:31: error[H301]: this pattern asks for what `re` does not run: a lookahead `(?=…)` is not supported (…)
```

as is a replacement that names a group the pattern does not have (`$3` of
two groups: H303). A pattern made when the page runs (from what someone
typed) throws where it is used if it is wrong: `re.check(p)` says first.

```mote
// docs: whole
shape Tok
  kind: string
  text: string

state source = "total = price * 1.0825 + 'tax'"

fn tokens(s: string): Tok[]
  let out: Tok[] = []
  let rules = [{kind: "space", p: r"\s+"}, {kind: "number", p: r"\d+(\.\d+)?"}, {kind: "word", p: r"[A-Za-z_]\w*"}, {kind: "string", p: r"'[^']*'"}, {kind: "mark", p: r"."}]
  let i = 0
  while i < s.length
    let got = false
    for r in rules
      if !got
        let m = re.at(s, r.p, i)
        if m
          if r.kind != "space" out.push({kind: r.kind, text: m.text})
          i = m.end
          got = true
    if !got i += 1
  return out

column gap=8 padding=16
  input value=source
  row gap=6 flex-wrap=wrap
    for t in tokens(source)
      text t.text color=(t.kind == "number" ? "accent" : (t.kind == "string" ? "ok" : "fg"))
```

```mote
// docs: whole
state text = "Ship 2 doors on 2026-11-27, 3 more on 2026-12-01"
state typed = r"\d+"

derive dates = re.all(text, r"(?<year>\d{4})-(?<month>\d\d)-(?<day>\d\d)").map(m => `${m.named.day}.${m.named.month}.${m.named.year}`)
derive louder = re.replace(text, r"\d+", m => `[${m.text}]`)
derive why = re.check(typed) ?? ""

column gap=8 padding=16
  text dates.join(", ")
  text louder
  input value=typed
  text (why == "" ? `${re.all(text, typed).length} matches` : why) color=dim
```

**How it runs.** A pattern is compiled once and kept, to a program run as a
Pike VM: every way the pattern can go steps over the text together, a
character at a time, so a text of n characters takes n steps times the
pattern's size, whatever the pattern (`(a+)+$` on a million `a`s and a `b`
takes milliseconds; a backtracking engine would not finish). Where a match
can begin is found first by its literal start or its first bytes; a match's
end alone (`re.test`, `re.at` without groups) runs a lazy DFA. The text last
searched stays in the engine, so a tokeniser's loop over one text copies it
in once. Against the browser's own regular expressions, which are compiled
to machine code, it is level on a tokeniser's loop and several times slower
on a long text with many matches ([bench/README.md](../bench/README.md#re-against-the-hosts-regexp)).

Source: `runtime/shared/patterns.mote`, part `RE`.

## search

Full-text search, ranked by BM25. A battery, in Rust. An index is made of
**segments**: bytes made once from some documents, searched together, joined
by a merge. A mailbox of hundreds of thousands of messages is a few dozen
segments, and a message that arrives is a small segment more.

```mote
// docs: whole
shape Doc
  id: string
  text: string

state docs: Doc[] = [{id: "a", text: "red oak door"}, {id: "b", text: "white oak cabinet door"}, {id: "c", text: "maple drawer"}]
state query = "oak door"
state index: bytes? = none
state hits: {id: string, score: number}[] = []

action build
  index = search.index(docs)?

action find
  if index == none return
  hits = search.find(index, query, {limit: 5, prefix: true})?

task
  build()

column gap=8 padding=16
  input value=query input={find()} placeholder="Search"
  for h in hits key=h.id
    text `${h.id}: ${h.score.toFixed(3)}`
```

| Call | Gives |
|---|---|
| `search.index([{id, text}, …])` | A segment, as bytes to keep (in state, in a file, in sql; sealed with `crypto.aes`). |
| `search.index([{id, fields: {subject, from, body}}, …])` | The same, with named fields (eight at most; `text` is a field called `text`). |
| `search.find(segments, "oak door")` | The best ten as `{id, score, matches}`, best first. `segments` is one segment, a list of them, or a searcher. |
| `search.find(s, words, {limit: 3, prefix: true})` | `limit`: how many. `prefix`: the last word also finds the words it begins (searching as you type). |
| `search.find(s, words, {all: true})` | Only the documents that hold every word, phrase and prefix asked (else any of them, the more the better). |
| `search.find(s, words, {weights: {subject: 3}})` | A field's weight (unsaid: 1): a word in a subject counts three times one in the body. |
| `search.find(s, words, {removed: ["m12"]})` | Those ids are not found. |
| `search.merge([a, b, c], {removed: [ids]})` | One segment of them all, less the removed ids. |
| `search.open([a, b], {removed: [ids]})` | A **searcher**: the segments loaded once, so a query does not hand them over again. |
| `search.add(s, segment)` · `search.remove(s, [ids])` · `search.close(s)` | A segment more (the newest); ids removed from now on; the searcher let go. |
| `search.count(segments or s)` | How many documents (removed ones too, until a merge leaves them out). |
| `search.marks(text, words, {field, prefix})` | Where the words are in a text, as `{from, to}` (UTF-16 offsets, as `text.slice` takes): for a snippet with the words marked. `field`: the text is that field's (a `subject:` word marks nothing in another). |

Each hit's `matches` says where it matched: `[{field: "subject", words: [0, 3]}]`,
the positions of the words found, counted in words from the field's start.
`search.marks` gives the same as places in the text, which is what a page draws:

```mote
// docs: whole
state text = "Re: the oak door for March"
state query = "oak doo"
resource marks: {from: number, to: number}[] = search.marks(text, query, {prefix: true}) else []

column gap=4 padding=16
  input value=query
  text (marks.map(m => text.slice(m.from, m.to)).join(", "))
```

**What a query says.** Words, any of which may match. `"a phrase"` in quotes:
its words in that order, next to each other. `word*`: any word that starts
with `word`. `field:word` or `field:"a phrase"`: in that field only, where a
segment has a field of that name (else `field:` is just more words). A word
written with something between its pieces (`don't`, `ada@example.com`,
`10:30`) is a phrase of them.

**Words.** A text is cut wherever a character is neither a letter, a digit
nor a mark, and each character is folded first:

- **Case and accents do not count.** A character becomes its compatibility
  decomposition (Unicode's NFKD) less the marks that are accents, in lower
  case: `Ünïcödé`, `UNICODE` and `ｕｎｉｃｏｄｅ` (full-width) are one word;
  the ligature `ﬁ` is `fi`, `①` is `1`. The marks taken off are the
  combining diacritics, Hebrew points and Arabic vowel signs; a mark that
  is part of a letter elsewhere (an Indic vowel sign, a kana's voicing mark)
  stays, and Hangul syllables are not taken apart.
- **A few letters that are not decomposed are read as plain ones:** `ß` and
  `ẞ` are `ss` (so `straße` finds `STRASSE`), `ı` is `i`, `ø` `o`, `ł` `l`,
  `đ` and `ð` `d`, `ħ` `h`, `ŧ` `t`, `æ` `ae`, `œ` `oe`, `þ` `th`.
- **No language's own rules.** `İ`, `I`, `ı` and `i` are all `i`, Turkish or not.
- **Chinese, Japanese and Korean** are written without spaces: a run of Han,
  hiragana, katakana or Hangul is indexed as its overlapping pairs of
  characters, and its last character alone (東京都 is 東京, 京都 and 都). A
  query's run is a phrase of its pairs, so `京都` finds 京都 and not 京 here
  and 都 there; one character alone finds every pair it begins. No
  dictionary is used: a pair that crosses two words is indexed too, which
  can find a word inside a longer one. Thai, Lao, Khmer and Burmese, also
  written without spaces, are not cut: a run of them is one word.
- There is no stemming and no list of ignored words. A word over 64 bytes
  is cut there.

**Ranking** is BM25 (k1 = 1.2, b = 0.75) over weighted fields (BM25F): a
word's count in each field is divided by how long that field is against the
average, weighted, added up, and saturated; rare words count for more. The
numbers it takes (how many documents, how many hold each word, the average
length of each field) are those of **all the segments searched together**,
so a document scores the same whichever segment it is in and however the
documents were split; of two that score the same, the one indexed first
comes first. A removed document still counts in those numbers until a merge
leaves it out, as in Lucene.

**Segments that grow.** Index what arrives as a small segment; search the
list; now and then merge the small ones into one (`search.merge`), which
gives the same bytes as indexing their documents in one go.

- **The same id in two segments:** the later segment's copy is the one
  found, so a changed message is indexed again as a new small segment.
- **Removed ids** (`search.remove`, `removed:`) are not found, and a merge
  leaves them out. Keep the list of them beside the segments.

**A searcher.** `search.find` over bytes hands the segments to the battery
on each call, which is fine for thousands of documents and slow for
hundreds of thousands. `search.open` loads them once; each query is then the
words in and the hits out. A page's searchers live in one worker of their
own (not the main thread, not the pool's), so an action may call
`search.find(s, …)` on every key; 500,000 short documents in 40 segments
answer a two-word query in 1 to 13 ms there, and in 3 to 54 ms on a main
thread slowed down four times ([bench/README.md](../bench/README.md#search-that-grows)).
A searcher lives where it was opened: in a `server fn` it is the back end
process's until closed; in an `off fn` it is that worker's for that call
(open, find and close in the one call). Its memory is about the size of its
segments: 500,000 documents of fifty words each are 105 MB.

```mote
// docs: whole
state s: searcher? = none
state hits: {id: string, score: number}[] = []
state query = "invoice march"

// Sealed segments, opened in a worker: the key and the bytes are handed over, and the
// segments come back to be loaded.
off fn unseal(key: bytes, sealed: bytes[]): bytes[]
  let out: bytes[] = []
  for x in sealed
    out.push(crypto.aes.open(key, x.slice(0, 12), x.slice(12))?)
  return out

action load(key: bytes, sealed: bytes[])
  s = search.open(unseal(key, sealed)?)?

action arrived(mail: {id: string, subject: string, body: string}[])
  let open = s
  if open == none return
  search.add(open, search.index(mail.map(m => ({id: m.id, fields: {subject: m.subject, body: m.body}})))?)?

action find
  let open = s
  if open == none return
  hits = search.find(open, query, {limit: 20, prefix: true, weights: {subject: 2}})?

input value=query input={find()}
```

**Storing segments.** A segment is plain bytes and holds no secret of its
own: seal it with `crypto.aes.seal` before it is written anywhere, and open
it before `search.open`. It holds every word of its documents, in order:
treat it as the documents themselves. The format is named by its first four
bytes (`MSE1`, format 1, described at the top of `batteries/search/lib.rs`):
Mote will read format-1 segments in every later version; a new format will
come with the reading of the old one, and be said in the changelog. An index
made before there were segments (its first bytes `HSB1`) is refused, `this
is not a segment`: make it again from its documents. A program that keeps
an index between visits can tell before it searches, `search.count(b) else
-1` being `-1` for bytes that are not a segment, and make it again then
(the playground's search page does this when it loads a kept index).

- `search` waits: it cannot go in a derive. Keep the result in state, or use
  a resource.
- Bytes that are not a segment fail. So does a searcher that was closed or
  opened elsewhere (`this searcher is closed, or was opened elsewhere`).
- In an `off fn` and on the back end every call is the battery's, where it is.
- For rows of a model, which come and go, the model keeps an index itself
  and searches it under its rules: `index text fulltext` and
  `T.search(words)` ([models.md](models.md#full-text-search)).

Source: `batteries/search/lib.rs` (its tables of characters,
`batteries/search/fold.rs`, are written by `fold.mjs` from Unicode's own);
`runtime/shared/batteries.mote`, part `SE`; a page's searchers,
`runtime/page/workers.mote`, part `SK`.

## syntax

Text to a tree. A battery, in Rust.

| Call | Gives |
|---|---|
| `syntax.parse(text, "js")` | The tree: a node is `{kind, value, from, to, text, children}`. As `json`. |
| `syntax.grammar(text)` | A grammar of your own, read: what `parse`, `tokens` and `lines` take in place of a language's name ([below](#a-language-of-your-own)). |
| `syntax.tokens(text, lang)` | The leaves in order as `{kind, text}`, with what lies between them as kind `""`: joined, they are the text again. |
| `syntax.lines(text, lang)` | The same, a list per line: what drawing code wants. |

`from` and `to` count as a page's text does (UTF-16 units), so they index
into the string you gave.

### Code

Code is its tokens, with structure over them.

- **Token kinds**: `keyword` `string` `number` `comment` `name` `function`
  `type` `constant` `operator` `punctuation` `property` `meta`.
- **`declaration`**: has `what` (function, class, struct, enum, interface,
  trait, impl, type, variable, import, module) and `name`; its `definition`
  child is the name's token.
- **`call`**: has `name`.
- **`block`**: a body in braces, or the lines set further in for Python and
  Mote.
- **`group`**: what is inside other brackets; its `value` is the opening
  bracket.

It is not a language's whole grammar: enough to colour, outline, fold and
find things.

**Languages**: js jsx ts tsx json c cpp java csharp go rust swift kotlin php
python ruby sh sql css scss yaml toml ini mote lua r dart scala zig graphql
powershell dockerfile makefile; html xml (kinds: tag, attribute, string,
text); diff (inserted, deleted, meta). A language it does not know fails.

```mote
// docs: whole
state code = "function area(w, h) {\n  return mul(w, h)\n}\nclass Shop {}\n"
state outline: string[] = []

fn names(n: json, depth: number): string[]
  let out: string[] = []
  for c in n.children
    if c.kind == "declaration"
      out.push(`${"  ".repeat(depth)}${c.what} ${c.name}`)
      for x in names(c, depth + 1)
        out.push(x)
    else if c.children.length > 0
      for x in names(c, depth)
        out.push(x)
  return out

action read
  let tree = syntax.parse(code, "js")?
  outline = names(tree, 0)

task
  read()

column gap=8 padding=16
  for l in outline
    text l white-space=pre font-family=monospace
```

### A language of your own

The languages above are outlines. For a language of your own (a formula, a
query, a config, a small programming language) write its grammar, and
`syntax.parse` gives a text's whole tree by it.

```mote
// docs: whole
state source = "1 + 2 * (3 - 4)"
state out = ""

fn calc(): string = "expr = left:expr op:(\"+\" | \"-\") right:term | term\nterm = left:term op:(\"*\" | \"/\") right:atom | atom\natom = number | \"(\" expr \")\"\ntoken number @number = [0-9]+ (\".\" [0-9]+)?\nskip = [ \\t\\n]+\n"

fn worth(n: json): number
  if n.kind == "number"
    return Number(n.text)
  if n.kind == "atom"
    return worth(n.children.length == 1 ? n.children[0] : n.children[1])
  if n.children.length == 1
    return worth(n.children[0])
  let a = worth(n.children[0])
  let b = worth(n.children[2])
  let op = n.children[1].text
  return op == "+" ? a + b : op == "-" ? a - b : op == "*" ? a * b : a / b

action run
  let g = syntax.grammar(calc())?
  let tree = syntax.parse(source, g)?
  out = `${worth(tree.children[0])}`

column gap=8 padding=16
  input value=source
  button "Work it out" press=run
  text out
```

A grammar is rules, one a line (a rule may run over the lines after it):

```text
expr   = left:expr op:("+" | "-") right:term | term
term   = left:term op:("*" | "/") right:atom | atom
atom   = number | "(" expr ")"
token number @number = [0-9]+ ("." [0-9]+)?
skip   = [ \t\n]+ | "#" [^\n]*
```

| Written | Means |
|---|---|
| `"let"` | That text. A word (`"in"`) is not found at the start of a longer word (`index`). |
| `[a-z0-9_]`, `[^"]` | One character of a set, or one not of it. |
| `.` | Any one character. |
| `/[0-9]+(\.[0-9]+)?/` | A regular expression, [`re`'s](#patterns), tried at the place it stands. `/…/i` for any case (and `m`, `s`, `u`); a `/` inside one is `\/`. |
| `name` | Another rule. |
| `a b` | `a`, then `b`. |
| `a \| b` | `a`, or else `b`: the first that fits is taken. |
| `( … )` | A group. |
| `a*` `a+` `a?` | Any number of `a`; one or more; one or none. |
| `&a` `!a` | `a` must come next, or must not; nothing is taken. |
| `label:a` | `a`, and its node says `label` (`left`, `op`, `right` above). |
| `# …` | A comment. |

- **The first rule** is what a text is parsed as, and all of the text must fit.
- **`token name = …`** matches characters with nothing skipped between
  them, and is one leaf of the tree. Every other rule skips what the rule
  **`skip`** matches (spaces, comments) before each text and each token.
- **A rule may begin with itself** (`expr = expr "+" term | term`): operators
  are written the plain way, and lean left.
- **A rule whose name begins with `_`** leaves no node: what it holds stands
  in its place.
- **A pattern is best in a token**: `token number @number = /[0-9]+(\.[0-9]+)?/`.
  It takes what the pattern would take there (of `a|ab`, the first that
  fits, as in `re`), `^`, `$` and `\b` see the whole text, and it leaves no
  node of its own: the rule it stands in says what was found. A pattern that
  is wrong is the grammar's mistake, said at the character in it; a
  backreference or a lookaround is refused, as everywhere.
- **The grammar's own words are never a token**: with `"let"` in the grammar,
  `let` is not a `name`.
- **`@keyword`** (or `@string`, `@number`, `@comment`, `@name`, `@type`,
  `@function`…) after a rule's name says what it is coloured as.

**The tree.** `syntax.parse(text, g)` gives `{kind: "root", children,
errors}`. A node is `{kind, from, to, children}`: `kind` is its rule's name,
or for a text of the grammar that text itself (`"+"`); a leaf also has
`text`; `label` and `colour` are there when the grammar says them. `from` and
`to` index into the text, as everywhere in `syntax`.

**A text that does not fit** fails, with where and what was wanted: `syntax:
line 2, column 1: number, name or "(" was wanted here, and there is "print"`.
With `{recover: true}` it does not fail: the text is read on from the line
after each mistake, the tree holds what was right, and `errors` says each
mistake (`{at, line, col, message, wanted}`). That is what an editor wants
while a text is being typed.

**Colours.** `syntax.tokens(text, g)` and `syntax.lines(text, g)` give the
leaves coloured by the grammar: a rule's `@colour`, `keyword` for the
grammar's own words, `punctuation` for its other texts. They are what
`Highlight` and the editor draw, so a language of your own is coloured like
any other.

**Read when the program is built.** A grammar in a file beside the program is
checked by the compiler, and a mistake in it is a diagnostic at its line in
that file (`H311`):

```text
grammar Calc from "./calc.grammar"

let tree = syntax.parse(source, Calc)?
```

`Calc` is what `syntax.grammar` would have given: `{grammar, rules}`.
A `server fn` may name it too.
`syntax.grammar(text)` reads one as the program runs (a grammar someone types
into the page); what is wrong with it is the call's failure, with the line
and column.

It is a parsing expression grammar (PEG): a choice takes the first
alternative that fits and does not come back to try another, so put the
longer alternative first (`"<=" | "<"`). Parsing
takes time in proportion to the text for the grammars people write; a very
large text with deeply nested choices takes memory in proportion to both.

### Markdown

`syntax.parse(text, "markdown")` is the document, ready to draw: CommonMark,
with GitHub's tables, struck text, task lists, footnotes and bare addresses.

| Kind | Fields |
|---|---|
| `heading` | `level`, `id` |
| `paragraph` | |
| `list` | `ordered`, `loose`, `start` (the number it starts at) |
| `item` | `checked`: `none`, `false` or `true` |
| `code` | `lang` (the first word after the fence), `code` |
| `quote`, `rule` | |
| `table` of `row` (`head`) of `cell` (`align`: `""`, left, center, right) | |
| `emphasis`, `strong`, `strike` | |
| `codespan` | `code` |
| `link` | `url`, `title`, `pending` (true while its address is still arriving) |
| `image` | `url`, `title`, `alt` |
| `noteref` | `number`, `id` |
| `break` | a line break |
| `text` | `text`: its words as they are meant (entities read, escapes dropped) |

- An item of a list that is not loose holds its words themselves, with no
  paragraph over them.
- If the text points at footnotes, the root's last child is `notes`,
  holding a `note` (`number`, `refs`) for each.
- Raw HTML is text. An address that is not http, https, mailto, tel or
  relative is dropped.
- Each block right under the root has a `key` that stays the same while
  text is added: `for b in doc.children key=b.key`.
- `syntax.parse(text, "markdown", {streaming: true})`: the text is still
  arriving, and what is unfinished at its end is finished for it or held
  back.
- `{packed: true}`: the root's children come as `{key, kind, packed}`, each
  block as JSON text. A block that is as it was is then the same text,
  which a page can tell without looking inside it (the kit's `Markdown`
  uses this).

Source: `batteries/syntax/lib.rs` (its header says what the tree is);
`runtime/shared/batteries.mote`, part `SY`.

## HTML

HTML from elsewhere (a letter, a page someone pasted) is hostile: what it
holds may run, fetch, post, or draw over the page. `html` reads it as a
browser does, keeps only what an allow-list keeps, and writes it out again;
`htmlframe` shows it where nothing can run and nothing is fetched that the
program did not allow; `html.text` makes plain text of it.

```mote
// docs: whole
state letter = "<p style='color:#246'>Hi <b>Ada</b>, <a href='https://example.com/'>the plans</a> are ready.<img src='https://pixel.example/o.gif' width=1 height=1></p>"
state report = ""
state opened = ""
state snippet = ""

action cleaned(r: {html: string, images: string[], links: string[], removed: string[], trackers: number})
  report = `${r.images.length} remote pictures left out, ${r.trackers} to learn it was read`

action asText
  snippet = html.text(letter) else ""

column gap=8 padding=16
  htmlframe html=letter images="block" link={opened = it} cleaned=cleaned
  text report color=dim
  text opened
  button "As text" press=asText
  text snippet
```

**Where it is read, and why.** In the `html` battery (`batteries/html`,
Mote's own Rust as wasm), not by the browser's `DOMParser`: the battery is
there in a worker and on the back end, where `DOMParser` is not, so a mailbox
of thousands of letters is cleaned in the worker pool (or in an `off fn`, or
a `server fn`) by the same code a page uses. It follows the HTML standard's
tokenizer and tree builder closely (every insertion mode, the adoption
agency, foster parenting, where SVG and MathML end, the named character
references), so what is kept is what the letter's reader would have seen:
over DOMPurify's 223 fixtures and OWASP's filter-evasion cheat sheet its tree
is the browser's own in every case compared. And what is written out is
written from the tree it built, never from the text it was given: nothing of
the text reaches the output that was not read as text or as an allowed
element, so a reading that differs from the browser's ("mutation XSS") has
nothing to work with. What is kept has no element whose content a browser
reads otherwise (no `textarea`, `title`, `noscript`, `xmp`, `iframe`, no SVG
or MathML), so the output reads back the same.

### html.clean

```mote
// docs: whole
state raw = "<p onclick='x()'>Hello <img src='cid:logo@shop'></p>"
state safe = ""

action go
  let c = html.clean(raw, {images: "proxy", proxy: "/img?u={url}", cid: {"logo@shop": "data:image/png;base64,iVBORw0KGgo="}})?
  safe = c.html

column gap=8 padding=16
  button "Clean" press=go
  text safe
```

`html.clean(text, options)` waits and can fail (an offline page that has not
fetched the battery yet: kind `offline`; a document too large for memory:
kind `memory`). It gives:

| Field | |
|---|---|
| `html` | The document cleaned: its sheet first (one `<style>`, when it had any), then the body's content, inside a `<div>` with the body's look when it had one. |
| `images` | Every remote picture's address it held (each once), whatever `images` said. |
| `links` | Every link kept (`http`, `https`, `mailto`, `tel`), each once. |
| `removed` | What was taken out because it could run, fetch, post or embed: `<script>`, `onclick`, `javascript: link`, `css url() in cursor`, `<form>`, `<meta http-equiv>`, … Empty when there was none. |
| `trackers` | Remote pictures of at most 2×2 pixels, or hidden: the usual way to learn that a letter was opened. |

| Option | |
|---|---|
| `images` | `"block"` (unsaid): a remote picture's address is left out (its `alt`, `width` and `height` stay, so the layout holds); a remote `background` is `none`. `"proxy"`: every remote picture is asked of `proxy` instead. `"allow"`: as written. |
| `proxy` | An address (`https://…`, `http://…` or `/…`) with `{url}` where the picture's address goes, encoded as a URI component. Needed by `"proxy"` (H395). |
| `cid` | Content-ids (`<logo@shop>` or `logo@shop`) to the local address of each part (`blob:` or `data:image/…`): what `src="cid:…"` becomes. A content-id it does not name is left out. |
| `styles` | `false`: only the structure is kept (no `style=`, no sheet, no `class` or `id`, no colours, fonts or sizes as attributes, no `#` links). What an editor's paste wants: `html.clean(pasted, {styles: false})`. |

What is kept:

- **Elements**: text and its marks (`b i u s em strong small big sub sup
  code kbd samp var mark abbr cite dfn q del ins time bdi bdo ruby rt rp
  font span tt strike acronym`), blocks (`p div h1`–`h6 blockquote pre
  address article aside section header footer main nav hgroup figure
  figcaption center hr br wbr details summary`), lists (`ul ol li dl dt
  dd`), tables (`table caption thead tbody tfoot tr th td col colgroup`),
  `a` and `img`. `xmp`, `listing` and `plaintext` become `pre`; `nobr` a
  `span` that does not wrap. Anything else that is not listed below keeps
  its content without itself (`o:p`, `form`, `button`, `label`, `marquee`,
  an unknown tag).
- **Left out whole, with what is inside**: `script style template noscript
  noembed noframes iframe frame frameset object embed applet param audio
  video source track picture canvas map area svg math select textarea input
  option datalist output progress meter head title meta link base dialog`,
  and every comment. (A `<style>`'s sheet is read first: below.)
- **Attributes**: `dir lang title hidden role aria-label aria-hidden`
  everywhere; `align valign width height bgcolor border` (looks); `href` and
  `name` on `a`; `src alt hspace vspace` on `img`; a table's `cellpadding
  cellspacing frame rules summary background`, a cell's `colspan rowspan
  nowrap abbr scope headers background`; `start type reversed value` on
  lists; `color face size` on `font`; `span` on columns; `datetime`;
  `open`; and `style`, `class`, `id`. No `on…`, no `srcset`, `formaction`,
  `action`, `ping`, `poster`, `xlink:href`, `http-equiv`, nothing else.
- **Addresses**: a link keeps `http`, `https`, `mailto` and `tel` (after
  the browser's own tidying: spaces at the ends, tabs and line breaks
  inside, entities), and `#name` within the letter; `//host` is `https:`.
  Anything else (`javascript:`, `data:`, `vbscript:`, a relative path) is
  left out, and the link stays as words. A kept link opens apart:
  `target=_blank rel="noopener noreferrer"`. A picture keeps `data:image/`
  PNG, GIF, JPEG, WebP, BMP or AVIF (no SVG), a `cid:` it was given, and a
  remote one as `images` says.
- **CSS**, in `style=` and in every `<style>` (gathered into one sheet): a
  property is kept only from a list of ones that cannot name an address
  (colours, backgrounds, borders, margins and padding, sizes, fonts and text,
  `display`, `float`, `overflow`, `visibility`, `opacity`, `box-shadow`,
  list numbering, table layout, flex; `position` only `static` or
  `relative`); a value only of words, numbers, colours, strings and the
  functions `rgb rgba hsl hsla hwb lab lch oklab oklch color-mix calc min max
  clamp` and the gradients. `url()` only in `background` and
  `background-image`, as `images` says. A rule is kept with its selector of
  names, classes, ids, attributes and `:not :is :where :nth-…`; `@media`
  with what is inside it; no `@import`, `@font-face` or other at-rule. The
  CSS is read into tokens and written out from them, quoted and escaped
  anew, so no comment, escape or `</style>` of the letter's reaches it.
- **Names**: an `id` and an `a name=` are given `h-` before them (so none
  is a name of the page's own), and `href="#x"` and a `#x` selector follow.

### html.text

`html.text(text)` (or `html.text(text, {links: false})`) waits and gives
the document as plain text, for a list's snippet, search, or quoting in a
reply:

- **Blocks** each start a line; a paragraph, a heading, a table, `pre`, a
  quote and a list of the top level have a blank line around them. `<br>`
  is a line break, two in a row a blank line.
- **Lists**: an item after `-`, or its number in an `ol` (from `start`);
  a list inside one is indented two spaces.
- **Links**: the words, then the address in `<…>` (unless the words are the
  address, a `mailto:`'s mail or a `tel:`'s number); `{links: false}` gives
  the words alone.
- **Quotes**: a `blockquote`'s lines after `> `, a quote in a quote after
  `>> `.
- **Tables**: a row on a line, its cells with a space between.
- **Entities** are their characters (the parser's own reading); a picture
  is its `alt`.
- **Spaces** run together as a browser runs them, but in `pre`, which keeps
  its own; characters with no width (`&zwnj;`, soft hyphens, …) are left out.
- **Not said**: the head, scripts, styles, `template`, forms' fields, and
  what is `hidden` or `display: none` / `visibility: hidden` (a letter's
  hidden "preheader" included).

### htmlframe

```mote
htmlframe html=letter images="block" proxy="/img?u={url}" cid=parts link=open cleaned=seen
```

A letter shown cleaned, in a frame as tall as the letter. It cleans what it
is given itself (in the worker pool, with `html.clean`'s options), so nothing
uncleaned can reach it, and builds the cleaned tree into the frame element by
element: no text of the letter is ever parsed there.

| Attribute | Type | |
|---|---|---|
| `html` | string | The letter as it came. |
| `images`, `proxy`, `cid`, `styles` | | As `html.clean` takes them. A change cleans and draws it again. |

Events: `link` hands the address of a link pressed in the letter (a press,
a middle press, Enter on it); without a `link=` the address opens in a new
tab with no opener and no referrer. `cleaned` hands what `html.clean`
gives, each time the letter is drawn.

**What the frame is.** An `iframe` of the page's own, `sandbox="allow-same-origin"`
and nothing else: no scripts, no forms, no pop-ups, no navigating the page.
Of the same origin so that the page's own script can build its document and
read its height; nothing inside can use that, as nothing inside can run
(`allow-same-origin` is unsafe beside `allow-scripts`, which could take the
sandbox away: that pair is never given, and `H232` refuses it in markup).
Its document has a policy of its own, `default-src 'none'`, pictures only
from `data:`, `blob:` and where `images` lets them come (the proxy's origin,
or `https:` and `http:` for `"allow"`), and `no-referrer`; under
`policy=strict` the page's own policy holds in it too, so list the proxy in
`images=` ([delivery.md](delivery.md#the-strict-policy)). Styles are set
through each element's `style` and one constructed sheet, which no policy
refuses: under `policy=strict` the letter is drawn styled, with nothing
refused. A letter is laid out as it asked (no doctype: quirks; an XHTML or
HTML 4 transitional one: limited quirks; else standards), on white, with no
margin of the frame's own. A new letter, or other `images`, is drawn in a
new frame that takes the old one's place when whole (a document's policy
cannot be loosened). The frame's height follows its width, pictures as they
arrive, and a `details` opened.

### In a worker and on the back end

`html.clean` and `html.text` work the same in a page (the worker pool), in an
`off fn` (the battery is called in that worker), and in a `server fn` (in
place). `htmlframe` is the page's. A mailbox's import is a loop in an `off
fn`, or many calls from an action, which the pool spreads over its workers.

**What it costs a page.** `assets/html.<hash>.wasm`: 231 KB, 84 KB gzipped
(of which the named character references are a quarter), fetched by the
first call, as every battery is.

## font

A font file, read by Mote's own code: its facts, a line of text laid out as
the font itself sets it (the same numbers on every machine), each glyph's
outline, and the file given to the browser under a name.

```mote
// docs: whole
state face: font? = none
state words = "Waffle"
state shapes: number[][][] = []
state wide = 0
state said = ""

action open
  let file = fs.pick(".ttf,.otf,.woff")?
  if file == none return
  let f = font.open(file.data)?
  face = f
  said = `${f.family} ${f.style}: ${f.glyphs} glyphs`
  font.use(f, "Picked")?
  set()

action set
  let f = face
  if f == none return
  let line = font.layout(f, words, {size: 96})?
  wide = line.width
  let glyphs = font.outline(f, words, {size: 96, x: 16, y: 120})?
  shapes = glyphs.flatMap(g => g.contours)

watch words
  set()

fn show(g: pen, size: {width: number, height: number, time: number})
  draw.clear(g, "card")
  draw.line(g, 16, 120, 16 + wide, 120, {color: "line"})
  draw.path(g, shapes, {fill: "fg"})

column gap=8 padding=16
  row gap=8
    button "Open a font" press=open
    input value=words
  surface draw=show width=100% height=160
  text said font-family="Picked" font-size=24
  text (failure(open) ?? failure(set) ?? "") color=danger
```

| Call | Gives |
|---|---|
| `font.open(bytes)` | A `font`: a .ttf, .otf, .ttc or .woff, read. `font.open(b, 1)` is a collection's second face. |
| `font.layout(f, "words", {size: 24})` | The line laid out: `{width, glyphs}`. |
| `font.outline(f, "words", {size, x, y})` | The same glyphs, each with `contours`: its outline where it stands. |
| `font.metrics(f, "abc…")` | `{advance, kern, glyph, ligature}`: tables for code that sets text itself. |
| `font.has(f, "é")` | Whether every character has a glyph. |
| `font.subset(f, "the text")` | A font file with only the outlines that text needs, as bytes. |
| `font.table(f, "CFF ")` | One table's bytes, as the file has them. |
| `font.use(f, "Inter")` | Gives the file to the browser under that name; the name comes back. |

Every call waits and can fail: settle each with `else` or `?`.

**A `font`** is a record: the file's facts, and `data`, the file.

| Field | Is |
|---|---|
| `family` `style` `name` `postscript` | Its names: `"Inter"`, `"Bold"`, the full name, the PostScript name. |
| `weight` `italic` `fixed` `variable` | 400, 700 …; whether it is italic, fixed-width, a variable font. |
| `kerning` `ligatures` | Whether it has any that Mote reads. |
| `outlines` | `"glyf"` (TrueType) or `"cff"`. |
| `units` | Units to the em in the file. |
| `ascent` `descent` `lineGap` `capHeight` `xHeight` | In ems. |
| `box` | `[left, bottom, right, top]` of all its glyphs, in ems. |
| `underline` `underlineSize` `angle` | Where the underline sits and how thick, in ems; the slant in degrees. |
| `glyphs` `faces` | How many glyphs; how many faces the file holds. |
| `data` | The file, as bytes (a collection's face, or a WOFF, as a plain font of its own). |

**Its lengths are in ems**: times a size, they are pixels.

**`font.layout`** gives `{width, glyphs}`; each glyph is `{id, at, chars, x,
y, advance}`: which glyph, where in the text it starts and how many
characters it stands for (a ligature: 2), where it goes, and how far the
pen then moves. The options:

| Option | Means |
|---|---|
| `size` | Pixels to the em. With no size, everything is in ems. |
| `x`, `y` | Where the line starts; `y` is its baseline. |
| `tracking` | Added after each glyph. |
| `kerning: false` · `ligatures: false` | Leaves them out. |

**`font.outline`** takes the same options and gives the glyphs, each with
`contours`: every contour a closed list of points as `draw.path` takes them
(`[x, y]`, and `[c1x, c1y, c2x, c2y, x, y]` for a curve), y growing
downwards from the baseline. A glyph's contours are one shape: a contour
inside another is a hole. So `draw.path(g, glyph.contours, {fill: "fg"})`
draws a glyph, and `paint.path` does the same on a sheet.

**`font.metrics(f, "AVo")`** is for code that sets text itself or writes it
by glyph (a PDF): `advance` (each character's advance), `glyph` (its glyph's
number), `kern` (for each two characters, how much nearer they sit than
their advances say: kerning, and what a ligature of the two saves),
`ligature` (the one glyph two become, if any). Each is a record by the
characters (`{A: 0.6}`, `{AV: -0.08}`), as `json`; lengths in ems. With no
characters named, the keyboard's.

**`font.subset`** keeps the glyphs' numbers as they were, so what was laid
out with the whole font still names the right glyphs (to embed in a PDF or
an SVG). A subset draws but does not kern: lay out with the whole one.

**`font.use(f, "Inter")`** makes the file a family the browser knows (the
font's own family if no name is given). Then `font-family="Inter"` in
markup, and `font: "Inter"` in `draw.text` and `paint.text`, are that font.
Surfaces on the page are drawn again. Several files may share a name, as a
family's weights and italics do.

What is read: TrueType and CFF outlines (a variable font's default shape),
kerning from GPOS pairs or the old `kern` table, GSUB's standard ligatures.
What is not: what joins or reorders a script's letters, ligatures made by
context, Apple's own kerning tables. A WOFF 2 is refused: give the .ttf,
.otf or .woff.

Refused by the checker: `font.load` (`font.open`), `font.measure`
(`font.layout`), `font.glyph` (`font.outline`), `font.register`
(`font.use`), each with the right name (`H063`).

Source: `batteries/font/lib.rs` (its header says what is read);
`runtime/shared/batteries.mote`, part `FT`; `runtime/page/font.mote`, part
`UFT`.

## Highlight, CodeBlock and Markdown

Kit components over the `syntax` battery ([kit.md](kit.md)):

```mote
// docs: whole
state code = "const n: number = 1\nconst m = n + 1\n"
state answer = "# Hello\n\nSome **bold** text and a [link](https://example.com).\n"
state busy = false

column gap=16 padding=16
  Highlight text=code lang="ts" lines start=12 marks=[{line: 13, kind: "added"}]
  CodeBlock code=code language="ts" title="a.ts"
  Markdown text=answer streaming=busy
```

- `Highlight text=code lang="ts" lines start=12 wrap marks=[{line: 14,
  kind: "added"}]`: code, coloured. `lines` numbers them from `start`;
  `marks` tints lines (`added`, `removed`, `highlighted`). A language the
  battery does not know is shown plain.
- `CodeBlock code=… language="ts" title="a.ts"` is `Highlight` in a frame
  with a copy button ([kit/code.md](kit/code.md)).
- `Markdown text=answer streaming=busy`: a document, laid out as real
  elements ([kit/markdown.md](kit/markdown.md)). With `streaming`, text
  that is still arriving is drawn as it comes, and blocks that did not
  change are kept.

## The editor

`editor value=source lang="ts"` is a code editor that colours its text with
the same battery: [widgets.md](widgets.md#editor).

## Pitfalls

- **Use raw strings for patterns.** In `"\d+"` the backslash is dropped and
  the pattern is `d+`.
- **`re.find` gives `T?`.** Settle it: `m?.text`, `if m …`.
- **`re.replace` replaces every match**, not the first.
- **A pattern written out is checked when the program is built; one made at
  run time throws when used.** In a derive or a binding nothing catches it:
  the binding stops updating and the console says why. Build patterns from
  user input with `re.escape`, ask `re.check(p)` first, or run them in a fn
  you call with `else`.
- **No backreferences or lookarounds.** `re` refuses them (H301, or a throw
  for a pattern made at run time); see the table above for what to write.
- **A font's numbers are ems until you give a size.** `f.ascent * 24` is
  pixels at 24 px; `font.layout(f, text)` with no `size` is in ems too.
- **`font.layout` is not the browser's measuring.** It is the font's own
  advances, kerning and standard ligatures, the same everywhere. The
  browser may shape a line differently (other features, another script):
  for text the browser draws, `draw.measure`
  ([drawing.md](drawing.md#surface-2d)).
- **`search`, `syntax` and `font` wait.** They cannot go in a derive. Keep the
  result in state, or use a resource:
  `resource doc: json = syntax.parse(text, "markdown")`.
- **`html.clean`'s `html` is for a document of its own.** Its `<style>`
  applies to the whole document it is put in: show a letter with
  `htmlframe`, and put a paste into a page cleaned `{styles: false}`.
- **`images: "block"` is the default.** A remote picture is fetched only when
  the program says `"proxy"` or `"allow"`, typically after the person asks.
- **A syntax tree is `json`.** Fields are not checked: a misspelt
  `c.nmae` is `none` at run time, not an error.

## Where a new call goes

`re.*` under Patterns; `html.*` and `htmlframe` under HTML; `search.*` under search; `syntax.*` under syntax
(a new language in the Languages list; a new node kind in Code or in the
Markdown table); `font.*` under font. A component built on them is indexed in
[kit.md](kit.md), with its own page under `kit/`.

## In the source

| What | Where |
|---|---|
| Signatures | `compiler/src/types.rs`: `Checker::call` (`re`, `search`, `syntax`, `font`); `font`, `glyph` |
| Raw strings | `compiler/src/lex.rs` |
| `re` | `runtime/shared/patterns.mote` |
| `search`, `syntax`, `font`, `html` drivers | `runtime/shared/batteries.mote`: parts `SE`, `SY`, `FT`, `HT`; a page's searchers, `runtime/page/workers.mote`: part `SK` |
| `htmlframe` | `runtime/page/htmlframe.mote`: part `HF`; `compiler/src/tables.rs` (`widget`), `view.rs` |
| `html` | `batteries/html/core.rs` (tokenizer, tree builder), `clean.rs` (allow-list, writing out, text), `css.rs`; `entities.rs` written by `tools/html-entities.mjs`; tested by `compiler/src/tests_html.rs` and `tests/html.real.mjs` (`real_html`, with the published corpus `tests/html/fetch.sh` fetches) |
| `font.use` | `runtime/page/font.mote`: part `UFT` |
| The batteries | `batteries/search/lib.rs`, `batteries/syntax/lib.rs`, `batteries/font/lib.rs`; a grammar of your own is `batteries/grammar/lib.rs` (`batteries/syntax/grammar.rs` with the `re` engine), carried only by a program that has one |
| On the back end | `runtime/server/batteries.mote` |
| `Highlight`, `Markdown`, `CodeBlock` | `kit/code.mote` |
| Recorded behaviour | `tests/re`, `tests/search`, `tests/search_grows`, `tests/syntax`, `tests/font`, `tests/kit_code.real.mjs`, `tests/kit_markdown.real.mjs` |
