Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
editor: Reuse display-map cursors when converting word diffs (#58658)
Lukas Wirth489c880a5868
diff --git a/crates/editor/src/display_map.rs b/crates/editor/src/display_map.rsindex 522f58a25fa..4a5135a21ea 100644--- a/crates/editor/src/display_map.rs+++ b/crates/editor/src/display_map.rs@@ -133,11 +133,11 @@ use std::{use crate::{EditorStyle, RowExt, hover_links::InlayHighlight, inlays::Inlay, movement::TextLayoutDetails,};-use block_map::{BlockRow, BlockSnapshot};-use fold_map::FoldSnapshot;-use inlay_map::InlaySnapshot;-use tab_map::TabSnapshot;-use wrap_map::{WrapMap, WrapPatch};+use block_map::{BlockPointCursor, BlockRow, BlockSnapshot};+use fold_map::{FoldPointCursor, FoldSnapshot};+use inlay_map::{BufferOffsetToInlayPointCursor, InlaySnapshot};+use tab_map::{TabPointCursor, TabSnapshot};+use wrap_map::{WrapMap, WrapPatch, WrapPointCursor};#[derive(Copy, Clone, Debug, PartialEq, Eq)]pub enum FoldStatus {@@ -1676,29 +1676,23 @@ impl DisplaySnapshot {&self,range: Range<MultiBufferOffset>,) -> SmallVec<[Range<DisplayPoint>; 1]> {- let inlay_snapshot = self.inlay_snapshot();- inlay_snapshot- .buffer_offset_to_inlay_ranges(range)- .map(|inlay_range| {- let inlay_point_to_display_point = |inlay_point: InlayPoint, bias: Bias| {- let fold_point = self.fold_snapshot().to_fold_point(inlay_point, bias);- let tab_point = self.tab_snapshot().fold_point_to_tab_point(fold_point);- let wrap_point = self.wrap_snapshot().tab_point_to_wrap_point(tab_point);- let block_point = self.block_snapshot.to_block_point(wrap_point);- DisplayPoint(block_point)- };-- let start = inlay_point_to_display_point(- inlay_snapshot.to_point(inlay_range.start),- Bias::Left,- );- let end = inlay_point_to_display_point(- inlay_snapshot.to_point(inlay_range.end),- Bias::Left,- );- start..end- })- .collect()+ self.display_point_converter().map(range)+ }++ /// Returns a converter that maps buffer offset ranges to `DisplayPoint`+ /// ranges (as in [`Self::isomorphic_display_point_ranges_for_buffer_range`])+ /// while reusing cursor state across calls. Use this when converting many+ /// ranges in a single pass; the inputs must be supplied with non-decreasing+ /// offsets so the underlying cursors only advance forward.+ pub fn display_point_converter(&self) -> DisplayPointConverter<'_> {+ DisplayPointConverter {+ inlay_cursor: self.inlay_snapshot().buffer_offset_to_inlay_point_cursor(),+ fold_point_cursor: self.fold_snapshot().fold_point_cursor(),+ tab_point_cursor: self.tab_snapshot().tab_point_cursor(),+ wrap_point_cursor: self.wrap_snapshot().wrap_point_cursor(),+ block_point_cursor: self.block_snapshot.block_point_cursor(),+ prev_end: None,+ }}pub fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {@@ -2608,6 +2602,57 @@ impl ToDisplayPoint for Anchor {}}+/// Maps buffer offset ranges to `DisplayPoint` ranges covering only buffer text+/// (excluding inlay text), reusing cursor state across calls.+///+/// Created via [`DisplaySnapshot::display_point_converter`]. Each layer+/// (inlay -> fold -> tab -> wrap -> block) is backed by a forward-only cursor,+/// so it is most efficient when ranges are supplied with non-decreasing+/// offsets. If a range starts before the previous one ended, the cursors are+/// transparently reset so the result stays correct (at the cost of an extra+/// seek), which keeps the converter robust to overlapping inputs such as the+/// base and buffer word diffs of an inline modified hunk.+pub struct DisplayPointConverter<'a> {+ inlay_cursor: BufferOffsetToInlayPointCursor<'a>,+ fold_point_cursor: FoldPointCursor<'a>,+ tab_point_cursor: TabPointCursor<'a>,+ wrap_point_cursor: WrapPointCursor<'a>,+ block_point_cursor: BlockPointCursor<'a>,+ prev_end: Option<MultiBufferOffset>,+}++impl DisplayPointConverter<'_> {+ pub fn map(&mut self, range: Range<MultiBufferOffset>) -> SmallVec<[Range<DisplayPoint>; 1]> {+ if self.prev_end.is_some_and(|prev_end| range.start < prev_end) {+ // The input went backward relative to where the cursors are+ // positioned; reset them so they can seek freely.+ self.inlay_cursor.reset();+ self.fold_point_cursor.reset();+ self.tab_point_cursor.reset();+ self.wrap_point_cursor.reset();+ self.block_point_cursor.reset();+ }+ self.prev_end = Some(range.end);++ let inlay_ranges = self.inlay_cursor.map(range);+ inlay_ranges+ .into_iter()+ .map(|inlay_range| {+ let start = self.inlay_point_to_display_point(inlay_range.start);+ let end = self.inlay_point_to_display_point(inlay_range.end);+ start..end+ })+ .collect()+ }++ fn inlay_point_to_display_point(&mut self, inlay_point: InlayPoint) -> DisplayPoint {+ let fold_point = self.fold_point_cursor.map(inlay_point, Bias::Left);+ let tab_point = self.tab_point_cursor.map(fold_point);+ let wrap_point = self.wrap_point_cursor.map(tab_point);+ DisplayPoint(self.block_point_cursor.map(wrap_point))+ }+}+#[cfg(test)]pub mod tests {use super::*;diff --git a/crates/editor/src/display_map/block_map.rs b/crates/editor/src/display_map/block_map.rsindex 5093d56d34b..064e49ee3e0 100644--- a/crates/editor/src/display_map/block_map.rs+++ b/crates/editor/src/display_map/block_map.rs@@ -119,6 +119,43 @@ impl BlockPoint {}}+/// Forward-only cursor mapping [`WrapPoint`]s to [`BlockPoint`]s, reusing its+/// tree position across calls. This is the streaming equivalent of+/// [`BlockSnapshot::to_block_point`]; callers must provide non-decreasing wrap+/// points.+pub struct BlockPointCursor<'a> {+ snapshot: &'a BlockSnapshot,+ cursor: sum_tree::Cursor<'a, 'static, Transform, Dimensions<WrapRow, BlockRow>>,+}++impl BlockPointCursor<'_> {+ /// Resets the cursor to the start so it can seek backward again.+ pub fn reset(&mut self) {+ self.cursor.reset();+ }++ pub fn map(&mut self, wrap_point: WrapPoint) -> BlockPoint {+ let cursor = &mut self.cursor;+ if cursor.did_seek() {+ cursor.seek_forward(&wrap_point.row(), Bias::Right);+ } else {+ cursor.seek(&wrap_point.row(), Bias::Right);+ }+ if let Some(transform) = cursor.item() {+ if transform.block.is_some() {+ BlockPoint::new(cursor.start().1, 0)+ } else {+ let input_start = Point::new(cursor.start().0.0, 0);+ let output_start = Point::new(cursor.start().1.0, 0);+ let input_overshoot = wrap_point.0 - input_start;+ BlockPoint(output_start + input_overshoot)+ }+ } else {+ self.snapshot.max_point()+ }+ }+}+pub type RenderBlock = Arc<dyn Send + Sync + Fn(&mut BlockContext) -> AnyElement>;/// Where to place a block.@@ -2513,6 +2550,13 @@ impl BlockSnapshot {}}+ pub fn block_point_cursor(&self) -> BlockPointCursor<'_> {+ BlockPointCursor {+ snapshot: self,+ cursor: self.transforms.cursor::<Dimensions<WrapRow, BlockRow>>(()),+ }+ }+#[ztracing::instrument(skip_all)]pub fn to_block_point(&self, wrap_point: WrapPoint) -> BlockPoint {let (start, _, item) = self.transforms.find::<Dimensions<WrapRow, BlockRow>, _>(diff --git a/crates/editor/src/display_map/fold_map.rs b/crates/editor/src/display_map/fold_map.rsindex fa677f03c19..8bd67ac8da9 100644--- a/crates/editor/src/display_map/fold_map.rs+++ b/crates/editor/src/display_map/fold_map.rs@@ -1023,6 +1023,11 @@ pub struct FoldPointCursor<'transforms> {}impl FoldPointCursor<'_> {+ /// Resets the cursor to the start so it can seek backward again.+ pub fn reset(&mut self) {+ self.cursor.reset();+ }+#[ztracing::instrument(skip_all)]pub fn map(&mut self, point: InlayPoint, bias: Bias) -> FoldPoint {let cursor = &mut self.cursor;diff --git a/crates/editor/src/display_map/inlay_map.rs b/crates/editor/src/display_map/inlay_map.rsindex b1672a94bd7..a0eba30fa00 100644--- a/crates/editor/src/display_map/inlay_map.rs+++ b/crates/editor/src/display_map/inlay_map.rs@@ -16,6 +16,7 @@ use multi_buffer::{RowInfo, ToOffset,};use project::InlayId;+use smallvec::SmallVec;use std::{cmp, iter,ops::{Add, AddAssign, Range, Sub, SubAssign},@@ -1022,6 +1023,15 @@ impl InlaySnapshot {})}+ pub fn buffer_offset_to_inlay_point_cursor(&self) -> BufferOffsetToInlayPointCursor<'_> {+ BufferOffsetToInlayPointCursor {+ snapshot: self,+ cursor: self+ .transforms+ .cursor::<Dimensions<MultiBufferOffset, InlayPoint>>(()),+ }+ }+#[ztracing::instrument(skip_all)]pub fn inlay_point_cursor(&self) -> InlayPointCursor<'_> {let cursor = self.transforms.cursor::<Dimensions<Point, InlayPoint>>(());@@ -1351,6 +1361,75 @@ impl InlayPointCursor<'_> {}}+/// Forward-only cursor that maps buffer-offset ranges to the inlay-point ranges+/// covering only actual buffer text (excluding inlay text), reusing its tree+/// position across calls.+///+/// This is the streaming equivalent of+/// [`InlaySnapshot::buffer_offset_to_inlay_ranges`] composed with+/// [`InlaySnapshot::to_point`]. Because the cursor only seeks forward, callers+/// must provide ranges with non-decreasing offsets.+pub struct BufferOffsetToInlayPointCursor<'a> {+ snapshot: &'a InlaySnapshot,+ cursor: Cursor<'a, 'static, Transform, Dimensions<MultiBufferOffset, InlayPoint>>,+}++impl BufferOffsetToInlayPointCursor<'_> {+ /// Resets the cursor to the start so it can seek backward again.+ pub fn reset(&mut self) {+ self.cursor.reset();+ }++ pub fn map(&mut self, range: Range<MultiBufferOffset>) -> SmallVec<[Range<InlayPoint>; 1]> {+ let buffer = &self.snapshot.buffer;+ let cursor = &mut self.cursor;+ if cursor.did_seek() {+ cursor.seek_forward(&range.start, Bias::Right);+ } else {+ cursor.seek(&range.start, Bias::Right);+ }++ let mut result = SmallVec::new();+ loop {+ match cursor.item() {+ Some(Transform::Isomorphic(_)) => {+ let seg_buffer_start = cursor.start().0;+ let seg_buffer_end = cursor.end().0;+ let seg_inlay_point_start = cursor.start().1;++ let overlap_start = cmp::max(range.start, seg_buffer_start);+ let overlap_end = cmp::min(range.end, seg_buffer_end);++ if overlap_start < overlap_end {+ let seg_point_start = buffer.offset_to_point(seg_buffer_start);+ let start = InlayPoint(+ seg_inlay_point_start.0+ + (buffer.offset_to_point(overlap_start) - seg_point_start),+ );+ let end = InlayPoint(+ seg_inlay_point_start.0+ + (buffer.offset_to_point(overlap_end) - seg_point_start),+ );+ result.push(start..end);+ }++ // Leave the cursor on the transform containing `range.end`+ // rather than advancing past it, so a subsequent call with a+ // larger (but possibly same-transform) start does not seek+ // backward.+ if seg_buffer_end >= range.end {+ break;+ }+ cursor.next();+ }+ Some(Transform::Inlay(_)) => cursor.next(),+ None => break,+ }+ }+ result+ }+}+fn push_isomorphic(sum_tree: &mut SumTree<Transform>, summary: MBTextSummary) {if summary.len == MultiBufferOffset(0) {return;diff --git a/crates/editor/src/display_map/tab_map.rs b/crates/editor/src/display_map/tab_map.rsindex 2cc9296f034..1ebd168e231 100644--- a/crates/editor/src/display_map/tab_map.rs+++ b/crates/editor/src/display_map/tab_map.rs@@ -506,6 +506,10 @@ pub struct TabPointCursor<'this> {}impl TabPointCursor<'_> {+ /// No-op; this cursor is stateless. Provided for symmetry with the other+ /// display-map layer cursors.+ pub fn reset(&mut self) {}+#[ztracing::instrument(skip_all)]pub fn map(&mut self, point: FoldPoint) -> TabPoint {self.this.fold_point_to_tab_point(point)diff --git a/crates/editor/src/display_map/wrap_map.rs b/crates/editor/src/display_map/wrap_map.rsindex 9d2e016781b..8e01e3ffaeb 100644--- a/crates/editor/src/display_map/wrap_map.rs+++ b/crates/editor/src/display_map/wrap_map.rs@@ -1034,6 +1034,11 @@ pub struct WrapPointCursor<'transforms> {}impl WrapPointCursor<'_> {+ /// Resets the cursor to the start so it can seek backward again.+ pub fn reset(&mut self) {+ self.cursor.reset();+ }+#[ztracing::instrument(skip_all)]pub fn map(&mut self, point: TabPoint) -> WrapPoint {let cursor = &mut self.cursor;diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rsindex 459442342c8..c557603b710 100644--- a/crates/editor/src/element.rs+++ b/crates/editor/src/element.rs@@ -57,7 +57,8 @@ use language::{};use markdown::Markdown;use multi_buffer::{- Anchor, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint, MultiBufferRow, RowInfo,+ Anchor, ExpandExcerptDirection, ExpandInfo, MultiBufferOffset, MultiBufferPoint,+ MultiBufferRow, RowInfo,};use project::{@@ -4523,45 +4524,51 @@ impl EditorElement {let visible_end = DisplayPoint::new(DisplayRow(start_row.0 + row_infos.len() as u32), 0).to_offset(&snapshot.display_snapshot, Bias::Right);- let word_highlights = display_hunks- .into_iter()+ // Gather the word diffs that intersect the viewport. A hunk stores the+ // word diffs for its entire range, so without this filter a large hunk+ // that is only partially scrolled into view would cost work+ // proportional to its whole size every frame.+ let mut visible_word_diffs: Vec<&Range<MultiBufferOffset>> = display_hunks+ .iter().filter_map(|(hunk, _)| match hunk {DisplayDiffHunk::Unfolded {word_diffs, status, ..- } => Some((word_diffs, status)),+ } if status.is_modified() => Some(word_diffs),_ => None,})- .filter(|(_, status)| status.is_modified())- .flat_map(|(word_diffs, _)| word_diffs)+ .flatten().filter(|word_diff| word_diff.start < visible_end && word_diff.end > visible_start)- .flat_map(|word_diff| {- let display_ranges = snapshot- .display_snapshot- .isomorphic_display_point_ranges_for_buffer_range(- word_diff.start..word_diff.end,- );+ .collect();- display_ranges.into_iter().filter_map(|range| {- let start_row_offset = range.start.row().0.saturating_sub(start_row.0) as usize;+ // The converter walks each display-map layer with a forward-only cursor,+ // so it must receive ranges in non-decreasing order. Word diffs are+ // disjoint, so sorting by offset yields a monotonic sequence.+ visible_word_diffs.sort_unstable_by_key(|word_diff| (word_diff.start, word_diff.end));- let diff_status = row_infos- .get(start_row_offset)- .and_then(|row_info| row_info.diff_status)?;+ let mut converter = snapshot.display_snapshot.display_point_converter();+ for word_diff in visible_word_diffs {+ for range in converter.map(word_diff.start..word_diff.end) {+ let start_row_offset = range.start.row().0.saturating_sub(start_row.0) as usize;- let background_color = match diff_status.kind {- DiffHunkStatusKind::Added => colors.version_control_word_added,- DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,- DiffHunkStatusKind::Modified => {- debug_panic!("modified diff status for row info");- return None;- }- };+ let Some(diff_status) = row_infos+ .get(start_row_offset)+ .and_then(|row_info| row_info.diff_status)+ else {+ continue;+ };- Some((range, background_color))- })- });+ let background_color = match diff_status.kind {+ DiffHunkStatusKind::Added => colors.version_control_word_added,+ DiffHunkStatusKind::Deleted => colors.version_control_word_deleted,+ DiffHunkStatusKind::Modified => {+ debug_panic!("modified diff status for row info");+ continue;+ }+ };- highlighted_ranges.extend(word_highlights);+ highlighted_ranges.push((range, background_color));+ }+ }}fn layout_diff_hunk_controls(