fix wrapselection to apply cursor in center of selection on every instance of cursors correctly.

This commit is contained in:
Víctor Losada Hernández
2026-09-20 20:43:14 +02:00
parent bf06767488
commit 6243c27b08
@@ -1,4 +1,4 @@
/* eslint max-lines: ["error", { "max": 300 }] */ /* eslint max-lines: ["error", { "max": 400 }] */
import { keymap } from '@codemirror/view'; import { keymap } from '@codemirror/view';
import { undo, redo, indentMore, indentLess, deleteLine } from '@codemirror/commands'; import { undo, redo, indentMore, indentLess, deleteLine } from '@codemirror/commands';
import { EditorSelection } from '@codemirror/state'; import { EditorSelection } from '@codemirror/state';
@@ -92,25 +92,67 @@ const insertTab = (view)=>{
return true; return true;
}; };
const wrapSelection = (prefix, suffix)=>(view)=>{ const wrapSelection = (prefix, suffix) => (view) => {
const changes = []; view.dispatch(
view.state.changeByRange((range) => {
const { from, to } = range;
const doc = view.state.doc;
for (const range of view.state.selection.ranges) { if (from === to) {
const { from, to } = range; return {
const selected = view.state.doc.sliceString(from, to); changes: {
from,
to,
insert: prefix + suffix
},
range: EditorSelection.cursor(from + prefix.length)
};
}
let text; const before = doc.sliceString(
Math.max(0, from - prefix.length),
from
);
if(from === to) { text = prefix + suffix; } else if(selected.startsWith(prefix) && selected.endsWith(suffix)) { const after = doc.sliceString(
text = selected.slice(prefix.length, -suffix.length); to,
} else {text = `${prefix}${selected}${suffix}`;} to + suffix.length
);
changes.push({ from, to, insert: text }); if (before === prefix && after === suffix) {
} return {
changes: [
{
from: from - prefix.length,
to,
insert: ""
},
{
from: to,
to: to + suffix.length,
insert: ""
}
],
range: EditorSelection.range(
from - prefix.length,
to - prefix.length
)
};
}
view.dispatch({ return {
changes changes: {
}); from,
to,
insert: prefix + doc.sliceString(from, to) + suffix
},
range: EditorSelection.range(
from + prefix.length,
to + prefix.length
)
};
})
);
return true; return true;
}; };