Example: Read-Only Editor

CodeMirror splits the concept of editability into two parts.

Depending on your use case, you might want to combine these in different ways. An editor that should be completely non-interactive would set readOnly to true and editable to false. Though note that, if you only want syntax highlighting and no editing features, it is often preferable to not use EditorView at all, and directly use @lezer/highlight to highlight the code.

If you want an editor that responds to keyboard commands, you will need to make sure your editor is focusable, because DOM elements do not receive keyboard input unless they are focused. Turning editable off will make the content element a regular DOM <div> element which the user cannot focus. Depending on whether you want the browser to behave as if the content is editable or not, you could either leave editable on, or add a tabindex attribute via contentAttributes to make an uneditable element focusable.

import {EditorView, basicSetup} from "codemirror"
import {EditorState} from "@codemirror/state"

new EditorView({
  parent: document.querySelector("#editor_focus"),
  doc: "I am focusable but not editable",
  extensions: [
    basicSetup,
    EditorState.readOnly.of(true),
    EditorView.editable.of(false),
    EditorView.contentAttributes.of({tabindex: "0"})
  ]
})

The native cursor will not be visible in a non-editable element, but if you enable the library's own cursor drawing (which is enabled by default in basicSetup), you can still get a visible cursor.