дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
In overwrite mode, typing over an emoji replaced only its high surrogate and left a broken low half. A replaced range that ends inside a surrogate pair now takes the whole pair. Co-authored-by: audichuang <[email protected]>
48 рядки
1.9 KiB
TypeScript
48 рядки
1.9 KiB
TypeScript
/**
|
|
* Overwrite mode (Insert key, as in IDEA): typed characters replace the ones
|
|
* after the caret (never the line break) and the caret is drawn as a block.
|
|
*/
|
|
import { EditorSelection, Prec, StateEffect, StateField, type EditorState } from "@codemirror/state";
|
|
import { EditorView } from "@codemirror/view";
|
|
|
|
export const setOverwrite = StateEffect.define<boolean>();
|
|
|
|
export function isOverwrite(state: EditorState): boolean {
|
|
return state.field(overwriteField, false) ?? false;
|
|
}
|
|
|
|
export function toggleOverwrite(view: EditorView): boolean {
|
|
view.dispatch({ effects: setOverwrite.of(!isOverwrite(view.state)) });
|
|
return true;
|
|
}
|
|
|
|
const overwriteInput = EditorView.inputHandler.of((view, _from, _to, text) => {
|
|
const { state } = view;
|
|
if (!isOverwrite(state) || state.readOnly || /[\r\n]/.test(text)) return false;
|
|
const tr = state.changeByRange((r) => {
|
|
let to = r.to;
|
|
if (r.empty) {
|
|
const line = state.doc.lineAt(r.head);
|
|
to = Math.min(line.to, r.head + text.length);
|
|
// A range that ends between the halves of a surrogate pair takes the low half too, unless the
|
|
// typed text ends with a high surrogate that pairs with it.
|
|
const pair = state.doc.sliceString(to - 1, to + 1);
|
|
if (to > r.head && /^[\ud800-\udbff][\udc00-\udfff]$/.test(pair) && !/[\ud800-\udbff]$/.test(text)) to++;
|
|
}
|
|
return { changes: { from: r.from, to, insert: text }, range: EditorSelection.cursor(r.from + text.length) };
|
|
});
|
|
view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input.type" }));
|
|
return true;
|
|
});
|
|
|
|
export const overwriteField = StateField.define<boolean>({
|
|
create: () => false,
|
|
update: (on, tr) => tr.effects.reduce((acc, e) => (e.is(setOverwrite) ? e.value : acc), on),
|
|
provide: (f) => [
|
|
Prec.highest(overwriteInput),
|
|
EditorView.editorAttributes.compute([f], (s): Record<string, string> =>
|
|
s.field(f) ? { class: "cm-openidea-blockCaret" } : {},
|
|
),
|
|
],
|
|
});
|