codemirror / dev

Development repository for the CodeMirror editor project
https://codemirror.net/
Other
5.9k stars 376 forks source link

New: add `setValue` equivalent #1108

Closed fregante closed 1 year ago

fregante commented 1 year ago

I have a browser extension that gets/sets the value of fields and editors on the web and I'm trying to add support for CodeMirror 6:

As noted in a previous issue, there's no easy way to set the value of a document like setValue in CM5:

Would it be possible to expose such method? The shortest way I found was via ReplaceTransaction, but being an extension, I don't have access to that class:

Bad ChatGPT suggestion, ignore ```js import { ReplaceTransaction } from "@codemirror/state"; const newContent = 'good soup'; const tr = new ReplaceTransaction(0, editorView.state.doc.length, newContent); editorView.update([tr]); ```

getValue equivalent

document.querySelector('.cm-content').cmView.view.state.doc.toString()

setValue equivalent

Examples, not implemented ```js // Accept raw string document.querySelector('.cm-content').cmView.view.state.doc.set(newContent); ``` ```js // Matching https://codemirror.net/docs/ref/#state.EditorStateConfig document.querySelector('.cm-content').cmView.view.state.doc = newContent; ```
fregante commented 1 year ago

This is the shortest equivalent I found:

cmView = document.querySelector('.cm-content').cmView;
 newContent = Math.random()+'';
 transaction = cmView.view.state.update({
    changes: {
        from: 0,
        to: cmView.view.state.doc.length,
        insert: newContent,
    },
});
cmView.view.update([transaction]);
marijnh commented 1 year ago

view.dispatch({changes: {from: 0, to: view.state.doc.length, insert: newDoc}}) should work.

Also, ReplaceTransaction is not something that exists in the CodeMirror interface.

fregante commented 1 year ago

Thank you! The helps a little. I feel that the new API is bit less friendly to amateurs (i.e. it requires a lot more code/research just go find the get/set/onchange equivalents)