Code Block
The code block feature allows you to insert and display formatted code snippets within a document, with syntax highlighting powered by Prism.js.
Introduction
In Univer Docs, code blocks enable you to:
- Insert code snippets: Add formatted code blocks anywhere in your document.
- Syntax highlighting: Automatically highlight code based on language.
- Exit and cancel: Easily exit or cancel code formatting from empty paragraphs.
Plugin Mode
Installation
pnpm add @univerjs-pro/docs-code @univerjs-pro/docs-code-uinpm install @univerjs-pro/docs-code @univerjs-pro/docs-code-uiyarn add @univerjs-pro/docs-code @univerjs-pro/docs-code-uibun add @univerjs-pro/docs-code @univerjs-pro/docs-code-uiUsage
import { UniverDocsCodePlugin } from '@univerjs-pro/docs-code'import { UniverDocsCodeUIPlugin } from '@univerjs-pro/docs-code-ui'import DocsCodeUIEnUS from '@univerjs-pro/docs-code-ui/locale/en-US'import { LocaleType, mergeLocales, Univer } from '@univerjs/core'import '@univerjs-pro/docs-code-ui/lib/index.css'const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( DocsCodeUIEnUS, ), },})univer.registerPlugin(UniverDocsCodePlugin)univer.registerPlugin(UniverDocsCodeUIPlugin)If you have a commercial license for Univer, please refer to Using License in Client for configuration.
Mobile support
First configure the mobile editor. In this page’s plugin-mode setup, replace the desktop registrations below with their mobile exports from the same packages, before opening a document. Keep the model plugins, styles, locales and Facade imports; do not register both variants.
| Package | Desktop registration | Mobile registration |
|---|---|---|
@univerjs-pro/docs-code-ui | UniverDocsCodeUIPlugin | UniverDocsCodeMobileUIPlugin |
Facade API
Make sure to import the facade before using the API:
import '@univerjs-pro/docs-code/facade'Get All Code Blocks
const doc = univerAPI.getActiveDocument()const codes = doc?.getCodes() ?? []Insert a Code Block
const doc = univerAPI.getActiveDocument()const code = doc?.insertCode({ startOffset: 12, endOffset: 35,})Exit a Code Block
const doc = univerAPI.getActiveDocument()doc?.exitCode()Cancel Empty Code Paragraph
const doc = univerAPI.getActiveDocument()doc?.cancelEmptyCodeParagraph()Monospaced code fonts
The code block toolbar has a font picker that lists only fonts registered with FontCategory.MONOSPACE. Selecting a font applies it to the whole code block, including its paragraph styles.
Register a custom monospaced font with addFonts() as shown below. Registration adds a picker entry; load the actual font separately with CSS or the browser FontFace API, as described in custom fonts. This API works with either plugin or preset initialization.
import { FontCategory } from '@univerjs/ui'import '@univerjs/ui/facade'univerAPI.addFonts([ { value: 'JetBrains Mono', label: 'JetBrains Mono', category: FontCategory.MONOSPACE },])How is this guide?