Last active
October 1, 2024 18:21
-
-
Save andy0130tw/62d692ab52159f533584c78429d1bc5a to your computer and use it in GitHub Desktop.
Sample single line setup CodeMirror; note that you need to tweak the default keymap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { minimalSetup } from 'codemirror' | |
import { EditorState } from '@codemirror/state' | |
import { EditorView, keymap } from '@codemirror/view' | |
import { insertNewlineAndIndent, insertBlankLine } from '@codemirror/commands' | |
function removeNewlineCommands(exts) { | |
const newlineCommands = [insertNewlineAndIndent, insertBlankLine] | |
return exts.map(ext => { | |
if (ext?.facet == keymap) { | |
const newMap = ext.value.map(cmd => | |
newlineCommands.includes(cmd.run) ? | |
{ key: cmd.key, run: () => true } : cmd) | |
// shift-enter is not registered in the keymap, and it replaces selections | |
// with newline chars; A tx causes by it should be ignored, but I do not | |
// know how to do that when it occurs between two txs. | |
// XXX: will not be needed if this patch is released: | |
// https://github.com/codemirror/commands/commit/22d2119 | |
return keymap.of([...newMap, { key: 'Shift-Enter', run: () => true }]) | |
} | |
return ext | |
}) | |
} | |
function dispatchTransactions(trs, view) { | |
const docChanged = trs.some(tr => tr.docChanged) | |
if (!docChanged) { | |
view.update(trs) | |
return | |
} | |
const lastTr = trs[trs.length - 1] | |
const removeNLs = [] | |
for (let len = 0, iter = lastTr.newDoc.iterLines().next(); | |
!iter.done; | |
len += iter.value.length + 1, iter.next()) { | |
// skip the first line | |
if (len == 0) continue | |
removeNLs.push({from: len - 1, to: len}) | |
} | |
console.log(removeNLs) | |
view.update(removeNLs.length ? | |
[...trs, lastTr.state.update({ changes: removeNLs })] : | |
trs) | |
} | |
new EditorView({ | |
doc: 'this editor only allows a single line', | |
extensions: [ | |
removeNewlineCommands(minimalSetup), | |
EditorView.lineWrapping, | |
EditorState.allowMultipleSelections.of(true), | |
], | |
dispatchTransactions, | |
parent: document.body, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment