I am trying to implement a Markdown editor with Codemirror. Currently, I’m creating a toggleBold
command that would essentially add **
around selected text, or remove it if it’s already there. I have the following so far.
However, I noticed that when I use my toggleBold
command, but then use Mod+z
to undo, it doesn’t undo the bolding.
I expected this to be built into the Transaction system, but apparently it’s not?
Can someone please help me out to fix this issue? A quick working demo would be great.
Thank you in advance!
function toggleBold(editor) {
const { state, dispatch } = editor;
const { selection } = state;
const { from, to } = selection.main;
const text = state.doc.sliceString(from, to);
const before = state.doc.sliceString(Math.max(0, from - 2), from);
const after = state.doc.sliceString(to, Math.min(state.doc.length, to + 2));
if (before === "**" && after === "**") {
// Remove surrounding **
const transaction = state.update({
changes: [
{ from: from - 2, to: from, insert: "" },
{ from: to, to: to + 2, insert: "" }
],
selection: { anchor: from - 2, head: to - 2 },
scrollIntoView: true,
});
dispatch(transaction);
editor.focus();
return;
}
const isBold = text.startsWith("**") && text.endsWith("**");
if (isBold) {
// Remove bold
const newText = text.slice(2, -2);
const transaction = state.update({
changes: { from, to, insert: newText },
selection: { anchor: from, head: from + newText.length },
scrollIntoView: true,
});
dispatch(transaction);
} else {
// Add bold
const newText = `**${text}**`;
const transaction = state.update({
changes: { from, to, insert: newText },
selection: { anchor: from + 2, head: from + 2 + text.length },
scrollIntoView: true,
});
dispatch(transaction);
}
editor.focus();
}