Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New: add setValue equivalent #1108

Closed
fregante opened this issue Mar 11, 2023 · 3 comments
Closed

New: add setValue equivalent #1108

fregante opened this issue Mar 11, 2023 · 3 comments

Comments

@fregante
Copy link

fregante commented Mar 11, 2023

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
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
// Accept raw string
document.querySelector('.cm-content').cmView.view.state.doc.set(newContent);
// Matching https://codemirror.net/docs/ref/#state.EditorStateConfig
document.querySelector('.cm-content').cmView.view.state.doc = newContent;
@fregante
Copy link
Author

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
Copy link
Member

marijnh commented Mar 11, 2023

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.

@marijnh marijnh closed this as completed Mar 11, 2023
fregante added a commit to fregante/GhostText that referenced this issue Mar 11, 2023
@fregante
Copy link
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants