@liveblocks/codemirror

@liveblocks/codemirror provides CodeMirror 6 plugins that sync a document with LiveText in Storage and display remote carets and selections. Read our React or Next.js get started guides to learn more.

Setup

Install Liveblocks, CodeMirror, and this package:

Terminal

Each Liveblocks package should use the same version.

Create a room with a LiveText document in Storage and an initial presence shape for selection cursors:

liveblocks.config.ts
App.tsx

Use useMutableStorage to get the LiveText once Storage has loaded, then create the editor with its content and both plugins in the initial extensions:

Editor.tsx

Add styles for remote carets and selections. This package does not ship a stylesheet.

globals.css

createLiveblocksSyncPlugin

Keeps a CodeMirror document in sync with a LiveText node in Storage. Local edits are written to Storage. Remote edits are applied to the editor. The plugin also wires undo and redo to the room’s history:

  • Mod-z — undo
  • Mod-y — redo
  • Shift-Mod-z — redo on macOS
Returns
  • extensionExtension

    A CodeMirror extension to add to your editor state.

Arguments

createLiveblocksPresencePlugin

Broadcasts the local selection to other clients and renders remote carets and selection highlights. Remote caret colors come from each user’s user.info.color. Set user info when authenticating or joining a room.

The plugin renders elements with the .lb-remote-caret and .lb-remote-selection class names. Style them in your app CSS using the --lb-remote-color CSS variable.

Add the returned extensions to your editor:

Returns
  • extensionsExtension[]

    CodeMirror extensions that track remote selections and render carets.

Arguments

LiveblocksCodemirrorSelection

The presence selection shape used by createLiveblocksPresencePlugin. Positions are encoded against the LiveText version so remote carets stay stable across concurrent edits.

Properties
  • anchornumberRequired

    Encoded selection anchor index.

  • headnumberRequired

    Encoded selection head index.

  • versionnumberRequired

    The LiveText version used when encoding anchor and head.

Typing

Type your room’s presence, Storage, and user metadata in liveblocks.config.ts. Use LiveblocksCodemirrorSelection for the presence selection field.

liveblocks.config.ts

When joining a room, set initialPresence to { selection: null } and initialStorage to your LiveText document: