Skip to content

Code blocks

import { codeBlockPlugin, codeMirrorPlugin } from '@the-sumeet/sveltedown';
const plugins = [
codeBlockPlugin({ defaultCodeBlockLanguage: 'ts' }),
codeMirrorPlugin({ codeBlockLanguages: { ts: 'TypeScript', css: 'CSS', '': 'Plain text' } })
];

codeBlockPlugin imports and exports fenced code blocks, but doesn’t edit them: it uses the registered code block editors. codeMirrorPlugin registers a CodeMirror editor with syntax highlighting and a language select.

codeMirrorPlugin option
codeBlockLanguages Either a record of key to label, or an array of { name, alias, extensions, support }. @codemirror/language-data’s languages can be passed directly.
codeMirrorExtensions CodeMirror extensions added to every code block.
autoLoadLanguageSupport Load highlighting for known languages on demand. Default true.

Arrow keys move out of a code block at its start and end, and Backspace in an empty block removes it.

Register a descriptor to edit some code blocks with your own component, for example a live preview:

import { codeBlockPlugin, type CodeBlockEditorDescriptor } from '@the-sumeet/sveltedown';
import MermaidEditor from './MermaidEditor.svelte';
const mermaid: CodeBlockEditorDescriptor = {
priority: 10,
match: (language) => language === 'mermaid',
Editor: MermaidEditor
};
const plugins = [codeBlockPlugin({ codeBlockEditorDescriptors: [mermaid] })];

The component receives code, language, meta, nodeKey and focusEmitter. It changes the block with useCodeBlockEditorContext(), which has setCode, setLanguage and setMeta. Descriptors with a higher priority win, so a low-priority one that matches everything works as a fallback.