1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use gpui::{App, AppContext, Context, Entity};
4use itertools::Itertools;
5use language::{Buffer, BufferSnapshot};
6use rope::Point;
7use sum_tree::{Dimensions, SumTree};
8use text::{Bias, BufferId, Edit, OffsetRangeExt, Patch};
9use util::rel_path::RelPath;
10use ztracing::instrument;
11
12use crate::{
13 Anchor, BufferState, BufferStateSnapshot, DiffChangeKind, Event, Excerpt, ExcerptOffset,
14 ExcerptRange, ExcerptSummary, ExpandExcerptDirection, MultiBuffer, MultiBufferDimension,
15 PathKeyIndex, ToOffset, build_excerpt_ranges,
16};
17
18#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]
19pub struct PathKey {
20 // Used by the derived PartialOrd & Ord
21 pub sort_prefix: Option<u64>,
22 pub path: Arc<RelPath>,
23}
24
25impl PathKey {
26 pub fn min() -> Self {
27 Self {
28 sort_prefix: None,
29 path: RelPath::empty().into_arc(),
30 }
31 }
32
33 pub fn sorted(sort_prefix: u64) -> Self {
34 Self {
35 sort_prefix: Some(sort_prefix),
36 path: RelPath::empty().into_arc(),
37 }
38 }
39 pub fn with_sort_prefix(sort_prefix: u64, path: Arc<RelPath>) -> Self {
40 Self {
41 sort_prefix: Some(sort_prefix),
42 path,
43 }
44 }
45
46 pub fn for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Self {
47 if let Some(file) = buffer.read(cx).file() {
48 Self::with_sort_prefix(file.worktree_id(cx).to_proto(), file.path().clone())
49 } else {
50 Self {
51 sort_prefix: None,
52 path: RelPath::unix(&buffer.entity_id().to_string())
53 .unwrap()
54 .into_arc(),
55 }
56 }
57 }
58}
59
60impl MultiBuffer {
61 pub fn buffer_for_path(&self, path: &PathKey, cx: &App) -> Option<Entity<Buffer>> {
62 let snapshot = self.snapshot(cx);
63 let excerpt = snapshot.excerpts_for_path(path).next()?;
64 self.buffer(excerpt.buffer_id)
65 }
66
67 pub fn location_for_path(&self, path: &PathKey, cx: &App) -> Option<Anchor> {
68 let snapshot = self.snapshot(cx);
69 let excerpt = snapshot.excerpts_for_path(path).next()?;
70 Some(Anchor::in_buffer(
71 excerpt.path_key_index,
72 excerpt.range.start,
73 ))
74 }
75
76 pub fn set_excerpts_for_buffer(
77 &mut self,
78 buffer: Entity<Buffer>,
79 ranges: impl IntoIterator<Item = Range<Point>>,
80 context_line_count: u32,
81 cx: &mut Context<Self>,
82 ) -> (Vec<Range<Anchor>>, bool) {
83 let path = PathKey::for_buffer(&buffer, cx);
84 self.set_excerpts_for_path(path, buffer, ranges, context_line_count, cx)
85 }
86
87 /// Sets excerpts, returns `true` if at least one new excerpt was added.
88 #[instrument(skip_all)]
89 pub fn set_excerpts_for_path(
90 &mut self,
91 path: PathKey,
92 buffer: Entity<Buffer>,
93 ranges: impl IntoIterator<Item = Range<Point>>,
94 context_line_count: u32,
95 cx: &mut Context<Self>,
96 ) -> (Vec<Range<Anchor>>, bool) {
97 let buffer_snapshot = buffer.read(cx).snapshot();
98 let ranges: Vec<_> = ranges.into_iter().collect();
99 let excerpt_ranges =
100 build_excerpt_ranges(ranges.clone(), context_line_count, &buffer_snapshot);
101
102 let merged = Self::merge_excerpt_ranges(&excerpt_ranges);
103 let (inserted, path_key_index) =
104 self.set_merged_excerpt_ranges_for_path(path, buffer, &buffer_snapshot, merged, cx);
105 // todo!() move this into the callers that care
106 let anchors = ranges
107 .into_iter()
108 .map(|range| {
109 Anchor::range_in_buffer(path_key_index, buffer_snapshot.anchor_range_around(range))
110 })
111 .collect::<Vec<_>>();
112 (anchors, inserted)
113 }
114
115 pub fn set_excerpt_ranges_for_path(
116 &mut self,
117 path: PathKey,
118 buffer: Entity<Buffer>,
119 buffer_snapshot: &BufferSnapshot,
120 excerpt_ranges: Vec<ExcerptRange<Point>>,
121 cx: &mut Context<Self>,
122 ) -> (Vec<Range<Anchor>>, PathKeyIndex, bool) {
123 let merged = Self::merge_excerpt_ranges(&excerpt_ranges);
124 let (inserted, path_key_index) =
125 self.set_merged_excerpt_ranges_for_path(path, buffer, buffer_snapshot, merged, cx);
126 // todo!() move this into the callers that care
127 let anchors = excerpt_ranges
128 .into_iter()
129 .map(|range| {
130 Anchor::range_in_buffer(
131 path_key_index,
132 buffer_snapshot.anchor_range_around(range.primary),
133 )
134 })
135 .collect::<Vec<_>>();
136 (anchors, path_key_index, inserted)
137 }
138
139 pub fn set_anchored_excerpts_for_path(
140 &self,
141 path_key: PathKey,
142 buffer: Entity<Buffer>,
143 ranges: Vec<Range<text::Anchor>>,
144 context_line_count: u32,
145 cx: &Context<Self>,
146 ) -> impl Future<Output = Vec<Range<Anchor>>> + use<> {
147 let buffer_snapshot = buffer.read(cx).snapshot();
148 let multi_buffer = cx.weak_entity();
149 let mut app = cx.to_async();
150 async move {
151 let snapshot = buffer_snapshot.clone();
152 let (ranges, merged_excerpt_ranges) = app
153 .background_spawn(async move {
154 let point_ranges = ranges.iter().map(|range| range.to_point(&snapshot));
155 let excerpt_ranges =
156 build_excerpt_ranges(point_ranges, context_line_count, &snapshot);
157 let merged = Self::merge_excerpt_ranges(&excerpt_ranges);
158 (ranges, merged)
159 })
160 .await;
161
162 multi_buffer
163 .update(&mut app, move |multi_buffer, cx| {
164 let (_, path_key_index) = multi_buffer.set_merged_excerpt_ranges_for_path(
165 path_key,
166 buffer,
167 &buffer_snapshot,
168 merged_excerpt_ranges,
169 cx,
170 );
171 ranges
172 .into_iter()
173 .map(|range| Anchor::range_in_buffer(path_key_index, range))
174 .collect()
175 })
176 .ok()
177 .unwrap_or_default()
178 }
179 }
180
181 pub fn expand_excerpts(
182 &mut self,
183 anchors: impl IntoIterator<Item = Anchor>,
184 line_count: u32,
185 direction: ExpandExcerptDirection,
186 cx: &mut Context<Self>,
187 ) {
188 let snapshot = self.snapshot(cx);
189 let mut sorted_anchors = anchors
190 .into_iter()
191 .filter_map(|anchor| anchor.excerpt_anchor())
192 .collect::<Vec<_>>();
193 sorted_anchors.sort_by(|a, b| a.cmp(b, &snapshot));
194 let buffers = sorted_anchors.into_iter().chunk_by(|anchor| anchor.path);
195 let mut cursor = snapshot.excerpts.cursor::<ExcerptSummary>(());
196
197 for (path_index, excerpt_anchors) in &buffers {
198 let path = snapshot
199 .path_keys_by_index
200 .get(&path_index)
201 .expect("anchor from wrong multibuffer");
202
203 let mut excerpt_anchors = excerpt_anchors.peekable();
204 let mut ranges = Vec::new();
205
206 cursor.seek_forward(path, Bias::Left);
207 let Some((buffer, buffer_snapshot)) = cursor
208 .item()
209 .map(|excerpt| (excerpt.buffer(&self), excerpt.buffer_snapshot(&snapshot)))
210 else {
211 continue;
212 };
213
214 while let Some(excerpt) = cursor.item()
215 && &excerpt.path_key == path
216 {
217 let mut range = ExcerptRange {
218 context: excerpt.range.context.to_point(buffer_snapshot),
219 primary: excerpt.range.primary.to_point(buffer_snapshot),
220 };
221
222 let mut needs_expand = false;
223 while excerpt_anchors.peek().is_some_and(|anchor| {
224 excerpt
225 .range
226 .contains(&anchor.text_anchor(), buffer_snapshot)
227 }) {
228 needs_expand = true;
229 excerpt_anchors.next();
230 }
231
232 if needs_expand {
233 match direction {
234 ExpandExcerptDirection::Up => {
235 range.context.start.row =
236 range.context.start.row.saturating_sub(line_count);
237 range.context.start.column = 0;
238 }
239 ExpandExcerptDirection::Down => {
240 range.context.end.row = (range.context.end.row + line_count)
241 .min(excerpt.buffer_snapshot(&snapshot).max_point().row);
242 range.context.end.column = excerpt
243 .buffer_snapshot(&snapshot)
244 .line_len(range.context.end.row);
245 }
246 ExpandExcerptDirection::UpAndDown => {
247 range.context.start.row =
248 range.context.start.row.saturating_sub(line_count);
249 range.context.start.column = 0;
250 range.context.end.row = (range.context.end.row + line_count)
251 .min(excerpt.buffer_snapshot(&snapshot).max_point().row);
252 range.context.end.column = excerpt
253 .buffer_snapshot(&snapshot)
254 .line_len(range.context.end.row);
255 }
256 }
257 }
258
259 ranges.push(range);
260 cursor.next();
261 }
262
263 self.set_excerpt_ranges_for_path(path.clone(), buffer, buffer_snapshot, ranges, cx);
264 }
265 }
266
267 /// Sets excerpts, returns `true` if at least one new excerpt was added.
268 pub(crate) fn set_merged_excerpt_ranges_for_path<T>(
269 &mut self,
270 path: PathKey,
271 buffer: Entity<Buffer>,
272 buffer_snapshot: &BufferSnapshot,
273 new: Vec<ExcerptRange<T>>,
274 cx: &mut Context<Self>,
275 ) -> (bool, PathKeyIndex)
276 where
277 T: language::ToOffset,
278 {
279 let anchor_ranges = new
280 .into_iter()
281 .map(|r| ExcerptRange {
282 context: buffer_snapshot.anchor_before(r.context.start)
283 ..buffer_snapshot.anchor_after(r.context.end),
284 primary: buffer_snapshot.anchor_before(r.primary.start)
285 ..buffer_snapshot.anchor_after(r.primary.end),
286 })
287 .collect::<Vec<_>>();
288 self.update_path_excerpts(path, buffer, buffer_snapshot, &anchor_ranges, cx)
289 }
290
291 fn get_or_create_path_key_index(&mut self, path_key: &PathKey) -> PathKeyIndex {
292 let mut snapshot = self.snapshot.borrow_mut();
293 let existing = snapshot
294 .path_keys_by_index
295 .iter()
296 // todo!() perf? (but ExcerptIdMapping was doing this)
297 .find(|(_, existing_path)| existing_path == &path_key)
298 .map(|(index, _)| *index);
299
300 if let Some(existing) = existing {
301 return existing;
302 }
303
304 let index = snapshot
305 .path_keys_by_index
306 .last()
307 .map(|(index, _)| PathKeyIndex(index.0 + 1))
308 .unwrap_or(PathKeyIndex(0));
309 snapshot.path_keys_by_index.insert(index, path_key.clone());
310 index
311 }
312
313 // todo!() re-instate nonshrinking version for project diff / diagnostics
314 pub fn update_path_excerpts<'a>(
315 &mut self,
316 path_key: PathKey,
317 buffer: Entity<Buffer>,
318 buffer_snapshot: &BufferSnapshot,
319 to_insert: &Vec<ExcerptRange<text::Anchor>>,
320 cx: &mut Context<Self>,
321 ) -> (bool, PathKeyIndex) {
322 let path_key_index = self.get_or_create_path_key_index(&path_key);
323 if let Some(old_path_key) = self
324 .snapshot(cx)
325 .path_for_buffer(buffer_snapshot.remote_id())
326 && old_path_key != &path_key
327 {
328 self.remove_excerpts(old_path_key.clone(), cx);
329 }
330
331 if to_insert.len() == 0 {
332 self.remove_excerpts(path_key.clone(), cx);
333
334 return (false, path_key_index);
335 }
336 assert_eq!(self.history.transaction_depth(), 0);
337 self.sync_mut(cx);
338
339 let buffer_id = buffer_snapshot.remote_id();
340
341 let mut snapshot = self.snapshot.get_mut();
342 let mut cursor = snapshot
343 .excerpts
344 .cursor::<Dimensions<PathKey, ExcerptOffset>>(());
345 let mut new_excerpts = SumTree::new(());
346
347 let new_ranges = to_insert.clone();
348 let mut to_insert = to_insert.iter().peekable();
349 let mut patch = Patch::empty();
350 let mut added_new_excerpt = false;
351
352 new_excerpts.append(cursor.slice(&path_key, Bias::Left), ());
353
354 // handle the case where the path key used to be associated
355 // with a different buffer by removing its excerpts.
356 if let Some(excerpt) = cursor.item()
357 && excerpt.path_key == path_key
358 && excerpt.buffer_id != buffer_id
359 {
360 let before = cursor.position.1;
361 cursor.seek_forward(&path_key, Bias::Right);
362 let after = cursor.position.1;
363 patch.push(Edit {
364 old: before..after,
365 new: new_excerpts.summary().len()..new_excerpts.summary().len(),
366 });
367 }
368
369 while let Some(excerpt) = cursor.item()
370 && excerpt.path_key == path_key
371 {
372 assert_eq!(excerpt.buffer_id, buffer_id);
373 let Some(next_excerpt) = to_insert.peek() else {
374 break;
375 };
376 if &excerpt.range == *next_excerpt {
377 new_excerpts.push(excerpt.clone(), ());
378 to_insert.next();
379 cursor.next();
380 continue;
381 }
382
383 if excerpt
384 .range
385 .context
386 .start
387 .cmp(&next_excerpt.context.start, &buffer_snapshot)
388 .is_le()
389 {
390 // remove old excerpt
391 let before = cursor.position.1;
392 cursor.next();
393 let after = cursor.position.1;
394 patch.push(Edit {
395 old: before..after,
396 new: new_excerpts.summary().len()..new_excerpts.summary().len(),
397 });
398 } else {
399 // insert new excerpt
400 let next_excerpt = to_insert.next().unwrap();
401 added_new_excerpt = true;
402 let before = new_excerpts.summary().len();
403 new_excerpts.update_last(|excerpt| excerpt.has_trailing_newline = true, ());
404 new_excerpts.push(
405 Excerpt::new(
406 path_key.clone(),
407 path_key_index,
408 &buffer_snapshot,
409 next_excerpt.clone(),
410 to_insert.peek().is_some()
411 || cursor
412 .item()
413 .is_some_and(|item| item.path_key_index != path_key_index),
414 ),
415 (),
416 );
417 let after = new_excerpts.summary().len();
418 patch.push_maybe_empty(Edit {
419 old: cursor.position.1..cursor.position.1,
420 new: before..after,
421 });
422 }
423 }
424
425 // remove any further trailing excerpts
426 let before = cursor.position.1;
427 cursor.seek_forward(&path_key, Bias::Right);
428 let after = cursor.position.1;
429 patch.push(Edit {
430 old: before..after,
431 new: new_excerpts.summary().len()..new_excerpts.summary().len(),
432 });
433
434 while let Some(next_excerpt) = to_insert.next() {
435 added_new_excerpt = true;
436 let before = new_excerpts.summary().len();
437 new_excerpts.update_last(|excerpt| excerpt.has_trailing_newline = true, ());
438 new_excerpts.push(
439 Excerpt::new(
440 path_key.clone(),
441 path_key_index,
442 &buffer_snapshot,
443 next_excerpt.clone(),
444 to_insert.peek().is_some()
445 || cursor
446 .item()
447 .is_some_and(|item| item.path_key_index != path_key_index),
448 ),
449 (),
450 );
451 let after = new_excerpts.summary().len();
452 patch.push_maybe_empty(Edit {
453 old: cursor.position.1..cursor.position.1,
454 new: before..after,
455 });
456 }
457
458 let suffix = cursor.suffix();
459 let changed_trailing_excerpt = suffix.is_empty();
460 new_excerpts.append(suffix, ());
461 drop(cursor);
462 snapshot.excerpts = new_excerpts;
463 snapshot.buffers.insert(
464 buffer_id,
465 BufferStateSnapshot {
466 path_key: path_key.clone(),
467 buffer_snapshot: buffer_snapshot.clone(),
468 },
469 );
470
471 self.buffers.entry(buffer_id).or_insert_with(|| {
472 self.buffer_changed_since_sync.replace(true);
473 buffer.update(cx, |buffer, _| {
474 buffer.record_changes(Rc::downgrade(&self.buffer_changed_since_sync));
475 });
476 BufferState {
477 _subscriptions: [
478 cx.observe(&buffer, |_, _, cx| cx.notify()),
479 cx.subscribe(&buffer, Self::on_buffer_event),
480 ],
481 buffer: buffer.clone(),
482 }
483 });
484
485 if changed_trailing_excerpt {
486 snapshot.trailing_excerpt_update_count += 1;
487 }
488
489 let edits = Self::sync_diff_transforms(
490 &mut snapshot,
491 patch.into_inner(),
492 DiffChangeKind::BufferEdited,
493 );
494 if !edits.is_empty() {
495 self.subscriptions.publish(edits);
496 }
497
498 cx.emit(Event::Edited {
499 edited_buffer: None,
500 });
501 cx.emit(Event::BufferUpdated {
502 buffer,
503 path_key: path_key.clone(),
504 ranges: new_ranges,
505 });
506 cx.notify();
507
508 (added_new_excerpt, path_key_index)
509 }
510
511 pub fn remove_excerpts_for_buffer(&mut self, buffer: BufferId, cx: &mut Context<Self>) {
512 let snapshot = self.sync_mut(cx);
513 let Some(path) = snapshot.path_for_buffer(buffer).cloned() else {
514 return;
515 };
516 self.remove_excerpts(path, cx);
517 }
518
519 pub fn remove_excerpts(&mut self, path: PathKey, cx: &mut Context<Self>) {
520 assert_eq!(self.history.transaction_depth(), 0);
521 self.sync_mut(cx);
522
523 let mut snapshot = self.snapshot.get_mut();
524 let mut cursor = snapshot
525 .excerpts
526 .cursor::<Dimensions<PathKey, ExcerptOffset>>(());
527 let mut new_excerpts = SumTree::new(());
528 new_excerpts.append(cursor.slice(&path, Bias::Left), ());
529 let edit_start = cursor.position.1;
530 let mut buffer_id = None;
531 if let Some(excerpt) = cursor.item()
532 && excerpt.path_key == path
533 {
534 buffer_id = Some(excerpt.buffer_id);
535 }
536 cursor.seek(&path, Bias::Right);
537 let edit_end = cursor.position.1;
538 let suffix = cursor.suffix();
539 let changed_trailing_excerpt = suffix.is_empty();
540 new_excerpts.append(suffix, ());
541
542 let edit = Edit {
543 old: edit_start..edit_end,
544 new: edit_start..edit_start,
545 };
546
547 if let Some(buffer_id) = buffer_id {
548 snapshot.buffers.remove(&buffer_id);
549 self.buffers.remove(&buffer_id);
550 cx.emit(Event::BuffersRemoved {
551 removed_buffer_ids: vec![buffer_id],
552 })
553 }
554 drop(cursor);
555 if changed_trailing_excerpt {
556 snapshot.trailing_excerpt_update_count += 1;
557 new_excerpts.update_last(|excerpt| excerpt.has_trailing_newline = false, ())
558 }
559 snapshot.excerpts = new_excerpts;
560
561 let edits =
562 Self::sync_diff_transforms(&mut snapshot, vec![edit], DiffChangeKind::BufferEdited);
563 if !edits.is_empty() {
564 self.subscriptions.publish(edits);
565 }
566
567 cx.emit(Event::Edited {
568 edited_buffer: None,
569 });
570 cx.notify();
571 }
572}