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