Skip to content

CodeBlock

The codeBlock node is designed to represent blocks of code within your document.

Usage

ts
import { defineCodeBlock } from 'prosekit/extensions/code-block'

const extension = defineCodeBlock()

Commands

setCodeBlock

Set the selected node to a codeBlock node.

ts
editor
.
commands
.
setCodeBlock
()

insertCodeBlock

Insert a new codeBlock node.

ts
editor
.
commands
.
insertCodeBlock
()

toggleCodeBlock

Toggle the selected node between a codeBlock node and a default node (e.g. a paragraph node).

ts
editor
.
commands
.
insertCodeBlock
()

setCodeBlockAttrs

Set the attributes of the selected codeBlock node.

ts
editor
.
commands
.
setCodeBlockAttrs
({
language
: 'javascript' })

Keyboard Interaction

Input ``` followed by an optional language name and press Enter or Space to create a new codeBlock node.

Press Enter three times at the end of or press Shift-Enter to exit the current codeBlock node.

Syntax Highlighting

You can use defineCodeBlockShiki to enable syntax highlighting for the codeBlock node using the Shiki library. defineCodeBlockShiki will only load used languages and themes asynchronously, which is useful for reducing the initial bundle size of your application.

ts
import { defineCodeBlockShiki } from 'prosekit/extensions/code-block'

const extension = defineCodeBlockShiki({ themes: ['github-light'] })

If you want to use a different syntax highlighter or have more control over the syntax highlighting, you can use the defineCodeBlockHighlight function to create an extension. This function accepts a parser object, defined by the prosemirror-highlight library. For more details on how to use the other syntax highlighters, refer to the prosemirror-highlight documentation.

ts
import { defineCodeBlockHighlight } from 'prosekit/extensions/code-block'
import { parser } from './my-prosemirror-highlight-parser'

const extension = defineCodeBlockHighlight({ parser })