1use std::{
2 cell::Ref,
3 cmp, fmt, iter, mem,
4 ops::{Deref, DerefMut, Range, Sub},
5 sync::Arc,
6};
7
8use collections::HashMap;
9use gpui::{App, Entity, Pixels};
10use itertools::Itertools;
11use language::{Bias, Point, Selection, SelectionGoal, TextDimension};
12use util::post_inc;
13
14use crate::{
15 Anchor, DisplayPoint, DisplayRow, ExcerptId, MultiBuffer, MultiBufferSnapshot, SelectMode,
16 ToOffset, ToPoint,
17 display_map::{DisplayMap, DisplaySnapshot, ToDisplayPoint},
18 movement::TextLayoutDetails,
19};
20
21#[derive(Debug, Clone)]
22pub struct PendingSelection {
23 pub selection: Selection<Anchor>,
24 pub mode: SelectMode,
25}
26
27#[derive(Debug, Clone)]
28pub struct SelectionsCollection {
29 display_map: Entity<DisplayMap>,
30 buffer: Entity<MultiBuffer>,
31 next_selection_id: usize,
32 line_mode: bool,
33 /// The non-pending, non-overlapping selections.
34 /// The [SelectionsCollection::pending] selection could possibly overlap these
35 disjoint: Arc<[Selection<Anchor>]>,
36 /// A pending selection, such as when the mouse is being dragged
37 pending: Option<PendingSelection>,
38 select_mode: SelectMode,
39 is_extending: bool,
40}
41
42impl SelectionsCollection {
43 pub fn new(display_map: Entity<DisplayMap>, buffer: Entity<MultiBuffer>) -> Self {
44 Self {
45 display_map,
46 buffer,
47 next_selection_id: 1,
48 line_mode: false,
49 disjoint: Arc::default(),
50 pending: Some(PendingSelection {
51 selection: Selection {
52 id: 0,
53 start: Anchor::min(),
54 end: Anchor::min(),
55 reversed: false,
56 goal: SelectionGoal::None,
57 },
58 mode: SelectMode::Character,
59 }),
60 select_mode: SelectMode::Character,
61 is_extending: false,
62 }
63 }
64
65 pub fn display_map(&self, cx: &mut App) -> DisplaySnapshot {
66 self.display_map.update(cx, |map, cx| map.snapshot(cx))
67 }
68
69 fn buffer<'a>(&self, cx: &'a App) -> Ref<'a, MultiBufferSnapshot> {
70 self.buffer.read(cx).read(cx)
71 }
72
73 pub fn clone_state(&mut self, other: &SelectionsCollection) {
74 self.next_selection_id = other.next_selection_id;
75 self.line_mode = other.line_mode;
76 self.disjoint = other.disjoint.clone();
77 self.pending.clone_from(&other.pending);
78 }
79
80 pub fn count(&self) -> usize {
81 let mut count = self.disjoint.len();
82 if self.pending.is_some() {
83 count += 1;
84 }
85 count
86 }
87
88 /// The non-pending, non-overlapping selections. There could be a pending selection that
89 /// overlaps these if the mouse is being dragged, etc. This could also be empty if there is a
90 /// pending selection. Returned as selections over Anchors.
91 pub fn disjoint_anchors_arc(&self) -> Arc<[Selection<Anchor>]> {
92 self.disjoint.clone()
93 }
94
95 /// The non-pending, non-overlapping selections. There could be a pending selection that
96 /// overlaps these if the mouse is being dragged, etc. This could also be empty if there is a
97 /// pending selection. Returned as selections over Anchors.
98 pub fn disjoint_anchors(&self) -> &[Selection<Anchor>] {
99 &self.disjoint
100 }
101
102 pub fn disjoint_anchor_ranges(&self) -> impl Iterator<Item = Range<Anchor>> {
103 // Mapping the Arc slice would borrow it, whereas indexing captures it.
104 let disjoint = self.disjoint_anchors_arc();
105 (0..disjoint.len()).map(move |ix| disjoint[ix].range())
106 }
107
108 /// Non-overlapping selections using anchors, including the pending selection.
109 pub fn all_anchors(&self, cx: &mut App) -> Arc<[Selection<Anchor>]> {
110 if self.pending.is_none() {
111 self.disjoint_anchors_arc()
112 } else {
113 let all_offset_selections = self.all::<usize>(cx);
114 let buffer = self.buffer(cx);
115 all_offset_selections
116 .into_iter()
117 .map(|selection| selection_to_anchor_selection(selection, &buffer))
118 .collect()
119 }
120 }
121
122 pub fn pending_anchor(&self) -> Option<&Selection<Anchor>> {
123 self.pending.as_ref().map(|pending| &pending.selection)
124 }
125
126 pub fn pending_anchor_mut(&mut self) -> Option<&mut Selection<Anchor>> {
127 self.pending.as_mut().map(|pending| &mut pending.selection)
128 }
129
130 pub fn pending<D: TextDimension + Ord + Sub<D, Output = D>>(
131 &self,
132 cx: &mut App,
133 ) -> Option<Selection<D>> {
134 let map = self.display_map(cx);
135
136 resolve_selections(self.pending_anchor(), &map).next()
137 }
138
139 pub(crate) fn pending_mode(&self) -> Option<SelectMode> {
140 self.pending.as_ref().map(|pending| pending.mode.clone())
141 }
142
143 pub fn all<'a, D>(&self, cx: &mut App) -> Vec<Selection<D>>
144 where
145 D: 'a + TextDimension + Ord + Sub<D, Output = D>,
146 {
147 let map = self.display_map(cx);
148 let disjoint_anchors = &self.disjoint;
149 let mut disjoint = resolve_selections::<D, _>(disjoint_anchors.iter(), &map).peekable();
150 let mut pending_opt = self.pending::<D>(cx);
151 iter::from_fn(move || {
152 if let Some(pending) = pending_opt.as_mut() {
153 while let Some(next_selection) = disjoint.peek() {
154 if pending.start <= next_selection.end && pending.end >= next_selection.start {
155 let next_selection = disjoint.next().unwrap();
156 if next_selection.start < pending.start {
157 pending.start = next_selection.start;
158 }
159 if next_selection.end > pending.end {
160 pending.end = next_selection.end;
161 }
162 } else if next_selection.end < pending.start {
163 return disjoint.next();
164 } else {
165 break;
166 }
167 }
168
169 pending_opt.take()
170 } else {
171 disjoint.next()
172 }
173 })
174 .collect()
175 }
176
177 /// Returns all of the selections, adjusted to take into account the selection line_mode
178 pub fn all_adjusted(&self, cx: &mut App) -> Vec<Selection<Point>> {
179 let mut selections = self.all::<Point>(cx);
180 if self.line_mode {
181 let map = self.display_map(cx);
182 for selection in &mut selections {
183 let new_range = map.expand_to_line(selection.range());
184 selection.start = new_range.start;
185 selection.end = new_range.end;
186 }
187 }
188 selections
189 }
190
191 /// Returns all of the selections, adjusted to take into account the selection line_mode. Uses a provided snapshot to resolve selections.
192 pub fn all_adjusted_with_snapshot(
193 &self,
194 snapshot: &MultiBufferSnapshot,
195 ) -> Vec<Selection<Point>> {
196 let mut selections = self
197 .disjoint
198 .iter()
199 .chain(self.pending_anchor())
200 .map(|anchor| anchor.map(|anchor| anchor.to_point(&snapshot)))
201 .collect::<Vec<_>>();
202 if self.line_mode {
203 for selection in &mut selections {
204 let new_range = snapshot.expand_to_line(selection.range());
205 selection.start = new_range.start;
206 selection.end = new_range.end;
207 }
208 }
209 selections
210 }
211
212 /// Returns the newest selection, adjusted to take into account the selection line_mode
213 pub fn newest_adjusted(&self, cx: &mut App) -> Selection<Point> {
214 let mut selection = self.newest::<Point>(cx);
215 if self.line_mode {
216 let map = self.display_map(cx);
217 let new_range = map.expand_to_line(selection.range());
218 selection.start = new_range.start;
219 selection.end = new_range.end;
220 }
221 selection
222 }
223
224 pub fn all_adjusted_display(
225 &self,
226 cx: &mut App,
227 ) -> (DisplaySnapshot, Vec<Selection<DisplayPoint>>) {
228 if self.line_mode {
229 let selections = self.all::<Point>(cx);
230 let map = self.display_map(cx);
231 let result = selections
232 .into_iter()
233 .map(|mut selection| {
234 let new_range = map.expand_to_line(selection.range());
235 selection.start = new_range.start;
236 selection.end = new_range.end;
237 selection.map(|point| point.to_display_point(&map))
238 })
239 .collect();
240 (map, result)
241 } else {
242 self.all_display(cx)
243 }
244 }
245
246 pub fn disjoint_in_range<'a, D>(&self, range: Range<Anchor>, cx: &mut App) -> Vec<Selection<D>>
247 where
248 D: 'a + TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
249 {
250 let map = self.display_map(cx);
251 let start_ix = match self
252 .disjoint
253 .binary_search_by(|probe| probe.end.cmp(&range.start, map.buffer_snapshot()))
254 {
255 Ok(ix) | Err(ix) => ix,
256 };
257 let end_ix = match self
258 .disjoint
259 .binary_search_by(|probe| probe.start.cmp(&range.end, map.buffer_snapshot()))
260 {
261 Ok(ix) => ix + 1,
262 Err(ix) => ix,
263 };
264 resolve_selections(&self.disjoint[start_ix..end_ix], &map).collect()
265 }
266
267 pub fn all_display(&self, cx: &mut App) -> (DisplaySnapshot, Vec<Selection<DisplayPoint>>) {
268 let map = self.display_map(cx);
269 let disjoint_anchors = &self.disjoint;
270 let mut disjoint = resolve_selections_display(disjoint_anchors.iter(), &map).peekable();
271 let mut pending_opt = resolve_selections_display(self.pending_anchor(), &map).next();
272 let selections = iter::from_fn(move || {
273 if let Some(pending) = pending_opt.as_mut() {
274 while let Some(next_selection) = disjoint.peek() {
275 if pending.start <= next_selection.end && pending.end >= next_selection.start {
276 let next_selection = disjoint.next().unwrap();
277 if next_selection.start < pending.start {
278 pending.start = next_selection.start;
279 }
280 if next_selection.end > pending.end {
281 pending.end = next_selection.end;
282 }
283 } else if next_selection.end < pending.start {
284 return disjoint.next();
285 } else {
286 break;
287 }
288 }
289
290 pending_opt.take()
291 } else {
292 disjoint.next()
293 }
294 })
295 .collect();
296 (map, selections)
297 }
298
299 pub fn newest_anchor(&self) -> &Selection<Anchor> {
300 self.pending
301 .as_ref()
302 .map(|s| &s.selection)
303 .or_else(|| self.disjoint.iter().max_by_key(|s| s.id))
304 .unwrap()
305 }
306
307 pub fn newest<D: TextDimension + Ord + Sub<D, Output = D>>(
308 &self,
309 cx: &mut App,
310 ) -> Selection<D> {
311 let map = self.display_map(cx);
312
313 resolve_selections([self.newest_anchor()], &map)
314 .next()
315 .unwrap()
316 }
317
318 pub fn newest_display(&self, cx: &mut App) -> Selection<DisplayPoint> {
319 let map = self.display_map(cx);
320
321 resolve_selections_display([self.newest_anchor()], &map)
322 .next()
323 .unwrap()
324 }
325
326 pub fn oldest_anchor(&self) -> &Selection<Anchor> {
327 self.disjoint
328 .iter()
329 .min_by_key(|s| s.id)
330 .or_else(|| self.pending.as_ref().map(|p| &p.selection))
331 .unwrap()
332 }
333
334 pub fn oldest<D: TextDimension + Ord + Sub<D, Output = D>>(
335 &self,
336 cx: &mut App,
337 ) -> Selection<D> {
338 let map = self.display_map(cx);
339
340 resolve_selections([self.oldest_anchor()], &map)
341 .next()
342 .unwrap()
343 }
344
345 pub fn first_anchor(&self) -> Selection<Anchor> {
346 self.pending
347 .as_ref()
348 .map(|pending| pending.selection.clone())
349 .unwrap_or_else(|| self.disjoint.first().cloned().unwrap())
350 }
351
352 pub fn first<D: TextDimension + Ord + Sub<D, Output = D>>(&self, cx: &mut App) -> Selection<D> {
353 self.all(cx).first().unwrap().clone()
354 }
355
356 pub fn last<D: TextDimension + Ord + Sub<D, Output = D>>(&self, cx: &mut App) -> Selection<D> {
357 self.all(cx).last().unwrap().clone()
358 }
359
360 /// Returns a list of (potentially backwards!) ranges representing the selections.
361 /// Useful for test assertions, but prefer `.all()` instead.
362 #[cfg(any(test, feature = "test-support"))]
363 pub fn ranges<D: TextDimension + Ord + Sub<D, Output = D>>(
364 &self,
365 cx: &mut App,
366 ) -> Vec<Range<D>> {
367 self.all::<D>(cx)
368 .iter()
369 .map(|s| {
370 if s.reversed {
371 s.end..s.start
372 } else {
373 s.start..s.end
374 }
375 })
376 .collect()
377 }
378
379 #[cfg(any(test, feature = "test-support"))]
380 pub fn display_ranges(&self, cx: &mut App) -> Vec<Range<DisplayPoint>> {
381 let display_map = self.display_map(cx);
382 self.disjoint_anchors_arc()
383 .iter()
384 .chain(self.pending_anchor())
385 .map(|s| {
386 if s.reversed {
387 s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
388 } else {
389 s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
390 }
391 })
392 .collect()
393 }
394
395 pub fn build_columnar_selection(
396 &mut self,
397 display_map: &DisplaySnapshot,
398 row: DisplayRow,
399 positions: &Range<Pixels>,
400 reversed: bool,
401 text_layout_details: &TextLayoutDetails,
402 ) -> Option<Selection<Point>> {
403 let is_empty = positions.start == positions.end;
404 let line_len = display_map.line_len(row);
405 let line = display_map.layout_row(row, text_layout_details);
406 let start_col = line.closest_index_for_x(positions.start) as u32;
407
408 let (start, end) = if is_empty {
409 let point = DisplayPoint::new(row, std::cmp::min(start_col, line_len));
410 (point, point)
411 } else {
412 if start_col >= line_len {
413 return None;
414 }
415 let start = DisplayPoint::new(row, start_col);
416 let end_col = line.closest_index_for_x(positions.end) as u32;
417 let end = DisplayPoint::new(row, end_col);
418 (start, end)
419 };
420
421 Some(Selection {
422 id: post_inc(&mut self.next_selection_id),
423 start: start.to_point(display_map),
424 end: end.to_point(display_map),
425 reversed,
426 goal: SelectionGoal::HorizontalRange {
427 start: positions.start.into(),
428 end: positions.end.into(),
429 },
430 })
431 }
432
433 pub fn change_with<R>(
434 &mut self,
435 cx: &mut App,
436 change: impl FnOnce(&mut MutableSelectionsCollection) -> R,
437 ) -> (bool, R) {
438 let mut mutable_collection = MutableSelectionsCollection {
439 collection: self,
440 selections_changed: false,
441 cx,
442 };
443
444 let result = change(&mut mutable_collection);
445 assert!(
446 !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
447 "There must be at least one selection"
448 );
449 (mutable_collection.selections_changed, result)
450 }
451
452 pub fn next_selection_id(&self) -> usize {
453 self.next_selection_id
454 }
455
456 pub fn line_mode(&self) -> bool {
457 self.line_mode
458 }
459
460 pub fn set_line_mode(&mut self, line_mode: bool) {
461 self.line_mode = line_mode;
462 }
463
464 pub fn select_mode(&self) -> &SelectMode {
465 &self.select_mode
466 }
467
468 pub fn set_select_mode(&mut self, select_mode: SelectMode) {
469 self.select_mode = select_mode;
470 }
471
472 pub fn is_extending(&self) -> bool {
473 self.is_extending
474 }
475
476 pub fn set_is_extending(&mut self, is_extending: bool) {
477 self.is_extending = is_extending;
478 }
479}
480
481pub struct MutableSelectionsCollection<'a> {
482 collection: &'a mut SelectionsCollection,
483 selections_changed: bool,
484 cx: &'a mut App,
485}
486
487impl<'a> fmt::Debug for MutableSelectionsCollection<'a> {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 f.debug_struct("MutableSelectionsCollection")
490 .field("collection", &self.collection)
491 .field("selections_changed", &self.selections_changed)
492 .finish()
493 }
494}
495
496impl<'a> MutableSelectionsCollection<'a> {
497 pub fn display_map(&mut self) -> DisplaySnapshot {
498 self.collection.display_map(self.cx)
499 }
500
501 pub fn buffer(&self) -> Ref<'_, MultiBufferSnapshot> {
502 self.collection.buffer(self.cx)
503 }
504
505 pub fn clear_disjoint(&mut self) {
506 self.collection.disjoint = Arc::default();
507 }
508
509 pub fn delete(&mut self, selection_id: usize) {
510 let mut changed = false;
511 self.collection.disjoint = self
512 .disjoint
513 .iter()
514 .filter(|selection| {
515 let found = selection.id == selection_id;
516 changed |= found;
517 !found
518 })
519 .cloned()
520 .collect();
521
522 self.selections_changed |= changed;
523 }
524
525 pub fn clear_pending(&mut self) {
526 if self.collection.pending.is_some() {
527 self.collection.pending = None;
528 self.selections_changed = true;
529 }
530 }
531
532 pub(crate) fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
533 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
534 self.collection.pending = Some(PendingSelection {
535 selection: {
536 let mut start = range.start;
537 let mut end = range.end;
538 let reversed = if start.cmp(&end, &buffer).is_gt() {
539 mem::swap(&mut start, &mut end);
540 true
541 } else {
542 false
543 };
544 Selection {
545 id: post_inc(&mut self.collection.next_selection_id),
546 start,
547 end,
548 reversed,
549 goal: SelectionGoal::None,
550 }
551 },
552 mode,
553 });
554 self.selections_changed = true;
555 }
556
557 pub(crate) fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
558 self.collection.pending = Some(PendingSelection { selection, mode });
559 self.selections_changed = true;
560 }
561
562 pub fn try_cancel(&mut self) -> bool {
563 if let Some(pending) = self.collection.pending.take() {
564 if self.disjoint.is_empty() {
565 self.collection.disjoint = Arc::from([pending.selection]);
566 }
567 self.selections_changed = true;
568 return true;
569 }
570
571 let mut oldest = self.oldest_anchor().clone();
572 if self.count() > 1 {
573 self.collection.disjoint = Arc::from([oldest]);
574 self.selections_changed = true;
575 return true;
576 }
577
578 if !oldest.start.cmp(&oldest.end, &self.buffer()).is_eq() {
579 let head = oldest.head();
580 oldest.start = head;
581 oldest.end = head;
582 self.collection.disjoint = Arc::from([oldest]);
583 self.selections_changed = true;
584 return true;
585 }
586
587 false
588 }
589
590 pub fn insert_range<T>(&mut self, range: Range<T>)
591 where
592 T: 'a + ToOffset + ToPoint + TextDimension + Ord + Sub<T, Output = T> + std::marker::Copy,
593 {
594 let mut selections = self.collection.all(self.cx);
595 let mut start = range.start.to_offset(&self.buffer());
596 let mut end = range.end.to_offset(&self.buffer());
597 let reversed = if start > end {
598 mem::swap(&mut start, &mut end);
599 true
600 } else {
601 false
602 };
603 selections.push(Selection {
604 id: post_inc(&mut self.collection.next_selection_id),
605 start,
606 end,
607 reversed,
608 goal: SelectionGoal::None,
609 });
610 self.select(selections);
611 }
612
613 pub fn select<T>(&mut self, mut selections: Vec<Selection<T>>)
614 where
615 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
616 {
617 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
618 selections.sort_unstable_by_key(|s| s.start);
619 // Merge overlapping selections.
620 let mut i = 1;
621 while i < selections.len() {
622 if selections[i - 1].end >= selections[i].start {
623 let removed = selections.remove(i);
624 if removed.start < selections[i - 1].start {
625 selections[i - 1].start = removed.start;
626 }
627 if removed.end > selections[i - 1].end {
628 selections[i - 1].end = removed.end;
629 }
630 } else {
631 i += 1;
632 }
633 }
634
635 self.collection.disjoint = Arc::from_iter(
636 selections
637 .into_iter()
638 .map(|selection| selection_to_anchor_selection(selection, &buffer)),
639 );
640 self.collection.pending = None;
641 self.selections_changed = true;
642 }
643
644 pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
645 let map = self.display_map();
646 let resolved_selections =
647 resolve_selections::<usize, _>(&selections, &map).collect::<Vec<_>>();
648 self.select(resolved_selections);
649 }
650
651 pub fn select_ranges<I, T>(&mut self, ranges: I)
652 where
653 I: IntoIterator<Item = Range<T>>,
654 T: ToOffset,
655 {
656 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
657 let ranges = ranges
658 .into_iter()
659 .map(|range| range.start.to_offset(&buffer)..range.end.to_offset(&buffer));
660 self.select_offset_ranges(ranges);
661 }
662
663 fn select_offset_ranges<I>(&mut self, ranges: I)
664 where
665 I: IntoIterator<Item = Range<usize>>,
666 {
667 let selections = ranges
668 .into_iter()
669 .map(|range| {
670 let mut start = range.start;
671 let mut end = range.end;
672 let reversed = if start > end {
673 mem::swap(&mut start, &mut end);
674 true
675 } else {
676 false
677 };
678 Selection {
679 id: post_inc(&mut self.collection.next_selection_id),
680 start,
681 end,
682 reversed,
683 goal: SelectionGoal::None,
684 }
685 })
686 .collect::<Vec<_>>();
687
688 self.select(selections)
689 }
690
691 pub fn select_anchor_ranges<I>(&mut self, ranges: I)
692 where
693 I: IntoIterator<Item = Range<Anchor>>,
694 {
695 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
696 let selections = ranges
697 .into_iter()
698 .map(|range| {
699 let mut start = range.start;
700 let mut end = range.end;
701 let reversed = if start.cmp(&end, &buffer).is_gt() {
702 mem::swap(&mut start, &mut end);
703 true
704 } else {
705 false
706 };
707 Selection {
708 id: post_inc(&mut self.collection.next_selection_id),
709 start,
710 end,
711 reversed,
712 goal: SelectionGoal::None,
713 }
714 })
715 .collect::<Vec<_>>();
716 self.select_anchors(selections)
717 }
718
719 pub fn new_selection_id(&mut self) -> usize {
720 post_inc(&mut self.next_selection_id)
721 }
722
723 pub fn select_display_ranges<T>(&mut self, ranges: T)
724 where
725 T: IntoIterator<Item = Range<DisplayPoint>>,
726 {
727 let display_map = self.display_map();
728 let selections = ranges
729 .into_iter()
730 .map(|range| {
731 let mut start = range.start;
732 let mut end = range.end;
733 let reversed = if start > end {
734 mem::swap(&mut start, &mut end);
735 true
736 } else {
737 false
738 };
739 Selection {
740 id: post_inc(&mut self.collection.next_selection_id),
741 start: start.to_point(&display_map),
742 end: end.to_point(&display_map),
743 reversed,
744 goal: SelectionGoal::None,
745 }
746 })
747 .collect();
748 self.select(selections);
749 }
750
751 pub fn reverse_selections(&mut self) {
752 let map = &self.display_map();
753 let mut new_selections: Vec<Selection<Point>> = Vec::new();
754 let disjoint = self.disjoint.clone();
755 for selection in disjoint
756 .iter()
757 .sorted_by(|first, second| Ord::cmp(&second.id, &first.id))
758 .collect::<Vec<&Selection<Anchor>>>()
759 {
760 new_selections.push(Selection {
761 id: self.new_selection_id(),
762 start: selection.start.to_display_point(map).to_point(map),
763 end: selection.end.to_display_point(map).to_point(map),
764 reversed: selection.reversed,
765 goal: selection.goal,
766 });
767 }
768 self.select(new_selections);
769 }
770
771 pub fn move_with(
772 &mut self,
773 mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
774 ) {
775 let mut changed = false;
776 let display_map = self.display_map();
777 let (_, selections) = self.collection.all_display(self.cx);
778 let selections = selections
779 .into_iter()
780 .map(|selection| {
781 let mut moved_selection = selection.clone();
782 move_selection(&display_map, &mut moved_selection);
783 if selection != moved_selection {
784 changed = true;
785 }
786 moved_selection.map(|display_point| display_point.to_point(&display_map))
787 })
788 .collect();
789
790 if changed {
791 self.select(selections)
792 }
793 }
794
795 pub fn move_offsets_with(
796 &mut self,
797 mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<usize>),
798 ) {
799 let mut changed = false;
800 let snapshot = self.buffer().clone();
801 let selections = self
802 .collection
803 .all::<usize>(self.cx)
804 .into_iter()
805 .map(|selection| {
806 let mut moved_selection = selection.clone();
807 move_selection(&snapshot, &mut moved_selection);
808 if selection != moved_selection {
809 changed = true;
810 }
811 moved_selection
812 })
813 .collect();
814 drop(snapshot);
815
816 if changed {
817 self.select(selections)
818 }
819 }
820
821 pub fn move_heads_with(
822 &mut self,
823 mut update_head: impl FnMut(
824 &DisplaySnapshot,
825 DisplayPoint,
826 SelectionGoal,
827 ) -> (DisplayPoint, SelectionGoal),
828 ) {
829 self.move_with(|map, selection| {
830 let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
831 selection.set_head(new_head, new_goal);
832 });
833 }
834
835 pub fn move_cursors_with(
836 &mut self,
837 mut update_cursor_position: impl FnMut(
838 &DisplaySnapshot,
839 DisplayPoint,
840 SelectionGoal,
841 ) -> (DisplayPoint, SelectionGoal),
842 ) {
843 self.move_with(|map, selection| {
844 let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
845 selection.collapse_to(cursor, new_goal)
846 });
847 }
848
849 pub fn maybe_move_cursors_with(
850 &mut self,
851 mut update_cursor_position: impl FnMut(
852 &DisplaySnapshot,
853 DisplayPoint,
854 SelectionGoal,
855 ) -> Option<(DisplayPoint, SelectionGoal)>,
856 ) {
857 self.move_cursors_with(|map, point, goal| {
858 update_cursor_position(map, point, goal).unwrap_or((point, goal))
859 })
860 }
861
862 pub fn replace_cursors_with(
863 &mut self,
864 find_replacement_cursors: impl FnOnce(&DisplaySnapshot) -> Vec<DisplayPoint>,
865 ) {
866 let display_map = self.display_map();
867 let new_selections = find_replacement_cursors(&display_map)
868 .into_iter()
869 .map(|cursor| {
870 let cursor_point = cursor.to_point(&display_map);
871 Selection {
872 id: post_inc(&mut self.collection.next_selection_id),
873 start: cursor_point,
874 end: cursor_point,
875 reversed: false,
876 goal: SelectionGoal::None,
877 }
878 })
879 .collect();
880 self.select(new_selections);
881 }
882
883 /// Compute new ranges for any selections that were located in excerpts that have
884 /// since been removed.
885 ///
886 /// Returns a `HashMap` indicating which selections whose former head position
887 /// was no longer present. The keys of the map are selection ids. The values are
888 /// the id of the new excerpt where the head of the selection has been moved.
889 pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
890 let mut pending = self.collection.pending.take();
891 let mut selections_with_lost_position = HashMap::default();
892
893 let anchors_with_status = {
894 let buffer = self.buffer();
895 let disjoint_anchors = self
896 .disjoint
897 .iter()
898 .flat_map(|selection| [&selection.start, &selection.end]);
899 buffer.refresh_anchors(disjoint_anchors)
900 };
901 let adjusted_disjoint: Vec<_> = anchors_with_status
902 .chunks(2)
903 .map(|selection_anchors| {
904 let (anchor_ix, start, kept_start) = selection_anchors[0];
905 let (_, end, kept_end) = selection_anchors[1];
906 let selection = &self.disjoint[anchor_ix / 2];
907 let kept_head = if selection.reversed {
908 kept_start
909 } else {
910 kept_end
911 };
912 if !kept_head {
913 selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
914 }
915
916 Selection {
917 id: selection.id,
918 start,
919 end,
920 reversed: selection.reversed,
921 goal: selection.goal,
922 }
923 })
924 .collect();
925
926 if !adjusted_disjoint.is_empty() {
927 let map = self.display_map();
928 let resolved_selections = resolve_selections(adjusted_disjoint.iter(), &map).collect();
929 self.select::<usize>(resolved_selections);
930 }
931
932 if let Some(pending) = pending.as_mut() {
933 let buffer = self.buffer();
934 let anchors =
935 buffer.refresh_anchors([&pending.selection.start, &pending.selection.end]);
936 let (_, start, kept_start) = anchors[0];
937 let (_, end, kept_end) = anchors[1];
938 let kept_head = if pending.selection.reversed {
939 kept_start
940 } else {
941 kept_end
942 };
943 if !kept_head {
944 selections_with_lost_position
945 .insert(pending.selection.id, pending.selection.head().excerpt_id);
946 }
947
948 pending.selection.start = start;
949 pending.selection.end = end;
950 }
951 self.collection.pending = pending;
952 self.selections_changed = true;
953
954 selections_with_lost_position
955 }
956}
957
958impl Deref for MutableSelectionsCollection<'_> {
959 type Target = SelectionsCollection;
960 fn deref(&self) -> &Self::Target {
961 self.collection
962 }
963}
964
965impl DerefMut for MutableSelectionsCollection<'_> {
966 fn deref_mut(&mut self) -> &mut Self::Target {
967 self.collection
968 }
969}
970
971fn selection_to_anchor_selection<T>(
972 selection: Selection<T>,
973 buffer: &MultiBufferSnapshot,
974) -> Selection<Anchor>
975where
976 T: ToOffset + Ord,
977{
978 let end_bias = if selection.start == selection.end {
979 Bias::Right
980 } else {
981 Bias::Left
982 };
983 Selection {
984 id: selection.id,
985 start: buffer.anchor_after(selection.start),
986 end: buffer.anchor_at(selection.end, end_bias),
987 reversed: selection.reversed,
988 goal: selection.goal,
989 }
990}
991
992fn resolve_selections_point<'a>(
993 selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
994 map: &'a DisplaySnapshot,
995) -> impl 'a + Iterator<Item = Selection<Point>> {
996 let (to_summarize, selections) = selections.into_iter().tee();
997 let mut summaries = map
998 .buffer_snapshot()
999 .summaries_for_anchors::<Point, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
1000 .into_iter();
1001 selections.map(move |s| {
1002 let start = summaries.next().unwrap();
1003 let end = summaries.next().unwrap();
1004 assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1005 Selection {
1006 id: s.id,
1007 start,
1008 end,
1009 reversed: s.reversed,
1010 goal: s.goal,
1011 }
1012 })
1013}
1014
1015// Panics if passed selections are not in order
1016fn resolve_selections_display<'a>(
1017 selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1018 map: &'a DisplaySnapshot,
1019) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
1020 let selections = resolve_selections_point(selections, map).map(move |s| {
1021 let display_start = map.point_to_display_point(s.start, Bias::Left);
1022 let display_end = map.point_to_display_point(
1023 s.end,
1024 if s.start == s.end {
1025 Bias::Right
1026 } else {
1027 Bias::Left
1028 },
1029 );
1030 assert!(
1031 display_start <= display_end,
1032 "display_start: {:?}, display_end: {:?}",
1033 display_start,
1034 display_end
1035 );
1036 Selection {
1037 id: s.id,
1038 start: display_start,
1039 end: display_end,
1040 reversed: s.reversed,
1041 goal: s.goal,
1042 }
1043 });
1044 coalesce_selections(selections)
1045}
1046
1047// Panics if passed selections are not in order
1048pub(crate) fn resolve_selections<'a, D, I>(
1049 selections: I,
1050 map: &'a DisplaySnapshot,
1051) -> impl 'a + Iterator<Item = Selection<D>>
1052where
1053 D: TextDimension + Ord + Sub<D, Output = D>,
1054 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1055{
1056 let (to_convert, selections) = resolve_selections_display(selections, map).tee();
1057 let mut converted_endpoints =
1058 map.buffer_snapshot()
1059 .dimensions_from_points::<D>(to_convert.flat_map(|s| {
1060 let start = map.display_point_to_point(s.start, Bias::Left);
1061 let end = map.display_point_to_point(s.end, Bias::Right);
1062 assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1063 [start, end]
1064 }));
1065 selections.map(move |s| {
1066 let start = converted_endpoints.next().unwrap();
1067 let end = converted_endpoints.next().unwrap();
1068 assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1069 Selection {
1070 id: s.id,
1071 start,
1072 end,
1073 reversed: s.reversed,
1074 goal: s.goal,
1075 }
1076 })
1077}
1078
1079fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
1080 selections: impl Iterator<Item = Selection<D>>,
1081) -> impl Iterator<Item = Selection<D>> {
1082 let mut selections = selections.peekable();
1083 iter::from_fn(move || {
1084 let mut selection = selections.next()?;
1085 while let Some(next_selection) = selections.peek() {
1086 if selection.end >= next_selection.start {
1087 if selection.reversed == next_selection.reversed {
1088 selection.end = cmp::max(selection.end, next_selection.end);
1089 selections.next();
1090 } else {
1091 selection.end = cmp::max(selection.start, next_selection.start);
1092 break;
1093 }
1094 } else {
1095 break;
1096 }
1097 }
1098 assert!(
1099 selection.start <= selection.end,
1100 "selection.start: {:?}, selection.end: {:?}, selection.reversed: {:?}",
1101 selection.start,
1102 selection.end,
1103 selection.reversed
1104 );
1105 Some(selection)
1106 })
1107}