From d92d52b508c11092ca51a1174be14aabcc2fe5f2 Mon Sep 17 00:00:00 2001 From: Michael Sloan Date: Tue, 17 Jun 2025 01:26:58 -0600 Subject: [PATCH] Attempt to log error instead of crash in bracket highlighting (#32837) Crashes look like: ``` Panic `offset 632 is greater than the snapshot.len() 631` on thread 0 (com.apple.main-thread) ::innermost_enclosing_bracket_ranges:: editor::highlight_matching_bracket::refresh_matching_bracket_highlights ::update_window_id::>::subscribe_in::on_buffer_event>::{closure#0}::{closure#0}>::{closure#0} >::subscribe_in::::on_buffer_event>::{closure#0} ::flush_effects ::format_buffer_locally::{closure#0} ::format::{closure#1}::{closure#0}:: ``` Though `format_buffer_locally` is not always present. Both issue reports mention usage of the agent. I suspect this is somehow a result of agent format-on-save combined with the user's cursor being at the end of the buffer as it's getting edited by the agent. The offsets are always off-by-one in the error, so at first I thought the issue was the condition `head < snapshot.buffer_snapshot.len()` before setting `tail` to be `head + 1`, but an offset equal to len is valid. Seems like to get a `to_offset` crash, `head` must be greater than `len`. Which is quite weird, a selection's offset should never be out of bounds. Since this code is just about highlighting brackets, this PR logs an error instead of crashing in the `head > len` case. Closes #32732, #32171 Release Notes: - N/A --- crates/editor/src/highlight_matching_bracket.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/editor/src/highlight_matching_bracket.rs b/crates/editor/src/highlight_matching_bracket.rs index 778f5783e2..e38197283d 100644 --- a/crates/editor/src/highlight_matching_bracket.rs +++ b/crates/editor/src/highlight_matching_bracket.rs @@ -19,6 +19,11 @@ pub fn refresh_matching_bracket_highlights( let snapshot = editor.snapshot(window, cx); let head = newest_selection.head(); + if head > snapshot.buffer_snapshot.len() { + log::error!("bug: cursor offset is out of range while refreshing bracket highlights"); + return; + } + let mut tail = head; if (editor.cursor_shape == CursorShape::Block || editor.cursor_shape == CursorShape::Hollow) && head < snapshot.buffer_snapshot.len()