Skip to content

fix: undo/redo produces wrong results when text contains multiple newlines#852

Open
Giggitycountless wants to merge 1 commit intomicrosoft:mainfrom
Giggitycountless:fix/undo-redo-multiline
Open

fix: undo/redo produces wrong results when text contains multiple newlines#852
Giggitycountless wants to merge 1 commit intomicrosoft:mainfrom
Giggitycountless:fix/undo-redo-multiline

Conversation

@Giggitycountless
Copy link
Copy Markdown

What changed

Fixes the undo/redo reinsert loop in TextBuffer::undo_redo() that produces incorrect results when the edited text contains multiple newlines.

Root cause

The reinsert loop used simd::lines_fwd(added, beg, 0, 1) to find newlines in the recorded text. However, lines_fwd is designed to seek to a specific line number — on the second iteration, line >= line_stop causes it to return immediately without advancing the offset. This means only the first line of a multi-line edit is reinserted during undo/redo.

Fix

Replaced lines_fwd with simd::memchr2(b'\r', b'\n', ...) which correctly finds the next newline byte regardless of iteration state. Also properly handles \r\n as a single newline unit to avoid double-inserting line endings in CRLF buffers.

Tests added

8 regression tests covering:

  • Single newline undo/redo
  • Multiple newlines undo/redo
  • Only newlines (no text)
  • Newline at buffer start
  • CRLF line endings
  • Empty buffer
  • Multiple undo/redo cycles
  • Newlines with text before and after

Fixes #834

…lines

The undo_redo reinsert loop used `lines_fwd(added, beg, 0, 1)` to find
newlines, but lines_fwd is designed to seek to a specific line number.
On the second iteration, line >= line_stop causes lines_fwd to return
immediately without advancing, resulting in only the first line being
reinserted (or an infinite loop in debug builds).

Replaced with `memchr2(b'\r', b'\n', ...)` which correctly iterates
through all newlines regardless of position. Also properly handles
\r\n as a single newline unit to avoid double-inserting line endings
in CRLF buffers.

Fixes microsoft#834
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 in undo/redo with additional new lines

1 participant