1use std::{
2 cmp, fmt, iter, mem,
3 ops::{AddAssign, Deref, DerefMut, Range, Sub},
4 sync::Arc,
5};
6
7use collections::HashMap;
8use gpui::Pixels;
9use itertools::Itertools as _;
10use language::{Bias, Point, Selection, SelectionGoal};
11use multi_buffer::{MultiBufferDimension, MultiBufferOffset};
12use util::post_inc;
13
14use crate::{
15 Anchor, DisplayPoint, DisplayRow, ExcerptId, MultiBufferSnapshot, SelectMode, ToOffset,
16 display_map::{DisplaySnapshot, ToDisplayPoint},
17 movement::TextLayoutDetails,
18};
19
20#[derive(Debug, Clone)]
21pub struct PendingSelection {
22 selection: Selection<Anchor>,
23 mode: SelectMode,
24}
25
26#[derive(Debug, Clone)]
27pub struct SelectionsCollection {
28 next_selection_id: usize,
29 line_mode: bool,
30 /// The non-pending, non-overlapping selections.
31 /// The [SelectionsCollection::pending] selection could possibly overlap these
32 disjoint: Arc<[Selection<Anchor>]>,
33 /// A pending selection, such as when the mouse is being dragged
34 pending: Option<PendingSelection>,
35 select_mode: SelectMode,
36 is_extending: bool,
37}
38
39impl SelectionsCollection {
40 pub fn new() -> Self {
41 Self {
42 next_selection_id: 1,
43 line_mode: false,
44 disjoint: Arc::default(),
45 pending: Some(PendingSelection {
46 selection: Selection {
47 id: 0,
48 start: Anchor::min(),
49 end: Anchor::min(),
50 reversed: false,
51 goal: SelectionGoal::None,
52 },
53 mode: SelectMode::Character,
54 }),
55 select_mode: SelectMode::Character,
56 is_extending: false,
57 }
58 }
59
60 pub fn clone_state(&mut self, other: &SelectionsCollection) {
61 self.next_selection_id = other.next_selection_id;
62 self.line_mode = other.line_mode;
63 self.disjoint = other.disjoint.clone();
64 self.pending.clone_from(&other.pending);
65 }
66
67 pub fn count(&self) -> usize {
68 let mut count = self.disjoint.len();
69 if self.pending.is_some() {
70 count += 1;
71 }
72 count
73 }
74
75 /// The non-pending, non-overlapping selections. There could be a pending selection that
76 /// overlaps these if the mouse is being dragged, etc. This could also be empty if there is a
77 /// pending selection. Returned as selections over Anchors.
78 pub fn disjoint_anchors_arc(&self) -> Arc<[Selection<Anchor>]> {
79 self.disjoint.clone()
80 }
81
82 /// The non-pending, non-overlapping selections. There could be a pending selection that
83 /// overlaps these if the mouse is being dragged, etc. This could also be empty if there is a
84 /// pending selection. Returned as selections over Anchors.
85 pub fn disjoint_anchors(&self) -> &[Selection<Anchor>] {
86 &self.disjoint
87 }
88
89 pub fn disjoint_anchor_ranges(&self) -> impl Iterator<Item = Range<Anchor>> {
90 // Mapping the Arc slice would borrow it, whereas indexing captures it.
91 let disjoint = self.disjoint_anchors_arc();
92 (0..disjoint.len()).map(move |ix| disjoint[ix].range())
93 }
94
95 /// Non-overlapping selections using anchors, including the pending selection.
96 pub fn all_anchors(&self, snapshot: &DisplaySnapshot) -> Arc<[Selection<Anchor>]> {
97 if self.pending.is_none() {
98 self.disjoint_anchors_arc()
99 } else {
100 let all_offset_selections = self.all::<MultiBufferOffset>(snapshot);
101 all_offset_selections
102 .into_iter()
103 .map(|selection| selection_to_anchor_selection(selection, snapshot))
104 .collect()
105 }
106 }
107
108 pub fn pending_anchor(&self) -> Option<&Selection<Anchor>> {
109 self.pending.as_ref().map(|pending| &pending.selection)
110 }
111
112 pub fn pending<D>(&self, snapshot: &DisplaySnapshot) -> Option<Selection<D>>
113 where
114 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
115 {
116 resolve_selections_wrapping_blocks(self.pending_anchor(), &snapshot).next()
117 }
118
119 pub(crate) fn pending_mode(&self) -> Option<SelectMode> {
120 self.pending.as_ref().map(|pending| pending.mode.clone())
121 }
122
123 pub fn all<D>(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<D>>
124 where
125 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
126 {
127 let disjoint_anchors = &self.disjoint;
128 let mut disjoint =
129 resolve_selections_wrapping_blocks::<D, _>(disjoint_anchors.iter(), &snapshot)
130 .peekable();
131 let mut pending_opt = self.pending::<D>(&snapshot);
132 iter::from_fn(move || {
133 if let Some(pending) = pending_opt.as_mut() {
134 while let Some(next_selection) = disjoint.peek() {
135 if should_merge(
136 pending.start,
137 pending.end,
138 next_selection.start,
139 next_selection.end,
140 false,
141 ) {
142 let next_selection = disjoint.next().unwrap();
143 if next_selection.start < pending.start {
144 pending.start = next_selection.start;
145 }
146 if next_selection.end > pending.end {
147 pending.end = next_selection.end;
148 }
149 } else if next_selection.end < pending.start {
150 return disjoint.next();
151 } else {
152 break;
153 }
154 }
155
156 pending_opt.take()
157 } else {
158 disjoint.next()
159 }
160 })
161 .collect()
162 }
163
164 /// Returns all of the selections, adjusted to take into account the selection line_mode
165 pub fn all_adjusted(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<Point>> {
166 let mut selections = self.all::<Point>(&snapshot);
167 if self.line_mode {
168 for selection in &mut selections {
169 let new_range = snapshot.expand_to_line(selection.range());
170 selection.start = new_range.start;
171 selection.end = new_range.end;
172 }
173 }
174 selections
175 }
176
177 /// Returns the newest selection, adjusted to take into account the selection line_mode
178 pub fn newest_adjusted(&self, snapshot: &DisplaySnapshot) -> Selection<Point> {
179 let mut selection = self.newest::<Point>(&snapshot);
180 if self.line_mode {
181 let new_range = snapshot.expand_to_line(selection.range());
182 selection.start = new_range.start;
183 selection.end = new_range.end;
184 }
185 selection
186 }
187
188 pub fn all_adjusted_display(
189 &self,
190 display_map: &DisplaySnapshot,
191 ) -> Vec<Selection<DisplayPoint>> {
192 if self.line_mode {
193 let selections = self.all::<Point>(&display_map);
194 let result = selections
195 .into_iter()
196 .map(|mut selection| {
197 let new_range = display_map.expand_to_line(selection.range());
198 selection.start = new_range.start;
199 selection.end = new_range.end;
200 selection.map(|point| point.to_display_point(&display_map))
201 })
202 .collect();
203 result
204 } else {
205 self.all_display(display_map)
206 }
207 }
208
209 pub fn disjoint_in_range<D>(
210 &self,
211 range: Range<Anchor>,
212 snapshot: &DisplaySnapshot,
213 ) -> Vec<Selection<D>>
214 where
215 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord + std::fmt::Debug,
216 {
217 let start_ix = match self
218 .disjoint
219 .binary_search_by(|probe| probe.end.cmp(&range.start, snapshot.buffer_snapshot()))
220 {
221 Ok(ix) | Err(ix) => ix,
222 };
223 let end_ix = match self
224 .disjoint
225 .binary_search_by(|probe| probe.start.cmp(&range.end, snapshot.buffer_snapshot()))
226 {
227 Ok(ix) => ix + 1,
228 Err(ix) => ix,
229 };
230 resolve_selections_wrapping_blocks(&self.disjoint[start_ix..end_ix], snapshot).collect()
231 }
232
233 pub fn all_display(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<DisplayPoint>> {
234 let disjoint_anchors = &self.disjoint;
235 let mut disjoint =
236 resolve_selections_display(disjoint_anchors.iter(), &snapshot).peekable();
237 let mut pending_opt = resolve_selections_display(self.pending_anchor(), &snapshot).next();
238 iter::from_fn(move || {
239 if let Some(pending) = pending_opt.as_mut() {
240 while let Some(next_selection) = disjoint.peek() {
241 if should_merge(
242 pending.start,
243 pending.end,
244 next_selection.start,
245 next_selection.end,
246 false,
247 ) {
248 let next_selection = disjoint.next().unwrap();
249 if next_selection.start < pending.start {
250 pending.start = next_selection.start;
251 }
252 if next_selection.end > pending.end {
253 pending.end = next_selection.end;
254 }
255 } else if next_selection.end < pending.start {
256 return disjoint.next();
257 } else {
258 break;
259 }
260 }
261
262 pending_opt.take()
263 } else {
264 disjoint.next()
265 }
266 })
267 .collect()
268 }
269
270 pub fn newest_anchor(&self) -> &Selection<Anchor> {
271 self.pending
272 .as_ref()
273 .map(|s| &s.selection)
274 .or_else(|| self.disjoint.iter().max_by_key(|s| s.id))
275 .unwrap()
276 }
277
278 pub fn newest<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
279 where
280 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
281 {
282 resolve_selections_wrapping_blocks([self.newest_anchor()], &snapshot)
283 .next()
284 .unwrap()
285 }
286
287 pub fn newest_display(&self, snapshot: &DisplaySnapshot) -> Selection<DisplayPoint> {
288 resolve_selections_display([self.newest_anchor()], &snapshot)
289 .next()
290 .unwrap()
291 }
292
293 pub fn oldest_anchor(&self) -> &Selection<Anchor> {
294 self.disjoint
295 .iter()
296 .min_by_key(|s| s.id)
297 .or_else(|| self.pending.as_ref().map(|p| &p.selection))
298 .unwrap()
299 }
300
301 pub fn oldest<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
302 where
303 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
304 {
305 resolve_selections_wrapping_blocks([self.oldest_anchor()], &snapshot)
306 .next()
307 .unwrap()
308 }
309
310 pub fn first_anchor(&self) -> Selection<Anchor> {
311 self.pending
312 .as_ref()
313 .map(|pending| pending.selection.clone())
314 .unwrap_or_else(|| self.disjoint.first().cloned().unwrap())
315 }
316
317 pub fn first<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
318 where
319 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
320 {
321 self.all(snapshot).first().unwrap().clone()
322 }
323
324 pub fn last<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
325 where
326 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
327 {
328 self.all(snapshot).last().unwrap().clone()
329 }
330
331 /// Returns a list of (potentially backwards!) ranges representing the selections.
332 /// Useful for test assertions, but prefer `.all()` instead.
333 #[cfg(any(test, feature = "test-support"))]
334 pub fn ranges<D>(&self, snapshot: &DisplaySnapshot) -> Vec<Range<D>>
335 where
336 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
337 {
338 self.all::<D>(snapshot)
339 .iter()
340 .map(|s| {
341 if s.reversed {
342 s.end..s.start
343 } else {
344 s.start..s.end
345 }
346 })
347 .collect()
348 }
349
350 #[cfg(any(test, feature = "test-support"))]
351 pub fn display_ranges(&self, display_snapshot: &DisplaySnapshot) -> Vec<Range<DisplayPoint>> {
352 self.disjoint_anchors_arc()
353 .iter()
354 .chain(self.pending_anchor())
355 .map(|s| {
356 if s.reversed {
357 s.end.to_display_point(display_snapshot)
358 ..s.start.to_display_point(display_snapshot)
359 } else {
360 s.start.to_display_point(display_snapshot)
361 ..s.end.to_display_point(display_snapshot)
362 }
363 })
364 .collect()
365 }
366
367 /// Attempts to build a selection in the provided `DisplayRow` within the
368 /// same range as the provided range of `Pixels`.
369 /// Returns `None` if the range is not empty but it starts past the line's
370 /// length, meaning that the line isn't long enough to be contained within
371 /// part of the provided range.
372 pub fn build_columnar_selection(
373 &mut self,
374 display_map: &DisplaySnapshot,
375 row: DisplayRow,
376 positions: &Range<Pixels>,
377 reversed: bool,
378 text_layout_details: &TextLayoutDetails,
379 ) -> Option<Selection<Point>> {
380 let is_empty = positions.start == positions.end;
381 let line_len = display_map.line_len(row);
382 let line = display_map.layout_row(row, text_layout_details);
383 let start_col = line.closest_index_for_x(positions.start) as u32;
384
385 let (start, end) = if is_empty {
386 let point = DisplayPoint::new(row, std::cmp::min(start_col, line_len));
387 (point, point)
388 } else {
389 if start_col >= line_len {
390 return None;
391 }
392 let start = DisplayPoint::new(row, start_col);
393 let end_col = line.closest_index_for_x(positions.end) as u32;
394 let end = DisplayPoint::new(row, end_col);
395 (start, end)
396 };
397
398 Some(Selection {
399 id: post_inc(&mut self.next_selection_id),
400 start: start.to_point(display_map),
401 end: end.to_point(display_map),
402 reversed,
403 goal: SelectionGoal::HorizontalRange {
404 start: positions.start.into(),
405 end: positions.end.into(),
406 },
407 })
408 }
409
410 /// Attempts to build a selection in the provided buffer row using the
411 /// same buffer column range as specified.
412 /// Returns `None` if the range is not empty but it starts past the line's
413 /// length, meaning that the line isn't long enough to be contained within
414 /// part of the provided range.
415 pub fn build_columnar_selection_from_buffer_columns(
416 &mut self,
417 display_map: &DisplaySnapshot,
418 buffer_row: u32,
419 positions: &Range<u32>,
420 reversed: bool,
421 text_layout_details: &TextLayoutDetails,
422 ) -> Option<Selection<Point>> {
423 let is_empty = positions.start == positions.end;
424 let line_len = display_map
425 .buffer_snapshot()
426 .line_len(multi_buffer::MultiBufferRow(buffer_row));
427
428 let (start, end) = if is_empty {
429 let column = std::cmp::min(positions.start, line_len);
430 let point = Point::new(buffer_row, column);
431 (point, point)
432 } else {
433 if positions.start >= line_len {
434 return None;
435 }
436
437 let start = Point::new(buffer_row, positions.start);
438 let end_column = std::cmp::min(positions.end, line_len);
439 let end = Point::new(buffer_row, end_column);
440 (start, end)
441 };
442
443 let start_display_point = start.to_display_point(display_map);
444 let end_display_point = end.to_display_point(display_map);
445 let start_x = display_map.x_for_display_point(start_display_point, text_layout_details);
446 let end_x = display_map.x_for_display_point(end_display_point, text_layout_details);
447
448 Some(Selection {
449 id: post_inc(&mut self.next_selection_id),
450 start,
451 end,
452 reversed,
453 goal: SelectionGoal::HorizontalRange {
454 start: start_x.min(end_x).into(),
455 end: start_x.max(end_x).into(),
456 },
457 })
458 }
459
460 /// Finds the next columnar selection by walking display rows one at a time
461 /// so that soft-wrapped lines are considered and not skipped.
462 pub fn find_next_columnar_selection_by_display_row(
463 &mut self,
464 display_map: &DisplaySnapshot,
465 start_row: DisplayRow,
466 end_row: DisplayRow,
467 above: bool,
468 positions: &Range<Pixels>,
469 reversed: bool,
470 text_layout_details: &TextLayoutDetails,
471 ) -> Option<Selection<Point>> {
472 let mut row = start_row;
473 while row != end_row {
474 if above {
475 row.0 -= 1;
476 } else {
477 row.0 += 1;
478 }
479
480 if let Some(selection) = self.build_columnar_selection(
481 display_map,
482 row,
483 positions,
484 reversed,
485 text_layout_details,
486 ) {
487 return Some(selection);
488 }
489 }
490 None
491 }
492
493 /// Finds the next columnar selection by skipping to the next buffer row,
494 /// ignoring soft-wrapped lines.
495 pub fn find_next_columnar_selection_by_buffer_row(
496 &mut self,
497 display_map: &DisplaySnapshot,
498 start_row: DisplayRow,
499 end_row: DisplayRow,
500 above: bool,
501 goal_columns: &Range<u32>,
502 reversed: bool,
503 text_layout_details: &TextLayoutDetails,
504 ) -> Option<Selection<Point>> {
505 let mut row = start_row;
506 let direction = if above { -1 } else { 1 };
507 while row != end_row {
508 let new_row =
509 display_map.start_of_relative_buffer_row(DisplayPoint::new(row, 0), direction);
510 row = new_row.row();
511 let buffer_row = new_row.to_point(display_map).row;
512
513 if let Some(selection) = self.build_columnar_selection_from_buffer_columns(
514 display_map,
515 buffer_row,
516 goal_columns,
517 reversed,
518 text_layout_details,
519 ) {
520 return Some(selection);
521 }
522 }
523 None
524 }
525
526 pub fn change_with<R>(
527 &mut self,
528 snapshot: &DisplaySnapshot,
529 change: impl FnOnce(&mut MutableSelectionsCollection<'_, '_>) -> R,
530 ) -> (bool, R) {
531 let mut mutable_collection = MutableSelectionsCollection {
532 snapshot,
533 collection: self,
534 selections_changed: false,
535 };
536
537 let result = change(&mut mutable_collection);
538 assert!(
539 !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
540 "There must be at least one selection"
541 );
542 if cfg!(debug_assertions) {
543 mutable_collection.disjoint.iter().for_each(|selection| {
544 assert!(
545 selection.start.cmp(&selection.end, &snapshot).is_le(),
546 "disjoint selection has start > end: {:?}",
547 mutable_collection.disjoint
548 );
549 assert!(
550 snapshot.can_resolve(&selection.start),
551 "disjoint selection start is not resolvable for the given snapshot:\n{selection:?}, {excerpt:?}",
552 excerpt = snapshot.buffer_for_excerpt(selection.start.excerpt_id).map(|snapshot| snapshot.remote_id()),
553 );
554 assert!(
555 snapshot.can_resolve(&selection.end),
556 "disjoint selection end is not resolvable for the given snapshot: {selection:?}, {excerpt:?}",
557 excerpt = snapshot.buffer_for_excerpt(selection.end.excerpt_id).map(|snapshot| snapshot.remote_id()),
558 );
559 });
560 assert!(
561 mutable_collection
562 .disjoint
563 .is_sorted_by(|first, second| first.end.cmp(&second.start, &snapshot).is_le()),
564 "disjoint selections are not sorted: {:?}",
565 mutable_collection.disjoint
566 );
567 if let Some(pending) = &mutable_collection.pending {
568 let selection = &pending.selection;
569 assert!(
570 selection.start.cmp(&selection.end, &snapshot).is_le(),
571 "pending selection has start > end: {:?}",
572 selection
573 );
574 assert!(
575 snapshot.can_resolve(&selection.start),
576 "pending selection start is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
577 excerpt = snapshot
578 .buffer_for_excerpt(selection.start.excerpt_id)
579 .map(|snapshot| snapshot.remote_id()),
580 );
581 assert!(
582 snapshot.can_resolve(&selection.end),
583 "pending selection end is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
584 excerpt = snapshot
585 .buffer_for_excerpt(selection.end.excerpt_id)
586 .map(|snapshot| snapshot.remote_id()),
587 );
588 }
589 }
590 (mutable_collection.selections_changed, result)
591 }
592
593 pub fn next_selection_id(&self) -> usize {
594 self.next_selection_id
595 }
596
597 pub fn line_mode(&self) -> bool {
598 self.line_mode
599 }
600
601 pub fn set_line_mode(&mut self, line_mode: bool) {
602 self.line_mode = line_mode;
603 }
604
605 pub fn select_mode(&self) -> &SelectMode {
606 &self.select_mode
607 }
608
609 pub fn set_select_mode(&mut self, select_mode: SelectMode) {
610 self.select_mode = select_mode;
611 }
612
613 pub fn is_extending(&self) -> bool {
614 self.is_extending
615 }
616
617 pub fn set_is_extending(&mut self, is_extending: bool) {
618 self.is_extending = is_extending;
619 }
620}
621
622pub struct MutableSelectionsCollection<'snap, 'a> {
623 collection: &'a mut SelectionsCollection,
624 snapshot: &'snap DisplaySnapshot,
625 selections_changed: bool,
626}
627
628impl<'snap, 'a> fmt::Debug for MutableSelectionsCollection<'snap, 'a> {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.debug_struct("MutableSelectionsCollection")
631 .field("collection", &self.collection)
632 .field("selections_changed", &self.selections_changed)
633 .finish()
634 }
635}
636
637impl<'snap, 'a> MutableSelectionsCollection<'snap, 'a> {
638 pub fn display_snapshot(&self) -> DisplaySnapshot {
639 self.snapshot.clone()
640 }
641
642 pub fn clear_disjoint(&mut self) {
643 self.collection.disjoint = Arc::default();
644 }
645
646 pub fn delete(&mut self, selection_id: usize) {
647 let mut changed = false;
648 self.collection.disjoint = self
649 .disjoint
650 .iter()
651 .filter(|selection| {
652 let found = selection.id == selection_id;
653 changed |= found;
654 !found
655 })
656 .cloned()
657 .collect();
658
659 self.selections_changed |= changed;
660 }
661
662 pub fn remove_selections_from_buffer(&mut self, buffer_id: language::BufferId) {
663 let mut changed = false;
664
665 let filtered_selections: Arc<[Selection<Anchor>]> = {
666 self.disjoint
667 .iter()
668 .filter(|selection| {
669 if let Some(selection_buffer_id) =
670 self.snapshot.buffer_id_for_anchor(selection.start)
671 {
672 let should_remove = selection_buffer_id == buffer_id;
673 changed |= should_remove;
674 !should_remove
675 } else {
676 true
677 }
678 })
679 .cloned()
680 .collect()
681 };
682
683 if filtered_selections.is_empty() {
684 let buffer_snapshot = self.snapshot.buffer_snapshot();
685 let anchor = buffer_snapshot
686 .excerpts()
687 .find(|(_, buffer, _)| buffer.remote_id() == buffer_id)
688 .and_then(|(excerpt_id, _, range)| {
689 buffer_snapshot.anchor_in_excerpt(excerpt_id, range.context.start)
690 })
691 .unwrap_or_else(|| self.snapshot.anchor_before(MultiBufferOffset(0)));
692 self.collection.disjoint = Arc::from([Selection {
693 id: post_inc(&mut self.collection.next_selection_id),
694 start: anchor,
695 end: anchor,
696 reversed: false,
697 goal: SelectionGoal::None,
698 }]);
699 } else {
700 self.collection.disjoint = filtered_selections;
701 }
702
703 self.selections_changed |= changed;
704 }
705
706 pub fn clear_pending(&mut self) {
707 if self.collection.pending.is_some() {
708 self.collection.pending = None;
709 self.selections_changed = true;
710 }
711 }
712
713 pub(crate) fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
714 self.collection.pending = Some(PendingSelection {
715 selection: {
716 let mut start = range.start;
717 let mut end = range.end;
718 let reversed = if start.cmp(&end, self.snapshot).is_gt() {
719 mem::swap(&mut start, &mut end);
720 true
721 } else {
722 false
723 };
724 Selection {
725 id: post_inc(&mut self.collection.next_selection_id),
726 start,
727 end,
728 reversed,
729 goal: SelectionGoal::None,
730 }
731 },
732 mode,
733 });
734 self.selections_changed = true;
735 }
736
737 pub(crate) fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
738 self.collection.pending = Some(PendingSelection { selection, mode });
739 self.selections_changed = true;
740 }
741
742 pub fn try_cancel(&mut self) -> bool {
743 if let Some(pending) = self.collection.pending.take() {
744 if self.disjoint.is_empty() {
745 self.collection.disjoint = Arc::from([pending.selection]);
746 }
747 self.selections_changed = true;
748 return true;
749 }
750
751 let mut oldest = self.oldest_anchor().clone();
752 if self.count() > 1 {
753 self.collection.disjoint = Arc::from([oldest]);
754 self.selections_changed = true;
755 return true;
756 }
757
758 if !oldest.start.cmp(&oldest.end, self.snapshot).is_eq() {
759 let head = oldest.head();
760 oldest.start = head;
761 oldest.end = head;
762 self.collection.disjoint = Arc::from([oldest]);
763 self.selections_changed = true;
764 return true;
765 }
766
767 false
768 }
769
770 pub fn insert_range<T>(&mut self, range: Range<T>)
771 where
772 T: ToOffset,
773 {
774 let display_map = self.display_snapshot();
775 let mut selections = self.collection.all(&display_map);
776 let mut start = range.start.to_offset(self.snapshot);
777 let mut end = range.end.to_offset(self.snapshot);
778 let reversed = if start > end {
779 mem::swap(&mut start, &mut end);
780 true
781 } else {
782 false
783 };
784 selections.push(Selection {
785 id: post_inc(&mut self.collection.next_selection_id),
786 start,
787 end,
788 reversed,
789 goal: SelectionGoal::None,
790 });
791 self.select(selections);
792 }
793
794 pub fn select<T>(&mut self, selections: Vec<Selection<T>>)
795 where
796 T: ToOffset + std::marker::Copy + std::fmt::Debug,
797 {
798 let mut selections = selections
799 .into_iter()
800 .map(|selection| selection.map(|it| it.to_offset(self.snapshot)))
801 .map(|mut selection| {
802 if selection.start > selection.end {
803 mem::swap(&mut selection.start, &mut selection.end);
804 selection.reversed = true
805 }
806 selection
807 })
808 .collect::<Vec<_>>();
809 selections.sort_unstable_by_key(|s| s.start);
810
811 let mut i = 1;
812 while i < selections.len() {
813 let prev = &selections[i - 1];
814 let current = &selections[i];
815
816 if should_merge(prev.start, prev.end, current.start, current.end, true) {
817 let removed = selections.remove(i);
818 if removed.start < selections[i - 1].start {
819 selections[i - 1].start = removed.start;
820 }
821 if selections[i - 1].end < removed.end {
822 selections[i - 1].end = removed.end;
823 }
824 } else {
825 i += 1;
826 }
827 }
828
829 self.collection.disjoint = Arc::from_iter(
830 selections
831 .into_iter()
832 .map(|selection| selection_to_anchor_selection(selection, self.snapshot)),
833 );
834 self.collection.pending = None;
835 self.selections_changed = true;
836 }
837
838 pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
839 let map = self.display_snapshot();
840 let resolved_selections =
841 resolve_selections_wrapping_blocks::<MultiBufferOffset, _>(&selections, &map)
842 .collect::<Vec<_>>();
843 self.select(resolved_selections);
844 }
845
846 pub fn select_ranges<I, T>(&mut self, ranges: I)
847 where
848 I: IntoIterator<Item = Range<T>>,
849 T: ToOffset,
850 {
851 let ranges = ranges
852 .into_iter()
853 .map(|range| range.start.to_offset(self.snapshot)..range.end.to_offset(self.snapshot));
854 self.select_offset_ranges(ranges);
855 }
856
857 fn select_offset_ranges<I>(&mut self, ranges: I)
858 where
859 I: IntoIterator<Item = Range<MultiBufferOffset>>,
860 {
861 let selections = ranges
862 .into_iter()
863 .map(|range| {
864 let mut start = range.start;
865 let mut end = range.end;
866 let reversed = if start > end {
867 mem::swap(&mut start, &mut end);
868 true
869 } else {
870 false
871 };
872 Selection {
873 id: post_inc(&mut self.collection.next_selection_id),
874 start,
875 end,
876 reversed,
877 goal: SelectionGoal::None,
878 }
879 })
880 .collect::<Vec<_>>();
881
882 self.select(selections)
883 }
884
885 pub fn select_anchor_ranges<I>(&mut self, ranges: I)
886 where
887 I: IntoIterator<Item = Range<Anchor>>,
888 {
889 let selections = ranges
890 .into_iter()
891 .map(|range| {
892 let mut start = range.start;
893 let mut end = range.end;
894 let reversed = if start.cmp(&end, self.snapshot).is_gt() {
895 mem::swap(&mut start, &mut end);
896 true
897 } else {
898 false
899 };
900 Selection {
901 id: post_inc(&mut self.collection.next_selection_id),
902 start,
903 end,
904 reversed,
905 goal: SelectionGoal::None,
906 }
907 })
908 .collect::<Vec<_>>();
909 self.select_anchors(selections)
910 }
911
912 pub fn new_selection_id(&mut self) -> usize {
913 post_inc(&mut self.next_selection_id)
914 }
915
916 pub fn select_display_ranges<T>(&mut self, ranges: T)
917 where
918 T: IntoIterator<Item = Range<DisplayPoint>>,
919 {
920 let selections = ranges
921 .into_iter()
922 .map(|range| {
923 let mut start = range.start;
924 let mut end = range.end;
925 let reversed = if start > end {
926 mem::swap(&mut start, &mut end);
927 true
928 } else {
929 false
930 };
931 Selection {
932 id: post_inc(&mut self.collection.next_selection_id),
933 start: start.to_point(self.snapshot),
934 end: end.to_point(self.snapshot),
935 reversed,
936 goal: SelectionGoal::None,
937 }
938 })
939 .collect();
940 self.select(selections);
941 }
942
943 pub fn reverse_selections(&mut self) {
944 let mut new_selections: Vec<Selection<Point>> = Vec::new();
945 let disjoint = self.disjoint.clone();
946 for selection in disjoint
947 .iter()
948 .sorted_by(|first, second| Ord::cmp(&second.id, &first.id))
949 {
950 new_selections.push(Selection {
951 id: self.new_selection_id(),
952 start: selection
953 .start
954 .to_display_point(self.snapshot)
955 .to_point(self.snapshot),
956 end: selection
957 .end
958 .to_display_point(self.snapshot)
959 .to_point(self.snapshot),
960 reversed: selection.reversed,
961 goal: selection.goal,
962 });
963 }
964 self.select(new_selections);
965 }
966
967 pub fn move_with(
968 &mut self,
969 mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
970 ) {
971 let mut changed = false;
972 let display_map = self.display_snapshot();
973 let selections = self.collection.all_display(&display_map);
974 let selections = selections
975 .into_iter()
976 .map(|selection| {
977 let mut moved_selection = selection.clone();
978 move_selection(&display_map, &mut moved_selection);
979 if selection != moved_selection {
980 changed = true;
981 }
982 moved_selection.map(|display_point| display_point.to_point(&display_map))
983 })
984 .collect();
985
986 if changed {
987 self.select(selections)
988 }
989 }
990
991 pub fn move_offsets_with(
992 &mut self,
993 mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<MultiBufferOffset>),
994 ) {
995 let mut changed = false;
996 let display_map = self.display_snapshot();
997 let selections = self
998 .collection
999 .all::<MultiBufferOffset>(&display_map)
1000 .into_iter()
1001 .map(|selection| {
1002 let mut moved_selection = selection.clone();
1003 move_selection(self.snapshot, &mut moved_selection);
1004 if selection != moved_selection {
1005 changed = true;
1006 }
1007 moved_selection
1008 })
1009 .collect();
1010
1011 if changed {
1012 self.select(selections)
1013 }
1014 }
1015
1016 pub fn move_heads_with(
1017 &mut self,
1018 mut update_head: impl FnMut(
1019 &DisplaySnapshot,
1020 DisplayPoint,
1021 SelectionGoal,
1022 ) -> (DisplayPoint, SelectionGoal),
1023 ) {
1024 self.move_with(|map, selection| {
1025 let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
1026 selection.set_head(new_head, new_goal);
1027 });
1028 }
1029
1030 pub fn move_cursors_with(
1031 &mut self,
1032 mut update_cursor_position: impl FnMut(
1033 &DisplaySnapshot,
1034 DisplayPoint,
1035 SelectionGoal,
1036 ) -> (DisplayPoint, SelectionGoal),
1037 ) {
1038 self.move_with(|map, selection| {
1039 let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
1040 selection.collapse_to(cursor, new_goal)
1041 });
1042 }
1043
1044 pub fn maybe_move_cursors_with(
1045 &mut self,
1046 mut update_cursor_position: impl FnMut(
1047 &DisplaySnapshot,
1048 DisplayPoint,
1049 SelectionGoal,
1050 ) -> Option<(DisplayPoint, SelectionGoal)>,
1051 ) {
1052 self.move_cursors_with(|map, point, goal| {
1053 update_cursor_position(map, point, goal).unwrap_or((point, goal))
1054 })
1055 }
1056
1057 pub fn replace_cursors_with(
1058 &mut self,
1059 find_replacement_cursors: impl FnOnce(&DisplaySnapshot) -> Vec<DisplayPoint>,
1060 ) {
1061 let new_selections = find_replacement_cursors(self.snapshot)
1062 .into_iter()
1063 .map(|cursor| {
1064 let cursor_point = cursor.to_point(self.snapshot);
1065 Selection {
1066 id: post_inc(&mut self.collection.next_selection_id),
1067 start: cursor_point,
1068 end: cursor_point,
1069 reversed: false,
1070 goal: SelectionGoal::None,
1071 }
1072 })
1073 .collect();
1074 self.select(new_selections);
1075 }
1076
1077 pub fn pending_anchor_mut(&mut self) -> Option<&mut Selection<Anchor>> {
1078 self.selections_changed = true;
1079 self.pending.as_mut().map(|pending| &mut pending.selection)
1080 }
1081
1082 /// Compute new ranges for any selections that were located in excerpts that have
1083 /// since been removed.
1084 ///
1085 /// Returns a `HashMap` indicating which selections whose former head position
1086 /// was no longer present. The keys of the map are selection ids. The values are
1087 /// the id of the new excerpt where the head of the selection has been moved.
1088 pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
1089 let mut pending = self.collection.pending.take();
1090 let mut selections_with_lost_position = HashMap::default();
1091
1092 let anchors_with_status = {
1093 let disjoint_anchors = self
1094 .disjoint
1095 .iter()
1096 .flat_map(|selection| [&selection.start, &selection.end]);
1097 self.snapshot.refresh_anchors(disjoint_anchors)
1098 };
1099 let adjusted_disjoint: Vec<_> = anchors_with_status
1100 .chunks(2)
1101 .map(|selection_anchors| {
1102 let (anchor_ix, start, kept_start) = selection_anchors[0];
1103 let (_, end, kept_end) = selection_anchors[1];
1104 let selection = &self.disjoint[anchor_ix / 2];
1105 let kept_head = if selection.reversed {
1106 kept_start
1107 } else {
1108 kept_end
1109 };
1110 if !kept_head {
1111 selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
1112 }
1113
1114 Selection {
1115 id: selection.id,
1116 start,
1117 end,
1118 reversed: selection.reversed,
1119 goal: selection.goal,
1120 }
1121 })
1122 .collect();
1123
1124 if !adjusted_disjoint.is_empty() {
1125 let map = self.display_snapshot();
1126 let resolved_selections =
1127 resolve_selections_wrapping_blocks(adjusted_disjoint.iter(), &map).collect();
1128 self.select::<MultiBufferOffset>(resolved_selections);
1129 }
1130
1131 if let Some(pending) = pending.as_mut() {
1132 let anchors = self
1133 .snapshot
1134 .refresh_anchors([&pending.selection.start, &pending.selection.end]);
1135 let (_, start, kept_start) = anchors[0];
1136 let (_, end, kept_end) = anchors[1];
1137 let kept_head = if pending.selection.reversed {
1138 kept_start
1139 } else {
1140 kept_end
1141 };
1142 if !kept_head {
1143 selections_with_lost_position
1144 .insert(pending.selection.id, pending.selection.head().excerpt_id);
1145 }
1146
1147 pending.selection.start = start;
1148 pending.selection.end = end;
1149 }
1150 self.collection.pending = pending;
1151 self.selections_changed = true;
1152
1153 selections_with_lost_position
1154 }
1155}
1156
1157impl Deref for MutableSelectionsCollection<'_, '_> {
1158 type Target = SelectionsCollection;
1159 fn deref(&self) -> &Self::Target {
1160 self.collection
1161 }
1162}
1163
1164impl DerefMut for MutableSelectionsCollection<'_, '_> {
1165 fn deref_mut(&mut self) -> &mut Self::Target {
1166 self.collection
1167 }
1168}
1169
1170fn selection_to_anchor_selection(
1171 selection: Selection<MultiBufferOffset>,
1172 buffer: &MultiBufferSnapshot,
1173) -> Selection<Anchor> {
1174 let end_bias = if selection.start == selection.end {
1175 Bias::Right
1176 } else {
1177 Bias::Left
1178 };
1179 Selection {
1180 id: selection.id,
1181 start: buffer.anchor_after(selection.start),
1182 end: buffer.anchor_at(selection.end, end_bias),
1183 reversed: selection.reversed,
1184 goal: selection.goal,
1185 }
1186}
1187
1188fn resolve_selections_point<'a>(
1189 selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1190 map: &'a DisplaySnapshot,
1191) -> impl 'a + Iterator<Item = Selection<Point>> {
1192 let (to_summarize, selections) = selections.into_iter().tee();
1193 let mut summaries = map
1194 .buffer_snapshot()
1195 .summaries_for_anchors::<Point, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
1196 .into_iter();
1197 selections.map(move |s| {
1198 let start = summaries.next().unwrap();
1199 let end = summaries.next().unwrap();
1200 assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1201 Selection {
1202 id: s.id,
1203 start,
1204 end,
1205 reversed: s.reversed,
1206 goal: s.goal,
1207 }
1208 })
1209}
1210
1211/// Panics if passed selections are not in order
1212/// Resolves the anchors to display positions
1213fn resolve_selections_display<'a>(
1214 selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1215 map: &'a DisplaySnapshot,
1216) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
1217 let selections = resolve_selections_point(selections, map).map(move |s| {
1218 let display_start = map.point_to_display_point(s.start, Bias::Left);
1219 let display_end = map.point_to_display_point(
1220 s.end,
1221 if s.start == s.end {
1222 Bias::Right
1223 } else {
1224 Bias::Left
1225 },
1226 );
1227 assert!(
1228 display_start <= display_end,
1229 "display_start: {:?}, display_end: {:?}",
1230 display_start,
1231 display_end
1232 );
1233 Selection {
1234 id: s.id,
1235 start: display_start,
1236 end: display_end,
1237 reversed: s.reversed,
1238 goal: s.goal,
1239 }
1240 });
1241 coalesce_selections(selections)
1242}
1243
1244/// Resolves the passed in anchors to [`MultiBufferDimension`]s `D`
1245/// wrapping around blocks inbetween.
1246///
1247/// # Panics
1248///
1249/// Panics if passed selections are not in order
1250pub(crate) fn resolve_selections_wrapping_blocks<'a, D, I>(
1251 selections: I,
1252 map: &'a DisplaySnapshot,
1253) -> impl 'a + Iterator<Item = Selection<D>>
1254where
1255 D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
1256 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1257{
1258 // Transforms `Anchor -> DisplayPoint -> Point -> DisplayPoint -> D`
1259 // todo(lw): We should be able to short circuit the `Anchor -> DisplayPoint -> Point` to `Anchor -> Point`
1260 let (to_convert, selections) = resolve_selections_display(selections, map).tee();
1261 let mut converted_endpoints =
1262 map.buffer_snapshot()
1263 .dimensions_from_points::<D>(to_convert.flat_map(|s| {
1264 let start = map.display_point_to_point(s.start, Bias::Left);
1265 let end = map.display_point_to_point(s.end, Bias::Right);
1266 assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1267 [start, end]
1268 }));
1269 selections.map(move |s| {
1270 let start = converted_endpoints.next().unwrap();
1271 let end = converted_endpoints.next().unwrap();
1272 assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1273 Selection {
1274 id: s.id,
1275 start,
1276 end,
1277 reversed: s.reversed,
1278 goal: s.goal,
1279 }
1280 })
1281}
1282
1283fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
1284 selections: impl Iterator<Item = Selection<D>>,
1285) -> impl Iterator<Item = Selection<D>> {
1286 let mut selections = selections.peekable();
1287 iter::from_fn(move || {
1288 let mut selection = selections.next()?;
1289 while let Some(next_selection) = selections.peek() {
1290 if should_merge(
1291 selection.start,
1292 selection.end,
1293 next_selection.start,
1294 next_selection.end,
1295 true,
1296 ) {
1297 if selection.reversed == next_selection.reversed {
1298 selection.end = cmp::max(selection.end, next_selection.end);
1299 selections.next();
1300 } else {
1301 selection.end = cmp::max(selection.start, next_selection.start);
1302 break;
1303 }
1304 } else {
1305 break;
1306 }
1307 }
1308 assert!(
1309 selection.start <= selection.end,
1310 "selection.start: {:?}, selection.end: {:?}, selection.reversed: {:?}",
1311 selection.start,
1312 selection.end,
1313 selection.reversed
1314 );
1315 Some(selection)
1316 })
1317}
1318
1319/// Determines whether two selections should be merged into one.
1320///
1321/// Two selections should be merged when:
1322/// 1. They overlap: the selections share at least one position
1323/// 2. They have the same start position: one contains or equals the other
1324/// 3. A cursor touches a selection boundary: a zero-width selection (cursor) at the
1325/// start or end of another selection should be absorbed into it
1326///
1327/// Note: two selections that merely touch (one ends exactly where the other begins)
1328/// but don't share any positions remain separate, see: https://github.com/zed-industries/zed/issues/24748
1329fn should_merge<T: Ord + Copy>(a_start: T, a_end: T, b_start: T, b_end: T, sorted: bool) -> bool {
1330 let is_overlapping = if sorted {
1331 // When sorted, `a` starts before or at `b`, so overlap means `b` starts before `a` ends
1332 b_start < a_end
1333 } else {
1334 a_start < b_end && b_start < a_end
1335 };
1336
1337 // Selections starting at the same position should always merge (one contains the other)
1338 let same_start = a_start == b_start;
1339
1340 // A cursor (zero-width selection) touching another selection's boundary should merge.
1341 // This handles cases like a cursor at position X merging with a selection that
1342 // starts or ends at X.
1343 let is_cursor_a = a_start == a_end;
1344 let is_cursor_b = b_start == b_end;
1345 let cursor_at_boundary = (is_cursor_a && (a_start == b_start || a_end == b_end))
1346 || (is_cursor_b && (b_start == a_start || b_end == a_end));
1347
1348 is_overlapping || same_start || cursor_at_boundary
1349}