Code Block

Plugins Info

A code block places formatted code inside a document. Syntax highlighting is provided by Prism.js.

Introduction

In Univer Docs, code blocks serve a few common needs:

  • A formatted code block can be inserted anywhere in the document.
  • Code is highlighted automatically according to its language.
  • An empty code paragraph allows the user to exit the block or cancel the code formatting.

Plugin mode

Installation

Shell
pnpm add @univerjs-pro/docs-code @univerjs-pro/docs-code-ui

Usage

TypeScript
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 your application uses Univer under a commercial license, configure it as described in Using License in Client.

Mobile support

Configure the mobile editor first. In the plugin-mode setup on this page, replace the desktop registrations listed below with the mobile exports from the same packages, and make the replacement before opening a document. Keep the model plugins, styles, locales, and Facade imports, and do not register both variants.

PackageDesktop registrationMobile registration
@univerjs-pro/docs-code-uiUniverDocsCodeUIPluginUniverDocsCodeMobileUIPlugin

Facade API

Import the facade before calling these methods:

TypeScript
import '@univerjs-pro/docs-code/facade'

Get all code blocks

TypeScript
const doc = univerAPI.getActiveDocument()const codes = doc?.getCodes() ?? []

Insert a code block

TypeScript
const doc = univerAPI.getActiveDocument()const code = doc?.insertCode({  startOffset: 12,  endOffset: 35,})

Exit a code block

TypeScript
const doc = univerAPI.getActiveDocument()doc?.exitCode()

Cancel empty code paragraph

TypeScript
const doc = univerAPI.getActiveDocument()doc?.cancelEmptyCodeParagraph()

Monospaced code fonts

The font picker in the code block toolbar lists only fonts registered with FontCategory.MONOSPACE. Selecting a font applies it to the entire code block, including its paragraph styles.

To register a custom monospaced font, call addFonts():

TypeScript
import { FontCategory } from '@univerjs/ui'import '@univerjs/ui/facade'univerAPI.addFonts([  { value: 'JetBrains Mono', label: 'JetBrains Mono', category: FontCategory.MONOSPACE },])

Registration only adds an entry to the picker. The font file itself must be loaded with CSS or the browser FontFace API, as described in custom fonts. This method works with both plugin and preset initialization.

How is this guide?

© 2026 DreamNum Co., Ltd.