Selfscribe on a site, in an app, anywhere
To show a Selfscribe document on your own page, render it to HTML and put it in an element:
import { init, renderToHtml } from "selfscribe";
await init();
const { html, css } = renderToHtml("# Harbour notes\n\nThe market opens at six.", { scope: "#post" });
document.querySelector("#post").innerHTML = `<style>${css}</style>${html}`;
init loads the engine once. renderToHtml parses and renders in one call and frees the
engine's memory before it returns. With scope, the document's own CSS styles only #post
and never the page around it. Without scope, put the HTML inside an element with the class
self-doc: a document's named colours and shared classes apply only there.
This page is for anyone who wants Selfscribe somewhere other than the app: a blog, a forum, a
docs site, a notes app. The engine is written in Rust. It runs as WebAssembly (about 330 KB
gzipped, plus a few KB of JavaScript) and as a command line tool, self. Both give the same
HTML for the same text, and the conformance suite in spec/conformance checks both. The output
is plain, safe HTML. It has no scripts, its links and CSS are checked, and the document's own
rules come as one <style> block.
Add an editor with CodeMirror
#selfscribe-cm6 turns a CodeMirror 6 editor into the app's editor.
It highlights each document by its own rules, draws the text as you type (hybrid mode),
suggests words in the rules block and shows problems in place:
import { EditorView } from "@codemirror/view";
import { createWorker } from "selfscribe/worker";
import { selfscribe, selfscribeEditing } from "selfscribe-cm6";
const worker = createWorker({ resolve: async () => null }); // no other files to read
const parse = (src) => worker.parse(src);
new EditorView({
doc: "# Harbour notes\n",
parent: document.querySelector("#editor"),
extensions: [selfscribe({ parse }), selfscribeEditing({ render: parse })],
});
The engine parses in a Web Worker, so typing never waits on it. The editor starts in hybrid
mode. Pass mode: "source" to start with plain text, and call setMode(view, "hybrid") or
setMode(view, "source") to switch later.
To draw charts and diagrams inside the editor, pass plugins: names to worker.parse, give
selfscribe a hydrate function and call setBlockDisposer(dispose). The package's
README has the whole setup. It also covers a preview
beside the editor that draws only what is on screen (VirtualPreview), and plainMessage,
which turns an engine message into one a person can act on.
Pick where it runs
#| Where | Use | Good for |
| Node, Bun, Deno | selfscribe/node (WASM) | a server that renders on save or on request |
| Edge workers (Cloudflare, Deno Deploy, Vercel Edge) | selfscribe + init(wasmModule) | rendering close to readers, no server |
| The browser | selfscribe or selfscribe/worker (off the main thread) | live previews, comment boxes, offline apps |
| PHP, Python, Ruby, Go, anything | self serve --stdio (one long-lived process) or self render | a site in any language |
| Static sites | self render --standalone, or the app's Export › Website | a folder of pages |
Render on a server: Node, Bun or Deno
#import { init, renderToHtml, settingOf } from "selfscribe/node";
await init(); // reads the bundled .wasm from disk, once
const { html, css, title, settings, diagnostics } = renderToHtml(text, { path: "post.self" });
const lang = settingOf({ settings }, "lang"); // "fr" for `set lang fr`
settingOf reads any set value the same way, such as page, width or style.
Render when a post is saved and store the HTML. A render takes milliseconds, and a stored page
takes none. The options below let a document read other files (resolver), fill in
{{name}} values (vars) and mark the plugins your page draws (plugins).
To keep the parsed document and render it more than one way, use parse and free it yourself:
import { init, parse, render_html } from "selfscribe/node";
await init();
const doc = parse(text, { path: "post.self" });
try {
const { html, css } = render_html(doc);
// …
} finally {
doc.free();
}
renderHtml, renderTree and renderAst are camelCase names for the spec's render_html,
render_tree and render_ast.
Render at the edge
#import { init, parse, render_html } from "selfscribe";
import wasm from "selfscribe/wasm/selfscribe_wasm_bg.wasm"; // your bundler's WASM import
await init(wasm);
The selfscribe entry has no Node imports, so it runs on any runtime with WebAssembly. init
also takes bytes, a Response or a URL.
Draw plugins in the browser
#Charts, diagrams, data views and maths are plugins. The server marks their blocks, and the page
draws them with hydrate from selfscribe/client. Register the plugins first:
import { hydrate } from "selfscribe/client";
import { registerPlugins } from "selfscribe-plugins";
const { names } = registerPlugins({ only: ["chart", "math", "mermaid"] });
// render on the server with { plugins: names } (the same list), then in the page:
await hydrate(document.querySelector(".self-doc"));
Use the same list on both sides. The server marks only the plugins it is told about. When you
take rendered output away, call dispose(root) so plugins stop their timers.
Show a live preview in the browser
#selfscribe/worker parses in a Web Worker, so typing never waits on the engine:
import { scopeRuleCss } from "selfscribe";
import { createWorker } from "selfscribe/worker";
import { dispose, hydrate } from "selfscribe/client";
import { registerPlugins } from "selfscribe-plugins";
const { names } = registerPlugins(); // the plugins this page draws
const files = { "house-style.self": "~~~ selfscribe\nuse markdown\n~~~\n" }; // what `use ./x.self` may read
// `resolve` answers `use ./house-style.self` and friends; null when there is no such file.
const worker = createWorker({ resolve: async (key) => files[key] ?? null });
const preview = document.querySelector("#preview");
async function show(text) {
const result = await worker.parse(text, { path: "post.self", plugins: names });
dispose(preview); // plugins drawn last time stop their timers
// The document's rules style only the preview, not the page around it.
preview.innerHTML = `<style>${scopeRuleCss(result.css, "#preview")}</style>${result.html}`;
await hydrate(preview);
}
To see it all work in a browser, run the demo in
packages/selfscribe/demo. It shows the engine, plugins, maths
and a form. After building, run node packages/selfscribe/demo/serve.mjs and open the address
it prints. Its main.js is a plain ES module to copy from.
Render from any other language
#self serve --stdio reads one JSON request per line and answers one per line:
{"id": 1, "method": "render", "params": {"source": "# Hi", "path": "post.self"}}
{"id": 1, "result": {"html": "<h1>Hi</h1>\n", "css": "", "blocks": [...], "diagnostics": []}}
Start it once with your app (PHP-FPM, a Python worker, a Go service) and keep the pipe open.
For a site built ahead of time, self render post.self -o post.html --standalone writes a
whole page. A runtime with a WebAssembly host can also load the .wasm directly: wasmtime for
Python and Go, wasmer for PHP.
Take short texts from users: forums, comments, chat
#A reply is Markdown unless the site says otherwise, so Selfscribe suits these well.
- Choose the rules for your readers. Parse with your own rulebook, so every post gets your
syntax: mentions, spoilers, quotes with a name. Pass
defaults: [{ key: "forum.self", level: "project" }]and aresolverthat serves it. - Keep the switches off. Leave
unsafeHtml,formsandallowRemotefalse. Then postsget no
scriptoriframe, no fields to fill in and no imports from the web. Passpluginsonly for the plugins your page draws. - Keep each post's CSS to itself. Put each post in its own element and pass its selector:
renderToHtml(text, { scope: "#post-42" }). The post's rules then style only that element, so two posts cannot restyle each other or your page.position: fixedis left out. Give the elementposition: relative; contain: paint; overflow: hiddenas well, so nothing a post positions can reach outside its box. - Render once. Store the HTML with the post, and render again only when the text changes.
Style the page around the document
#The engine's css styles the document's own rules. The page around it comes from one shared
stylesheet, STYLES_CSS in selfscribe/styles. It holds the fonts, colours and width, and the
looks a document asks for with set style paper numbered:
import { STYLES_CSS, styleClasses, styleWords } from "selfscribe/styles";
const words = styleWords(settingOf({ settings }, "style")); // ["paper", "numbered"]
const page = `<style>${STYLES_CSS}${css}</style>
<div class="self-page self-base ${styleClasses(words)}"><article class="self-doc">${html}</article></div>`;
To match your site, set these variables on .self-page: --doc-bg, --doc-fg,
--doc-heading, --doc-link, --doc-border, --doc-font, --doc-font-heading and
--doc-measure. --doc-measure is the reading column: set width 40em means
--doc-measure: 40em. Use the lang setting for the page's lang attribute, and page for
your print CSS.
A document's fonts (set font Literata, set heading-font Inter) are only names. Set
--doc-font and --doc-font-heading to them with your own fallbacks, such as
"Literata", Georgia, serif. Load the font yourself if your site offers it. The app loads its
own gallery of open fonts.
Options of parse
#renderToHtml takes the same options. So does worker.parse, except resolver: a worker
reads files through the resolve you gave createWorker.
| Option | Default | What it does |
path | none | the document's name. Messages mention it, and a relative use starts from its folder |
resolver(key) | none | returns the text of a file the document uses or includes, or null. It is called synchronously, so load files first |
defaults | none | rulebooks every document gets first, such as [{ key: "forum.self", level: "project" }]. A document with no rules reads as Markdown anyway |
vars | {} | values for {{name}} in documents |
plugins | [] | the plugins your page draws. The engine marks their blocks for hydrate instead of reporting them as unknown |
unsafeHtml | false | lets through elements that are normally refused, such as script. Keep it off for anything users write |
forms | false | draws form fields that can be filled in. Otherwise they show, disabled |
allowRemote | false | passes use https://… imports to your resolver |
allowRe | false | allows the full-form rules that use regular expressions |
sourceSpans | false | marks each block with where it came from in the text, for editors |
scope (renderToHtml only) | none | a selector for the element you put the HTML in. The document's CSS applies only inside it |
The spec's own spellings, unsafe_html, allow_remote and allow_re, work too.
Keep it safe
#- Documents never run code. Rules are patterns and CSS, and only plugins you register draw
anything active.
- Links and pictures keep safe schemes only:
http,https,mailtoand relative links. CSSin rules cannot load anything, so
url(and@importare refused. - With a strict Content-Security-Policy, use the element tree below instead of HTML strings.
Put the returned CSS in your own stylesheet.
- Your
resolverdecides which files a document can read. The engine never asks for a keywith
..in it.
Link documents to each other
#A site of many documents should do what the app's exporter does. A link to notes.self (or
notes, Notes.MD, notes.html) goes to the page that file is published as. A link to
#Getting started finds the heading by its text. The editor's apps/editor/src/ui/links.ts
does exactly this with resolveLink, withHeadingIds and fragmentId, and has tests to copy.
Render without HTML strings
#Some pages may not take HTML strings: a strict Content-Security-Policy, a plugin review that
forbids innerHTML, a native view. Render to data instead:
import { init, parse, render_tree } from "selfscribe";
import { buildDom } from "selfscribe/client";
await init();
const doc = parse(source);
const tree = render_tree(doc); // { css, blocks: [{ from, to, nodes }] }, nodes in JsonML
for (const block of tree.blocks) container.append(buildDom(block.nodes));
doc.free();
buildDom builds with createElement and keeps SVG and MathML in their namespaces. It drops
event attributes, script URLs and executable scripts. self render --tree FILE prints the same
JSON. A native app can walk the JsonML (["p", {}, "text", ["em", {}, "x"]]) and map each tag
to one of its own views.
Support Selfscribe in another editor
#Selfscribe files are text, so any editor can open them. The self tool checks and renders them
from a script or a git hook. For a web editor of your own, use selfscribe-cm6 as above.
A plugin for another editor is a thin layer over the same pieces. It parses with selfscribe,
shows the HTML and runs hydrate for plugins. An Obsidian plugin, for example, would register
the .self extension with a view that renders the file. It would add a code block processor
for ``` `selfscribe ``` fences inside Markdown notes, so a vault can mix both.
Write a plugin
#See PLUGINS.md. A plugin is a small JavaScript module. The engine knows only its name, so documents stay text and still render, plainly, everywhere.
Install the packages
#The packages are not on npm yet, because the name selfscribe is taken there. Until they are,
build them from this repository and pack them into files your project can install:
pnpm install
pnpm --filter "./packages/**" build
pnpm --dir packages/selfscribe pack --pack-destination ../../dist-out
pnpm --dir packages/selfscribe-plugins pack --pack-destination ../../dist-out
pnpm --dir packages/selfscribe-cm6 pack --pack-destination ../../dist-out
Then install them in your project. The version in the file names may differ:
npm install ../Selfscribe/dist-out/selfscribe-0.1.0.tgz ../Selfscribe/dist-out/selfscribe-plugins-0.1.0.tgz
selfscribeis the engine.selfscribe-pluginsadds charts, diagrams, maths and data views. Skip it if you only needtext.
selfscribe-cm6is the editor half, for CodeMirror 6.
Pack them rather than linking the folders. Packing turns the repository's links between
packages into normal dependencies, and a plain file: link would not. They are ES modules
only.
The packages have their own version numbers, 0.x until they are published, separate from the app's. CHANGELOG.md says which app version each change came with.
To build the command line tool, run cd engine && cargo build --release -p selfscribe-cli.