99

Concurrent visitors over the last 30 minutes. (~)

Peak concurrent visitors -
Yesterday: 0 / Today: 0

Combining Default Key Bindings with Custom Keys in CodeMirror

LibraryCodeMirror
2 years ago
0

When you use CodeMirror, you sometimes need to run extra custom behavior when a default key like Backspace or Enter is pressed, on top of its default action such as deleting text or inserting a line break.
However, CodeMirror gives priority to its default keymaps like standardKeymap and defaultKeymap, so if you bind keys with a plain keymap.of, your custom behavior (function) cannot run.
In this case, you can use the highest method of the Prec (Precedence) module to make your custom keymap take priority over the default keymaps.

TS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { EditorView } from 'codemirror' import { keymap } from '@codemirror/view' import { Prec } from '@codemirror/state' new EditorView({ // ... extensions: [ Prec.highest( keymap.of([ { key: 'Backspace', run: () => { console.log('Backspace key!') return false // Moves on to the next handler, so the text can be deleted. } }, { key: 'Enter', run: () => { console.log('Enter key!') return true // Does not move on to the next handler, so no line break is inserted. } } ]) ) ] })

If the run function of a keymap returns true, the next handler does not run, so you can disable the default keymap.
On the other hand, if it returns false, the next handler runs, so you can combine your behavior with the default keymap.