From 54da9c2c12a8265445faa7abd66badd47dc0844f Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:57:01 +0800 Subject: [PATCH] fix(editor): overwrite a whole emoji instead of leaving half a surrogate pair (#7220) 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 <72485427+audichuang@users.noreply.github.com> --- src/editor/core/cm/ideaParity.test.ts | 21 +++++++++++++++++++++ src/editor/core/cm/overwrite.ts | 4 ++++ 2 files changed, 25 insertions(+) diff --git a/src/editor/core/cm/ideaParity.test.ts b/src/editor/core/cm/ideaParity.test.ts index aa53f783ee..157de9ffb6 100644 --- a/src/editor/core/cm/ideaParity.test.ts +++ b/src/editor/core/cm/ideaParity.test.ts @@ -457,6 +457,27 @@ describe("overwrite mode", () => { type("XYZ"); expect(show(v)).toBe("abXYZ|\nx"); }); + + it("overwrites a whole surrogate pair after the caret", () => { + for (const [text, typed, after] of [ + ["|😀b", "A", "A|b"], + ["|ab😀c", "XYZ", "XYZ|c"], + ["|是\u200D全角", "非", "非|\u200D全角"], + // A DOM change from 😀 to 🨀 arrives as the new high surrogate alone. + ["|😀b", "\ud83e", "\ud83e|\ude00b"], + ]) { + const v = make(text!, overwriteField); + toggleOverwrite(v); + v.state.facet(EditorView.inputHandler).some((h) => h(v, 0, 0, typed!, () => v.state.update({}))); + expect(show(v)).toBe(after); + } + // A caret between the halves of a pair (Go to Line:Column can put it there) replaces nothing on its own. + const v = make("|😀b", overwriteField); + toggleOverwrite(v); + v.dispatch({ selection: { anchor: 1 } }); + v.state.facet(EditorView.inputHandler).some((h) => h(v, 1, 1, "", () => v.state.update({}))); + expect(v.state.doc.toString()).toBe("😀b"); + }); }); describe("smooth caret", () => { diff --git a/src/editor/core/cm/overwrite.ts b/src/editor/core/cm/overwrite.ts index f4f6e25f53..e9170fa53b 100644 --- a/src/editor/core/cm/overwrite.ts +++ b/src/editor/core/cm/overwrite.ts @@ -24,6 +24,10 @@ const overwriteInput = EditorView.inputHandler.of((view, _from, _to, text) => { 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) }; });