Hi, in my ProseMirror editor I have a button which toggle the view to HTML
view and the codemirror
(5.54.0) is used to do that. I call as follows:
cmInstance.setValue(editor.getHTML()); // init content
// state.setValue(editor.view.dom.innerHTML); // init content
// Format code
cmInstance.execCommand('selectAll');
const selectedRange = {
from: cmInstance.getCursor(true),
to: cmInstance.getCursor(false),
};
cmInstance.autoFormatRange(selectedRange.from, selectedRange.to);
cmInstance.setCursor(0);
The problem is that once I try to go back to WYSIWYG view by calling
const content = cmInstance.getValue();
editor.commands.setContent(content, true);
there are extra whitespaces introduced. Here is the example:
Is there a unique way to solve this problem or I shouldn’t simply autoFormat
the code but then for huge documents it will look very ugly
Doe sanyone have an idea what could I change?
marijn
October 25, 2023, 3:11pm
3
Autoformat isn’t part of CodeMirror (it was a long time ago, but no longer), so I don’t expect you’ll find support for it here.
OK so let me elaborate a little bit more. The problem is that if I have for example this piece of content:
Then, when switching to CodeView mode, I have the following:
which is a single, completely unreadable line. I’m wondering how to produce some more readable output in such a way that when I go back to WYSIWYG mode, the content is properly parsed without any extra whitespaces introduced by possible formatting. Is there an easy solution for that or I would need to implement some kind of custom formatter?
Here is the way I create the CodeView in React
useEffect(() => {
if (!editor) return;
if (isCodeViewMode && !cmInstance) {
const codeView = editor.extensionManager.extensions.find(
(e) => e.name === 'code_view'
);
if (codeView) {
const { codemirror, codemirrorOptions } = codeView.options;
if (codemirror) {
// merge options
const cmOptions = {
...codemirrorOptions,
readOnly: !editor.isEditable,
theme: document.documentElement.classList.contains('dark')
? 'base16-dark'
: 'default',
};
let newCmInstance = codemirror.fromTextArea(
cmTextAreaRef.current,
cmOptions
);
setCmInstance(newCmInstance);
}
}
}
if (isCodeViewMode && cmInstance) {
cmInstance.setValue(editor.getHTML()); // init content
} else {
if (!cmInstance) return;
const content = cmInstance.getValue();
editor.commands.setContent(content, true);
// Destroy code mirror
const element = cmInstance.doc.cm.getWrapperElement();
element && element.remove && element.remove();
setCmInstance(null);
}
}, [isCodeViewMode, cmInstance]);