Skip to content

fix: #4926 prevent emoji deletion from splitting surrogate pairs - #4931

Merged
Jocs merged 2 commits into
marktext:developfrom
Renakoni:fix/emoji-delete-unicode-offset
Sep 14, 2026
Merged

Jocs merged 2 commits into
marktext:developfrom
Renakoni:fix/emoji-delete-unicode-offset

Conversation

@Renakoni

@Renakoni Renakoni commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4926
Related to #4892

Summary

Emoji and other astral characters are stored as UTF-16 surrogate pairs (a high code unit followed by a low one). When a collapsed caret sits between those two units and the user presses Backspace or Delete, the editor could delete a single code unit and leave a lone surrogate in the document. ot-text-unicode cannot encode a lone surrogate, so a subsequent operation throws Invalid offset - splits unicode bytes and crashes the renderer.

#4926 is reproduced and fixed here — the error is thrown while applying the text operation (JSONState._flushOperationCache → apply → strPosToUni).

A second, related path could also split a pair: the inline-token Backspace handler (_scanBackspaceTokens) trimmed one UTF-16 code unit at a time, so deleting a leading or trailing emoji from a token left half of its surrogate pair behind.

Changes

  • Snap the caret to a code-point boundary before deletion (packages/muya/src/block/base/content.ts) — when a collapsed caret would split a surrogate pair, it is moved to the adjacent valid boundary before the delete runs (Backspace snaps past the pair, Delete snaps before it), so the whole emoji is removed as a single code point.
  • Delete inline-token characters by whole code point (packages/muya/src/block/base/format.ts) — _scanBackspaceTokens now removes a complete leading/trailing code point instead of one code unit, and reports the removed length so the cursor offset is adjusted to match.

Type of change

  • Bug fix (non-breaking, fixes an issue)
  • New feature (non-breaking, adds functionality)
  • Breaking change (causes existing functionality to change)
  • Documentation update

Test plan

New automated coverage:

  • Muya unit tests — deleting a trailing (abc🙂) and a leading (🙂abc) astral emoji removes the whole code point and leaves the cursor at the correct offset.
  • Electron E2E (real clipboard paste) — Backspace and Delete inside a pasted emoji, plus a trailing emoji, asserting the exact resulting text and that a follow-up edit still applies cleanly (which catches deferred corruption).

Notes for reviewers [optional]


By submitting this pull request, I confirm that my contribution is made under the terms of the MIT license.

niyo-oyin added a commit to niyo-oyin/marktext-ja that referenced this pull request Jul 29, 2026
- PR marktext#4946 (includes its base PR marktext#4942): removes the quadratic costs
  that froze large documents and mounts them progressively — a 2.1 MB
  document goes from an indefinite freeze to interactive in seconds.
  Applied verbatim; upstream review addressed 19 findings with 31
  regression tests, all passing here.
- PR marktext#4931 (marktext#4926): deleting at an offset inside a surrogate pair left
  a lone surrogate that crashed text-unicode ("Invalid offset - splits
  unicode bytes"). The content.ts hunk conflicted with our Phase 1
  isComposed guards and was integrated by hand; the new cursor snap
  additionally runs only when no IME composition is open, since moving
  the DOM selection mid-composition would detach the IME anchor.
- PR marktext#4913 (marktext#4899): Shift+Tab outdent with trailing sibling blocks
  corrupted the state tree (paragraphs appended directly into a list),
  crashing the next composed op. muya hunks only — the PR's legacy
  muyajs hunks target the removed engine.
- PR marktext#4911 skipped: the equivalent detached-block guard already exists
  in @muyajs/core's language selector (marktext#4654), verified in source.
- PR marktext#4930 (marktext#4921): CodeMirror instance wrapped in a Vue proxy broke
  source-code mode; markRaw fix applied cleanly.

muya suite 1515/1515, tsc/eslint/madge clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ef4yFuXFbyKNTazkwUtygY
niyo-oyin added a commit to niyo-oyin/marktext-ja that referenced this pull request Jul 29, 2026
- PR marktext#4946 (includes its base PR marktext#4942): removes the quadratic costs
  that froze large documents and mounts them progressively — a 2.1 MB
  document goes from an indefinite freeze to interactive in seconds.
  Applied verbatim; upstream review addressed 19 findings with 31
  regression tests, all passing here.
- PR marktext#4931 (marktext#4926): deleting at an offset inside a surrogate pair left
  a lone surrogate that crashed text-unicode ("Invalid offset - splits
  unicode bytes"). The content.ts hunk conflicted with our Phase 1
  isComposed guards and was integrated by hand; the new cursor snap
  additionally runs only when no IME composition is open, since moving
  the DOM selection mid-composition would detach the IME anchor.
- PR marktext#4913 (marktext#4899): Shift+Tab outdent with trailing sibling blocks
  corrupted the state tree (paragraphs appended directly into a list),
  crashing the next composed op. muya hunks only — the PR's legacy
  muyajs hunks target the removed engine.
- PR marktext#4911 skipped: the equivalent detached-block guard already exists
  in @muyajs/core's language selector (marktext#4654), verified in source.
- PR marktext#4930 (marktext#4921): CodeMirror instance wrapped in a Vue proxy broke
  source-code mode; markRaw fix applied cleanly.

muya suite 1515/1515, tsc/eslint/madge clean.
Comment thread packages/muya/src/block/base/content.ts Resolved
@Jocs

Jocs commented Sep 10, 2026

Copy link
Copy Markdown
Member

@Renakoni Are you still working on fixing this issue? If not, I'll take care of it and publish a new RC version.

…nts (marktext#4926)

An emoji the user sees as one character can be several code points and
several UTF-16 code units (U+1F468 U+200D U+1F469 U+200D U+1F467 is five and
eight respectively). Handling deletion one code unit — or one code point — at
a time left part of the character behind, and half of a surrogate pair is a
lone surrogate `ot-text-unicode` cannot encode, which is the crash marktext#4926
reports.

- content: a collapsed caret parked *inside* a grapheme cluster now has that
  whole cluster removed on Backspace and Delete, on UAX marktext#29 boundaries via
  `Intl.Segmenter`. Previously the caret was nudged by one code unit and the
  browser was left to delete an arbitrary piece of the character.
- format: the inline-token backspace trim removes a whole leading / trailing
  cluster instead of one code point.
- utils: add `graphemeClusterContaining`, `firstGraphemeLength` and
  `lastGraphemeLength`.
- utils: `diffToTextOp` measured unchanged runs in grapheme clusters, but
  `ot-text-unicode` counts positions in code points. Any edit preceded by a
  multi-code-point character produced an operation aimed at the wrong offsets
  and silently desynced the JSON state from the document.
@Renakoni
Renakoni force-pushed the fix/emoji-delete-unicode-offset branch from af93258 to 376d5e2 Compare September 11, 2026 18:29
The search-replace E2E tests could read the old Markdown before the queued requestAnimationFrame applied the replacement to JSON state. Poll for the exact replacement result in both the single and all cases.
@Renakoni

Copy link
Copy Markdown
Contributor Author

I've pushed an updated fix that handles grapheme clusters, along with a fix for the CI test failure. Thanks foryour patience!

@Jocs
Jocs merged commit 911dd45 into marktext:develop Sep 14, 2026
15 checks passed
@Jocs

Jocs commented Sep 14, 2026

Copy link
Copy Markdown
Member

Thanks @Renakoni — merged! The grapheme-aware token trim in format.ts and the codePointLength fix in diffToTextOp fix the crash that #4926 and the related reports hit.

I opened #5332 as a follow-up with two changes:

  1. Code blocks had the same crash. CodeBlockContent doesn't extend Format; it has its own Prism-token Backspace trim that still removed one UTF-16 code unit, so // ship 🚀 + Backspace at the end of a code line still left a lone surrogate. It now uses your firstGraphemeLength / lastGraphemeLength helpers.
  2. _deleteGraphemeClusterContainingCaret is removed. I measured it in real Chromium and WebKit. The crash path is the caret after an emoji at a token end (on a boundary), which the format.ts trim covers. Ordinary interactions — clicks, arrow/word navigation, drags, deletes, undo, paste, Enter, over 4.7k checks — never left the caret inside a cluster, and disabling the handler changed nothing in any [Bug] emoji导致的渲染进程错误 #4926 scenario. Meanwhile it segmented the block text on every Backspace/Delete next to non-ASCII text (~15 ms at 100k characters). The details are in fix(muya): delete emoji whole in code blocks and drop the caret-inside-cluster handler (#4926) #5332.

Jocs added a commit that referenced this pull request Sep 14, 2026
…e-cluster handler (#4926) (#5332)

* fix(muya): delete whole characters on Backspace at a code token end (#4926)

The Firefox-compat Backspace path in code blocks trimmed one UTF-16 code
unit from the highlighted token under the caret. A comment ending in an
astral emoji (`// ship 🚀`) lost only the low surrogate; the lone high
surrogate then crashed the next op with "Invalid offset - splits unicode
bytes". Trim a whole grapheme cluster and move the caret by its length,
mirroring the paragraph fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KGKDSxyPk9WxU2h5DgPcWn

* refactor(muya): drop the caret-inside-cluster delete handler

#4931 added `_deleteGraphemeClusterContainingCaret` to delete a whole
grapheme cluster when a collapsed caret sits strictly inside one. That state
does not occur in practice: in real Chrome, 4736 caret checks after clicks,
arrow and word navigation, vertical moves, double clicks, drags,
Backspace/Delete walks, undo, paste, Enter and typed combining marks never
left the DOM selection or Muya's cursor inside a cluster, and the handler
never fired. With it disabled, every #4926 crash scenario behaves the same
in Chromium and WebKit, and even a caret forced inside an emoji deletes the
whole character natively without error.

The #4926 crash comes from Muya's own token-boundary Backspace, which the
Format and code block trims now handle by grapheme. The handler only added a
grapheme segmentation of the block text on every Backspace/Delete next to a
non-ASCII character (about 15 ms at 100k characters), so remove it together
with `graphemeClusterContaining` and the tests that forced the caret inside
a cluster. The token-trim tests now go through `keydownHandler` and cover
every cluster shape.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KGKDSxyPk9WxU2h5DgPcWn

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@Jocs Jocs mentioned this pull request Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] emoji导致的渲染进程错误

2 participants