Code
The code plugin adds code blocks made of editable lines, in a language picked in their header and highlighted with TanStack Highlight, with tab, auto-pairing and copy.
createCodePlugin() adds code blocks. A code block is an island that holds one codeLine child per line of code, in a language its header picks; each line is highlighted with TanStack Highlight (@tanstack/highlight, a dependency of edytor), whose grammars load the first time a line of their language renders.
<script lang="ts">
import { Edytor, createCodePlugin } from 'edytor';
</script>
<Edytor plugins={[createCodePlugin()]} />
createCodePlugin() without options makes code blocks with no header (the header and its language list are your header and menu snippets, see Languages). Importing it also imports its stylesheet, which keeps the code’s spaces and lines and scrolls it sideways; the panel and the syntax colours are the Notion theme’s.
Try it
Click a block’s language to pick another, type ``` at the start of an empty line for a new block, and press Tab in a line to indent it. The editor is local to this page: a reload resets it.
Customize
The header and the language list are your snippets (header, menu), so they can look like anything. Here, a window bar with the language as a tag, and a dark palette that filters the languages as chips.
<script lang="ts">
import {
Edytor,
createCodePlugin,
type CodeHeader,
type JSONDoc,
type LanguageMenu,
type Plugin
} from 'edytor';
// The page's document and the rest of your editor's plugins.
let { value, plugins = [] }: { value?: JSONDoc; plugins?: Plugin[] } = $props();
// Code blocks drawn with the two snippets below.
const code = createCodePlugin({ header, menu });
</script>
<!-- A window bar: the language as a tag, Copy as a quiet button. -->
{#snippet header(header: CodeHeader)}
<div class="bar">
<span class="dots" aria-hidden="true"><i></i><i></i><i></i></span>
{#if header.editable}
<button class="tag" aria-label="Language: {header.label}" {@attach header.button}>
{header.label} ▾
</button>
{:else}
<span class="tag">{header.label}</span>
{/if}
<button
class="copy"
onmousedown={(event) => event.preventDefault()}
onclick={() => header.copy()}
>
{header.copied ? 'Copied' : 'Copy'}
</button>
</div>
{/snippet}
<!-- A dark palette: a filter over the languages as chips. -->
{#snippet menu(menu: LanguageMenu)}
<div class="palette">
<input
aria-label="Filter languages"
placeholder="Filter…"
value={menu.query}
oninput={(event) => menu.search(event.currentTarget.value)}
{@attach menu.keys}
/>
<div class="chips" aria-label="Languages" {@attach menu.popup}>
{#each menu.items as item, index (item.item.id)}
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="chip"
data-selected={item.selected}
data-current={item.current}
onmousemove={item.select}
onclick={item.run}
{@attach menu.option(index)}
>
{item.item.label}
</div>
{/each}
</div>
{#if menu.items.length === 0}
<div class="none" role="status">No match</div>
{/if}
</div>
{/snippet}
<Edytor {value} plugins={[code, ...plugins]} aria-label="Code demo" />
<style>
.bar {
display: flex;
flex: 1;
align-items: center;
gap: 10px;
}
.dots {
display: flex;
gap: 5px;
}
.dots i {
width: 9px;
height: 9px;
border-radius: 50%;
background: #ff5f57;
}
.dots i:nth-child(2) {
background: #febc2e;
}
.dots i:nth-child(3) {
background: #28c840;
}
.tag,
.copy {
padding: 1px 8px;
border: 1px solid #d9d7d2;
border-radius: 999px;
background: #fff;
color: #45433f;
font: 600 11px/18px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.04em;
text-transform: uppercase;
cursor: pointer;
}
.copy {
margin-left: auto;
border-color: transparent;
background: transparent;
}
.tag:hover,
.copy:hover {
border-color: #a8a5a0;
}
.palette {
width: 260px;
padding: 8px;
border-radius: 12px;
background: #1f2328;
color: #e6edf3;
box-shadow: 0 12px 32px rgb(0 0 0 / 0.25);
font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
input {
box-sizing: border-box;
width: 100%;
margin-bottom: 8px;
padding: 6px 8px;
border: 1px solid #3d444d;
border-radius: 8px;
background: #151b23;
color: inherit;
font: inherit;
outline: none;
}
.chips {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4px;
max-height: 200px;
overflow-y: auto;
}
.chip {
padding: 4px 8px;
border-radius: 6px;
cursor: pointer;
}
.none {
padding: 4px 8px;
color: #9198a1;
}
.chip[data-current='true'] {
color: #7ee787;
}
.chip[data-selected='true'] {
background: #2f81f7;
color: #fff;
}
</style>
languages?readonly CodeLanguage[]
The languages a code block may be in, in the picker's order.
readonly CodeLanguage[]CODE_LANGUAGESdefaultLanguage?string
The language of a code block whose data.language is unset.
string'javascript'import { createCodePlugin, CODE_LANGUAGES } from 'edytor';
// Python by default, and only the languages this app writes.
export const code = createCodePlugin({
defaultLanguage: 'python',
languages: CODE_LANGUAGES.filter((language) =>
['plaintext', 'python', 'sql', 'bash'].includes(language.id)
)
});
What it adds
| Definition | Kind | Details |
|---|---|---|
code |
block | An island that renders only its children, under a header with the language and a Copy button. |
codeLine |
block | One line of code. The default child of code. |
codeToken |
mark | A highlighting token, rendered as <span class="th-…">. Computed on render, never stored. |
A code block has one preset, “Code”, with the command id block.code, the markdown shortcut ``` (three backticks typed at the start of an empty block) and the slash menu section Media. Mod + Alt + 8 converts to it when the rich text plugin is loaded, as it is by default. An empty block converts in place, into a code block of one empty line. A block with text or children stays as it is: the command (the slash menu, the chord) inserts an empty code block after it instead, and the caret moves to its line. See Presets.
A stored code block looks like this:
{
"type": "code",
"data": { "language": "javascript" },
"children": [
{ "type": "codeLine", "content": [{ "text": "const idea = \"start somewhere\";" }] },
{ "type": "codeLine", "content": [{ "text": "console.log(idea);" }] }
]
}
Languages
A code block’s language is its data.language, an id from the plugin’s languages (code.language). A block without one, as every code block stored before the picker was, is in the default language, JavaScript. The header names the language by its label (code.language.label): a language the plugin does not list shows its id as stored, and its lines are plain text.
The header and the language list are your markup: createCodePlugin({ header, menu }), a Snippet<[CodeHeader]> drawn above each block’s lines and a Snippet<[LanguageMenu]> drawn under the button that opened it (without them, a code block has no header, and its language is set from code or a command). In the demo, as in Notion, the header’s language is a button (named “Code language: JavaScript”, with a chevron) that opens the language list under it, in the overlay (code.language.picker): a search field over the languages by label, the block’s own marked with a check and highlighted. Typing filters the rows by label or id (script keeps JavaScript and TypeScript, cpp keeps C++); a click on a row, or Enter on the highlighted one, sets data.language. A pick is one patchData command, so it is one undo step, refused in a readonly view, and seen by hooks; a collaborator’s concurrent edits of the block’s other data are kept. The block’s lines render again in the new language, its grammar loaded if it is the first of its kind. In a readonly view and a suggestion’s preview the header’s editable is false: show the label only.
The keyboard reaches it all:
| Keys | Where | Action |
|---|---|---|
| Alt + F10 | At a caret in a code line | Move the focus to the block’s language button (as to a toolbar) |
| Enter, Space, ArrowDown, ArrowUp | On the language button | Open the list, its search field focused |
| Escape | On the language button | Give the keys back to the code, the caret where it was |
| Typing | In the search field | Filter the languages; the first one left is highlighted |
| ArrowDown, ArrowUp | In the search field | Move the highlighted row, around the ends |
| Enter | In the search field | Pick the highlighted language |
| Escape | In the search field | Close the list, the language as it was |
The search field is a combobox naming the highlighted row (aria-activedescendant) of a listbox; the button carries aria-haspopup="listbox" and aria-expanded. A list the keys opened gives them back to its button; one a click opened, to the editor, its caret where it was. A press or a focus outside the list closes it, as does the view turning readonly.
The controllers’ attachments (header.button, menu.keys, menu.popup, menu.option(index)) give your markup these keys and this ARIA. See Menus and handles; the demo’s markup is CodeHeader.svelte and LanguageMenu.svelte in the repository’s registry/edytor/chrome (the edytor-chrome registry item, in your app after shadcn-svelte add).
CODE_LANGUAGES holds the default list, after Notion’s:
id |
Label | Grammar |
|---|---|---|
plaintext |
Plain text | none: no tokens |
bash |
Bash | shell |
cpp |
C++ | cpp |
css |
CSS | css |
diff |
Diff | diff |
docker |
Docker | dockerfile |
go |
Go | go |
html |
HTML | html, with css, js and ts for its style and script elements |
javascript |
JavaScript | jsx (also covers plain JavaScript) |
json |
JSON | json |
markdown |
Markdown | markdown |
mermaid |
Mermaid | mermaid |
php |
PHP | php |
python |
Python | python |
sql |
SQL | sql |
svelte |
Svelte | svelte, with css, js and ts |
toml |
TOML | toml |
typescript |
TypeScript | ts |
vue |
Vue | vue, with css, js and ts |
xml |
XML | html |
yaml |
YAML | yaml |
A CodeLanguage is { id, label, grammar?, load? }: grammar names the TanStack Highlight grammar its lines are tokenized with, and load resolves to that grammar and the ones it embeds. Add a language by passing your own row:
import { createCodePlugin, CODE_LANGUAGES, type CodeLanguage } from 'edytor';
const nginx: CodeLanguage = {
id: 'nginx',
label: 'Nginx',
grammar: 'nginx',
load: () => import('@tanstack/highlight/languages/nginx').then((m) => [m.nginx])
};
export const code = createCodePlugin({ languages: [...CODE_LANGUAGES, nginx] });
Highlighting
Grammars load lazily (code.language.lazy): JSX, the default language’s, ships with the plugin; every other grammar is a chunk of its own, loaded the first time a line of its language renders. Until it lands, those lines show as plain text; then they render again, highlighted. A grammar is loaded once per page and shared by every editor. loadCodeLanguage(language) starts a load ahead of time and resolves once it is there (a failed load is tried again at the next render).
Each codeLine declares a transformText that tokenizes its text with its code block’s language. Tokens become codeToken marks carrying the token’s class name. For const idea = "x"; the tokenizer answers a keyword token, plain text, a string token and plain text, rendered as:
<span data-edytor-mark="codeToken"><span class="th-keyword">const</span></span> idea = <span data-edytor-mark="codeToken"><span class="th-string">"x"</span></span>;
The tokens are decorations: they exist only in the rendered DOM, never in the document, so collaborators and the clipboard see plain text. Each line is tokenized on its own, so a construct spanning lines (a block comment) is highlighted line by line.
The Notion theme colors the th-* classes with Notion’s light syntax theme (each color darkened to a 4.5:1 contrast on the panel):
| Classes | Color |
|---|---|
th-comment, th-meta |
#63717f |
th-keyword, th-link |
#0077aa |
th-string, th-attr, th-selector, th-inserted |
#527a00 |
th-function, th-type |
#c2415c |
th-number, th-literal, th-tag, th-property, th-deleted |
#990055 |
th-variable |
#9b6300 |
th-operator |
#916737 |
Without the theme the tokens are uncolored; style those classes to theme it.
Editing
Inside a code line:
| Keys | Action |
|---|---|
| Enter, Shift + Enter | Start a new line. Enter in the empty last line (not the only one) leaves the block: the line is removed and a paragraph after the block takes the caret, one undo step |
| ArrowDown | In the last line, go below the block; at the end of the document, to an empty paragraph after its last block, created when needed (navigation) |
| Tab | At a caret, insert a tab character, or accept the line’s end suggestion. Over a selection, add a tab at the start of every line it touches, as one undo step; the selection keeps its characters |
| Shift + Tab | Remove one leading tab, or up to two spaces, from the caret’s line or every line the selection touches |
| Mod + A | Select the text of the whole code block; press again to select the code block |
| Escape | Discard the line’s end suggestions |
- Typing
(,[,{,"or'at a caret also inserts the closing character. A quote pairs only at a word boundary: the apostrophe indon'tstays single. - Typing a closing character (
),],},",') right before the same character steps over it instead of inserting another:f(a)types asf(a), notf(a)). - A line break inside a line splits it: each code line holds exactly one line of text.
- Backspace at the start of the first line and Delete at the end of the last line do nothing: a line never merges out of its block.
- Delete at the end of the block right before a code block removes that block if it is empty, and does nothing otherwise. The caret goes to the end of the text before the removed block, or to the start of the code when nothing comes before it.
- Backspace in an empty block right after a code block removes that block and puts the caret at the end of the last line. In a block with text it moves the caret to the end of the code and merges nothing.
- Deleting or cutting the whole code text (Mod + A, then Backspace, Delete or cut) leaves the code block with one empty line and the caret in it.
- A selection that ends at the start of a line leaves that line out of Tab and Shift + Tab, as code editors do.
- Tab and Shift + Tab over several lines change each line with its own operation (
insertTextordeleteText): a line a plugin vetoes stays as it is and the others still change, together one undo step (Refusing an edit). - The Copy button, shown while the block is hovered, writes the block’s text, lines joined with newlines, to the clipboard, and reads “Copied” for a moment.
A code block is an island: merges never cross its edge, and a block selection walked with the arrow keys does not enter it from outside. It is also not convertible, so the slash menu and markdown shortcuts do not apply inside it.
Styling
The plugin’s stylesheet keeps what makes the block work: the code keeps its spaces and lines (white-space: pre, a tab size of 2) and scrolls sideways, and the header is never selected; without a theme the header sits above the code. The Notion theme draws the block like Notion’s: a #f7f6f3 panel rounded 10px, padded 34px 16px 32px 32px, the header placed over its top padding (the demo’s: the language at the top left, a button with a chevron, shaded when hovered or open, ringed when focused from the keyboard, and the Copy button at the top right), the code in an SFMono-Regular, Menlo, Consolas stack at 85%. No utility classes are involved; everything goes through attributes and classes you can override:
| Selector | Element |
|---|---|
[data-edytor-type='code'] |
The block panel |
[data-edytor-code-header] |
Where your header renders, at the panel’s top: void chrome the caret never enters |
[data-edytor-code-language-button] |
Your language button (header.button marks it; [aria-expanded='true'] while its list is open) |
[data-edytor-code-language-panel] |
Where your language list renders, in the overlay |
pre.th-code |
The code area |
The Notion theme reads the panel’s colors from custom properties an app sets on the editor or the block: --edytor-code-background and --edytor-code-color (the panel and its text).
[data-edytor-type='code'] {
background: #1f1f1f;
color: #e6e6e6;
}
[data-edytor-type='code'] pre.th-code {
font-size: 14px;
}
Without --edytor-code-background, the Notion theme’s panel is --notion-code-panel.
Placement. The package places no popup: your markup places itself by the language list’s menu.anchor (the language button), a virtual element read live. With Floating UI, computePosition(anchor, element, { strategy: 'fixed', middleware: [offset(8), flip(), shift({ padding: 8 })] }) under autoUpdate; with bits-ui, customAnchor={anchor}. See Menus and handles.