| title | Code Blocks |
|---|---|
| description | How to add syntax highlighting to code blocks. |
| imageTitle | Code Blocks |
Code blocks are a simple way to display formatted code with syntax highlighting.
Code blocks by default are a simple way to display code. But, BlockNote also supports more advanced features like:
- Syntax highlighting
- Custom themes
- Multiple languages
- Tab indentation
Configuration Options
type CodeBlockOptions = {
indentLineWithTab?: boolean;
defaultLanguage?: string;
supportedLanguages?: Record<
string,
{
name: string;
aliases?: string[];
}
>;
createHighlighter?: () => Promise<HighlighterGeneric<any, any>>;
};indentLineWithTab: Whether the Tab key should indent lines, or not be handled by the code block specially. Defaults to true.
defaultLanguage: The syntax highlighting default language for code blocks which are created/inserted without a set language, which is text by default (no syntax highlighting).
supportedLanguages: The syntax highlighting languages supported by the code block, which is an empty array by default.
createHighlighter: The Shiki highliter to use for syntax highlighting.
BlockNote also provides a generic set of options for syntax highlighting in the @blocknote/code-block package, which support a wide range of languages:
import { createCodeBlockSpec } from "@blocknote/core";
import { codeBlockOptions } from "@blocknote/code-block";
const codeBlock = createCodeBlockSpec(codeBlockOptions);See this example to see it in action.
Type & Props
type CodeBlock = {
id: string;
type: "codeBlock";
props: {
language: string;
} & DefaultProps;
content: InlineContent[];
children: Block[];
};language: The syntax highlighting language to use. Defaults to text, which has no highlighting.
To create your own syntax highlighter, you can use the shiki-codegen CLI for generating the code to create one for your chosen languages and themes.
For example, to create a syntax highlighter using the optimized javascript engine, javascript, typescript, vue, with light and dark themes, you can run the following command:
npx shiki-codegen --langs javascript,typescript,vue --themes light,dark --engine javascript --precompiled ./shiki.bundle.tsThis will generate a shiki.bundle.ts file that you can use to create a syntax highlighter for your editor.
Like this:
import { createHighlighter } from "./shiki.bundle.js";
export default function App() {
const editor = useCreateBlockNote({
schema: BlockNoteSchema.create().extend({
codeBlock: createCodeBlockSpec({
indentLineWithTab: true,
defaultLanguage: "typescript",
supportedLanguages: {
typescript: {
name: "TypeScript",
aliases: ["ts"],
},
},
createHighlighter: () =>
createHighlighter({
themes: ["light-plus", "dark-plus"],
langs: [],
}),
}),
}),
});
return <BlockNoteView editor={editor} />;
}See the custom code block example for a more detailed example.