selections_collection.rs

  1use std::{
  2    cell::Ref,
  3    cmp, iter, mem,
  4    ops::{Deref, Range, Sub},
  5    sync::Arc,
  6};
  7
  8use collections::HashMap;
  9use gpui::{AppContext, ModelHandle};
 10use itertools::Itertools;
 11use language::{Bias, Point, Selection, SelectionGoal, TextDimension, ToPoint};
 12use util::post_inc;
 13
 14use crate::{
 15    display_map::{DisplayMap, DisplaySnapshot, ToDisplayPoint},
 16    Anchor, DisplayPoint, ExcerptId, MultiBuffer, MultiBufferSnapshot, SelectMode, ToOffset,
 17};
 18
 19#[derive(Debug, Clone)]
 20pub struct PendingSelection {
 21    pub selection: Selection<Anchor>,
 22    pub mode: SelectMode,
 23}
 24
 25#[derive(Debug, Clone)]
 26pub struct SelectionsCollection {
 27    display_map: ModelHandle<DisplayMap>,
 28    buffer: ModelHandle<MultiBuffer>,
 29    pub next_selection_id: usize,
 30    pub line_mode: bool,
 31    disjoint: Arc<[Selection<Anchor>]>,
 32    pending: Option<PendingSelection>,
 33}
 34
 35impl SelectionsCollection {
 36    pub fn new(display_map: ModelHandle<DisplayMap>, buffer: ModelHandle<MultiBuffer>) -> Self {
 37        Self {
 38            display_map,
 39            buffer,
 40            next_selection_id: 1,
 41            line_mode: false,
 42            disjoint: Arc::from([]),
 43            pending: Some(PendingSelection {
 44                selection: Selection {
 45                    id: 0,
 46                    start: Anchor::min(),
 47                    end: Anchor::min(),
 48                    reversed: false,
 49                    goal: SelectionGoal::None,
 50                },
 51                mode: SelectMode::Character,
 52            }),
 53        }
 54    }
 55
 56    fn display_map(&self, cx: &mut AppContext) -> DisplaySnapshot {
 57        self.display_map.update(cx, |map, cx| map.snapshot(cx))
 58    }
 59
 60    fn buffer<'a>(&self, cx: &'a AppContext) -> Ref<'a, MultiBufferSnapshot> {
 61        self.buffer.read(cx).read(cx)
 62    }
 63
 64    pub fn clone_state(&mut self, other: &SelectionsCollection) {
 65        self.next_selection_id = other.next_selection_id;
 66        self.line_mode = other.line_mode;
 67        self.disjoint = other.disjoint.clone();
 68        self.pending = other.pending.clone();
 69    }
 70
 71    pub fn count(&self) -> usize {
 72        let mut count = self.disjoint.len();
 73        if self.pending.is_some() {
 74            count += 1;
 75        }
 76        count
 77    }
 78
 79    /// The non-pending, non-overlapping selections. There could still be a pending
 80    /// selection that overlaps these if the mouse is being dragged, etc. Returned as
 81    /// selections over Anchors.
 82    pub fn disjoint_anchors(&self) -> Arc<[Selection<Anchor>]> {
 83        self.disjoint.clone()
 84    }
 85
 86    pub fn pending_anchor(&self) -> Option<Selection<Anchor>> {
 87        self.pending
 88            .as_ref()
 89            .map(|pending| pending.selection.clone())
 90    }
 91
 92    pub fn pending<D: TextDimension + Ord + Sub<D, Output = D>>(
 93        &self,
 94        cx: &AppContext,
 95    ) -> Option<Selection<D>> {
 96        self.pending_anchor()
 97            .as_ref()
 98            .map(|pending| pending.map(|p| p.summary::<D>(&self.buffer(cx))))
 99    }
100
101    pub fn pending_mode(&self) -> Option<SelectMode> {
102        self.pending.as_ref().map(|pending| pending.mode.clone())
103    }
104
105    pub fn all<'a, D>(&self, cx: &AppContext) -> Vec<Selection<D>>
106    where
107        D: 'a + TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
108    {
109        let disjoint_anchors = &self.disjoint;
110        let mut disjoint =
111            resolve_multiple::<D, _>(disjoint_anchors.iter(), &self.buffer(cx)).peekable();
112
113        let mut pending_opt = self.pending::<D>(cx);
114
115        iter::from_fn(move || {
116            if let Some(pending) = pending_opt.as_mut() {
117                while let Some(next_selection) = disjoint.peek() {
118                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
119                        let next_selection = disjoint.next().unwrap();
120                        if next_selection.start < pending.start {
121                            pending.start = next_selection.start;
122                        }
123                        if next_selection.end > pending.end {
124                            pending.end = next_selection.end;
125                        }
126                    } else if next_selection.end < pending.start {
127                        return disjoint.next();
128                    } else {
129                        break;
130                    }
131                }
132
133                pending_opt.take()
134            } else {
135                disjoint.next()
136            }
137        })
138        .collect()
139    }
140
141    /// Returns all of the selections, adjusted to take into account the selection line_mode
142    pub fn all_adjusted(&self, cx: &mut AppContext) -> Vec<Selection<Point>> {
143        let mut selections = self.all::<Point>(cx);
144        if self.line_mode {
145            let map = self.display_map(cx);
146            for selection in &mut selections {
147                let new_range = map.expand_to_line(selection.range());
148                selection.start = new_range.start;
149                selection.end = new_range.end;
150            }
151        }
152        selections
153    }
154
155    pub fn all_adjusted_display(
156        &self,
157        cx: &mut AppContext,
158    ) -> (DisplaySnapshot, Vec<Selection<DisplayPoint>>) {
159        if self.line_mode {
160            let selections = self.all::<Point>(cx);
161            let map = self.display_map(cx);
162            let result = selections
163                .into_iter()
164                .map(|mut selection| {
165                    let new_range = map.expand_to_line(selection.range());
166                    selection.start = new_range.start;
167                    selection.end = new_range.end;
168                    selection.map(|point| point.to_display_point(&map))
169                })
170                .collect();
171            (map, result)
172        } else {
173            self.all_display(cx)
174        }
175    }
176
177    pub fn disjoint_in_range<'a, D>(
178        &self,
179        range: Range<Anchor>,
180        cx: &AppContext,
181    ) -> Vec<Selection<D>>
182    where
183        D: 'a + TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
184    {
185        let buffer = self.buffer(cx);
186        let start_ix = match self
187            .disjoint
188            .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer))
189        {
190            Ok(ix) | Err(ix) => ix,
191        };
192        let end_ix = match self
193            .disjoint
194            .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer))
195        {
196            Ok(ix) => ix + 1,
197            Err(ix) => ix,
198        };
199        resolve_multiple(&self.disjoint[start_ix..end_ix], &buffer).collect()
200    }
201
202    pub fn all_display(
203        &self,
204        cx: &mut AppContext,
205    ) -> (DisplaySnapshot, Vec<Selection<DisplayPoint>>) {
206        let display_map = self.display_map(cx);
207        let selections = self
208            .all::<Point>(cx)
209            .into_iter()
210            .map(|selection| selection.map(|point| point.to_display_point(&display_map)))
211            .collect();
212        (display_map, selections)
213    }
214
215    pub fn newest_anchor(&self) -> &Selection<Anchor> {
216        self.pending
217            .as_ref()
218            .map(|s| &s.selection)
219            .or_else(|| self.disjoint.iter().max_by_key(|s| s.id))
220            .unwrap()
221    }
222
223    pub fn newest<D: TextDimension + Ord + Sub<D, Output = D>>(
224        &self,
225        cx: &AppContext,
226    ) -> Selection<D> {
227        resolve(self.newest_anchor(), &self.buffer(cx))
228    }
229
230    pub fn newest_display(&self, cx: &mut AppContext) -> Selection<DisplayPoint> {
231        let display_map = self.display_map(cx);
232        let selection = self
233            .newest_anchor()
234            .map(|point| point.to_display_point(&display_map));
235        selection
236    }
237
238    pub fn oldest_anchor(&self) -> &Selection<Anchor> {
239        self.disjoint
240            .iter()
241            .min_by_key(|s| s.id)
242            .or_else(|| self.pending.as_ref().map(|p| &p.selection))
243            .unwrap()
244    }
245
246    pub fn oldest<D: TextDimension + Ord + Sub<D, Output = D>>(
247        &self,
248        cx: &AppContext,
249    ) -> Selection<D> {
250        resolve(self.oldest_anchor(), &self.buffer(cx))
251    }
252
253    pub fn first<D: TextDimension + Ord + Sub<D, Output = D>>(
254        &self,
255        cx: &AppContext,
256    ) -> Selection<D> {
257        self.all(cx).first().unwrap().clone()
258    }
259
260    pub fn last<D: TextDimension + Ord + Sub<D, Output = D>>(
261        &self,
262        cx: &AppContext,
263    ) -> Selection<D> {
264        self.all(cx).last().unwrap().clone()
265    }
266
267    #[cfg(any(test, feature = "test-support"))]
268    pub fn ranges<D: TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug>(
269        &self,
270        cx: &AppContext,
271    ) -> Vec<Range<D>> {
272        self.all::<D>(cx)
273            .iter()
274            .map(|s| {
275                if s.reversed {
276                    s.end.clone()..s.start.clone()
277                } else {
278                    s.start.clone()..s.end.clone()
279                }
280            })
281            .collect()
282    }
283
284    #[cfg(any(test, feature = "test-support"))]
285    pub fn display_ranges(&self, cx: &mut AppContext) -> Vec<Range<DisplayPoint>> {
286        let display_map = self.display_map(cx);
287        self.disjoint_anchors()
288            .iter()
289            .chain(self.pending_anchor().as_ref())
290            .map(|s| {
291                if s.reversed {
292                    s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
293                } else {
294                    s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
295                }
296            })
297            .collect()
298    }
299
300    pub fn build_columnar_selection(
301        &mut self,
302        display_map: &DisplaySnapshot,
303        row: u32,
304        columns: &Range<u32>,
305        reversed: bool,
306    ) -> Option<Selection<Point>> {
307        let is_empty = columns.start == columns.end;
308        let line_len = display_map.line_len(row);
309        if columns.start < line_len || (is_empty && columns.start == line_len) {
310            let start = DisplayPoint::new(row, columns.start);
311            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
312
313            Some(Selection {
314                id: post_inc(&mut self.next_selection_id),
315                start: start.to_point(display_map),
316                end: end.to_point(display_map),
317                reversed,
318                goal: SelectionGoal::ColumnRange {
319                    start: columns.start,
320                    end: columns.end,
321                },
322            })
323        } else {
324            None
325        }
326    }
327
328    pub(crate) fn change_with<R>(
329        &mut self,
330        cx: &mut AppContext,
331        change: impl FnOnce(&mut MutableSelectionsCollection) -> R,
332    ) -> (bool, R) {
333        let mut mutable_collection = MutableSelectionsCollection {
334            collection: self,
335            selections_changed: false,
336            cx,
337        };
338
339        let result = change(&mut mutable_collection);
340        assert!(
341            !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
342            "There must be at least one selection"
343        );
344        (mutable_collection.selections_changed, result)
345    }
346}
347
348pub struct MutableSelectionsCollection<'a> {
349    collection: &'a mut SelectionsCollection,
350    selections_changed: bool,
351    cx: &'a mut AppContext,
352}
353
354impl<'a> MutableSelectionsCollection<'a> {
355    fn display_map(&mut self) -> DisplaySnapshot {
356        self.collection.display_map(self.cx)
357    }
358
359    fn buffer(&self) -> Ref<MultiBufferSnapshot> {
360        self.collection.buffer(self.cx)
361    }
362
363    pub fn clear_disjoint(&mut self) {
364        self.collection.disjoint = Arc::from([]);
365    }
366
367    pub fn delete(&mut self, selection_id: usize) {
368        let mut changed = false;
369        self.collection.disjoint = self
370            .disjoint
371            .iter()
372            .filter(|selection| {
373                let found = selection.id == selection_id;
374                changed |= found;
375                !found
376            })
377            .cloned()
378            .collect();
379
380        self.selections_changed |= changed;
381    }
382
383    pub fn clear_pending(&mut self) {
384        if self.collection.pending.is_some() {
385            self.collection.pending = None;
386            self.selections_changed = true;
387        }
388    }
389
390    pub fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
391        self.collection.pending = Some(PendingSelection {
392            selection: Selection {
393                id: post_inc(&mut self.collection.next_selection_id),
394                start: range.start,
395                end: range.end,
396                reversed: false,
397                goal: SelectionGoal::None,
398            },
399            mode,
400        });
401        self.selections_changed = true;
402    }
403
404    pub fn set_pending_display_range(&mut self, range: Range<DisplayPoint>, mode: SelectMode) {
405        let (start, end, reversed) = {
406            let display_map = self.display_map();
407            let buffer = self.buffer();
408            let mut start = range.start;
409            let mut end = range.end;
410            let reversed = if start > end {
411                mem::swap(&mut start, &mut end);
412                true
413            } else {
414                false
415            };
416
417            let end_bias = if end > start { Bias::Left } else { Bias::Right };
418            (
419                buffer.anchor_before(start.to_point(&display_map)),
420                buffer.anchor_at(end.to_point(&display_map), end_bias),
421                reversed,
422            )
423        };
424
425        let new_pending = PendingSelection {
426            selection: Selection {
427                id: post_inc(&mut self.collection.next_selection_id),
428                start,
429                end,
430                reversed,
431                goal: SelectionGoal::None,
432            },
433            mode,
434        };
435
436        self.collection.pending = Some(new_pending);
437        self.selections_changed = true;
438    }
439
440    pub fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
441        self.collection.pending = Some(PendingSelection { selection, mode });
442        self.selections_changed = true;
443    }
444
445    pub fn try_cancel(&mut self) -> bool {
446        if let Some(pending) = self.collection.pending.take() {
447            if self.disjoint.is_empty() {
448                self.collection.disjoint = Arc::from([pending.selection]);
449            }
450            self.selections_changed = true;
451            return true;
452        }
453
454        let mut oldest = self.oldest_anchor().clone();
455        if self.count() > 1 {
456            self.collection.disjoint = Arc::from([oldest]);
457            self.selections_changed = true;
458            return true;
459        }
460
461        if !oldest.start.cmp(&oldest.end, &self.buffer()).is_eq() {
462            let head = oldest.head();
463            oldest.start = head.clone();
464            oldest.end = head;
465            self.collection.disjoint = Arc::from([oldest]);
466            self.selections_changed = true;
467            return true;
468        }
469
470        false
471    }
472
473    pub fn insert_range<T>(&mut self, range: Range<T>)
474    where
475        T: 'a + ToOffset + ToPoint + TextDimension + Ord + Sub<T, Output = T> + std::marker::Copy,
476    {
477        let mut selections = self.all(self.cx);
478        let mut start = range.start.to_offset(&self.buffer());
479        let mut end = range.end.to_offset(&self.buffer());
480        let reversed = if start > end {
481            mem::swap(&mut start, &mut end);
482            true
483        } else {
484            false
485        };
486        selections.push(Selection {
487            id: post_inc(&mut self.collection.next_selection_id),
488            start,
489            end,
490            reversed,
491            goal: SelectionGoal::None,
492        });
493        self.select(selections);
494    }
495
496    pub fn select<T>(&mut self, mut selections: Vec<Selection<T>>)
497    where
498        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
499    {
500        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
501        selections.sort_unstable_by_key(|s| s.start);
502        // Merge overlapping selections.
503        let mut i = 1;
504        while i < selections.len() {
505            if selections[i - 1].end >= selections[i].start {
506                let removed = selections.remove(i);
507                if removed.start < selections[i - 1].start {
508                    selections[i - 1].start = removed.start;
509                }
510                if removed.end > selections[i - 1].end {
511                    selections[i - 1].end = removed.end;
512                }
513            } else {
514                i += 1;
515            }
516        }
517
518        self.collection.disjoint = Arc::from_iter(selections.into_iter().map(|selection| {
519            let end_bias = if selection.end > selection.start {
520                Bias::Left
521            } else {
522                Bias::Right
523            };
524            Selection {
525                id: selection.id,
526                start: buffer.anchor_after(selection.start),
527                end: buffer.anchor_at(selection.end, end_bias),
528                reversed: selection.reversed,
529                goal: selection.goal,
530            }
531        }));
532
533        self.collection.pending = None;
534        self.selections_changed = true;
535    }
536
537    pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
538        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
539        let resolved_selections =
540            resolve_multiple::<usize, _>(&selections, &buffer).collect::<Vec<_>>();
541        self.select(resolved_selections);
542    }
543
544    pub fn select_ranges<I, T>(&mut self, ranges: I)
545    where
546        I: IntoIterator<Item = Range<T>>,
547        T: ToOffset,
548    {
549        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
550        let ranges = ranges
551            .into_iter()
552            .map(|range| range.start.to_offset(&buffer)..range.end.to_offset(&buffer));
553        self.select_offset_ranges(ranges);
554    }
555
556    fn select_offset_ranges<I>(&mut self, ranges: I)
557    where
558        I: IntoIterator<Item = Range<usize>>,
559    {
560        let selections = ranges
561            .into_iter()
562            .map(|range| {
563                let mut start = range.start;
564                let mut end = range.end;
565                let reversed = if start > end {
566                    mem::swap(&mut start, &mut end);
567                    true
568                } else {
569                    false
570                };
571                Selection {
572                    id: post_inc(&mut self.collection.next_selection_id),
573                    start,
574                    end,
575                    reversed,
576                    goal: SelectionGoal::None,
577                }
578            })
579            .collect::<Vec<_>>();
580
581        self.select(selections)
582    }
583
584    pub fn select_anchor_ranges<I: IntoIterator<Item = Range<Anchor>>>(&mut self, ranges: I) {
585        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
586        let selections = ranges
587            .into_iter()
588            .map(|range| {
589                let mut start = range.start;
590                let mut end = range.end;
591                let reversed = if start.cmp(&end, &buffer).is_gt() {
592                    mem::swap(&mut start, &mut end);
593                    true
594                } else {
595                    false
596                };
597                Selection {
598                    id: post_inc(&mut self.collection.next_selection_id),
599                    start,
600                    end,
601                    reversed,
602                    goal: SelectionGoal::None,
603                }
604            })
605            .collect::<Vec<_>>();
606
607        self.select_anchors(selections)
608    }
609
610    pub fn select_display_ranges<T>(&mut self, ranges: T)
611    where
612        T: IntoIterator<Item = Range<DisplayPoint>>,
613    {
614        let display_map = self.display_map();
615        let selections = ranges
616            .into_iter()
617            .map(|range| {
618                let mut start = range.start;
619                let mut end = range.end;
620                let reversed = if start > end {
621                    mem::swap(&mut start, &mut end);
622                    true
623                } else {
624                    false
625                };
626                Selection {
627                    id: post_inc(&mut self.collection.next_selection_id),
628                    start: start.to_point(&display_map),
629                    end: end.to_point(&display_map),
630                    reversed,
631                    goal: SelectionGoal::None,
632                }
633            })
634            .collect();
635        self.select(selections);
636    }
637
638    pub fn move_with(
639        &mut self,
640        mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
641    ) {
642        let mut changed = false;
643        let display_map = self.display_map();
644        let selections = self
645            .all::<Point>(self.cx)
646            .into_iter()
647            .map(|selection| {
648                let mut moved_selection =
649                    selection.map(|point| point.to_display_point(&display_map));
650                move_selection(&display_map, &mut moved_selection);
651                let moved_selection =
652                    moved_selection.map(|display_point| display_point.to_point(&display_map));
653                if selection != moved_selection {
654                    changed = true;
655                }
656                moved_selection
657            })
658            .collect();
659
660        if changed {
661            self.select(selections)
662        }
663    }
664
665    pub fn move_offsets_with(
666        &mut self,
667        mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<usize>),
668    ) {
669        let mut changed = false;
670        let snapshot = self.buffer().clone();
671        let selections = self
672            .all::<usize>(self.cx)
673            .into_iter()
674            .map(|selection| {
675                let mut moved_selection = selection.clone();
676                move_selection(&snapshot, &mut moved_selection);
677                if selection != moved_selection {
678                    changed = true;
679                }
680                moved_selection
681            })
682            .collect();
683        drop(snapshot);
684
685        if changed {
686            self.select(selections)
687        }
688    }
689
690    pub fn move_heads_with(
691        &mut self,
692        mut update_head: impl FnMut(
693            &DisplaySnapshot,
694            DisplayPoint,
695            SelectionGoal,
696        ) -> (DisplayPoint, SelectionGoal),
697    ) {
698        self.move_with(|map, selection| {
699            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
700            selection.set_head(new_head, new_goal);
701        });
702    }
703
704    pub fn move_cursors_with(
705        &mut self,
706        mut update_cursor_position: impl FnMut(
707            &DisplaySnapshot,
708            DisplayPoint,
709            SelectionGoal,
710        ) -> (DisplayPoint, SelectionGoal),
711    ) {
712        self.move_with(|map, selection| {
713            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
714            selection.collapse_to(cursor, new_goal)
715        });
716    }
717
718    pub fn maybe_move_cursors_with(
719        &mut self,
720        mut update_cursor_position: impl FnMut(
721            &DisplaySnapshot,
722            DisplayPoint,
723            SelectionGoal,
724        ) -> Option<(DisplayPoint, SelectionGoal)>,
725    ) {
726        self.move_cursors_with(|map, point, goal| {
727            update_cursor_position(map, point, goal).unwrap_or((point, goal))
728        })
729    }
730
731    pub fn replace_cursors_with(
732        &mut self,
733        mut find_replacement_cursors: impl FnMut(&DisplaySnapshot) -> Vec<DisplayPoint>,
734    ) {
735        let display_map = self.display_map();
736        let new_selections = find_replacement_cursors(&display_map)
737            .into_iter()
738            .map(|cursor| {
739                let cursor_point = cursor.to_point(&display_map);
740                Selection {
741                    id: post_inc(&mut self.collection.next_selection_id),
742                    start: cursor_point,
743                    end: cursor_point,
744                    reversed: false,
745                    goal: SelectionGoal::None,
746                }
747            })
748            .collect();
749        self.select(new_selections);
750    }
751
752    /// Compute new ranges for any selections that were located in excerpts that have
753    /// since been removed.
754    ///
755    /// Returns a `HashMap` indicating which selections whose former head position
756    /// was no longer present. The keys of the map are selection ids. The values are
757    /// the id of the new excerpt where the head of the selection has been moved.
758    pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
759        let mut pending = self.collection.pending.take();
760        let mut selections_with_lost_position = HashMap::default();
761
762        let anchors_with_status = {
763            let buffer = self.buffer();
764            let disjoint_anchors = self
765                .disjoint
766                .iter()
767                .flat_map(|selection| [&selection.start, &selection.end]);
768            buffer.refresh_anchors(disjoint_anchors)
769        };
770        let adjusted_disjoint: Vec<_> = anchors_with_status
771            .chunks(2)
772            .map(|selection_anchors| {
773                let (anchor_ix, start, kept_start) = selection_anchors[0].clone();
774                let (_, end, kept_end) = selection_anchors[1].clone();
775                let selection = &self.disjoint[anchor_ix / 2];
776                let kept_head = if selection.reversed {
777                    kept_start
778                } else {
779                    kept_end
780                };
781                if !kept_head {
782                    selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
783                }
784
785                Selection {
786                    id: selection.id,
787                    start,
788                    end,
789                    reversed: selection.reversed,
790                    goal: selection.goal,
791                }
792            })
793            .collect();
794
795        if !adjusted_disjoint.is_empty() {
796            let resolved_selections =
797                resolve_multiple(adjusted_disjoint.iter(), &self.buffer()).collect();
798            self.select::<usize>(resolved_selections);
799        }
800
801        if let Some(pending) = pending.as_mut() {
802            let buffer = self.buffer();
803            let anchors =
804                buffer.refresh_anchors([&pending.selection.start, &pending.selection.end]);
805            let (_, start, kept_start) = anchors[0].clone();
806            let (_, end, kept_end) = anchors[1].clone();
807            let kept_head = if pending.selection.reversed {
808                kept_start
809            } else {
810                kept_end
811            };
812            if !kept_head {
813                selections_with_lost_position
814                    .insert(pending.selection.id, pending.selection.head().excerpt_id);
815            }
816
817            pending.selection.start = start;
818            pending.selection.end = end;
819        }
820        self.collection.pending = pending;
821        self.selections_changed = true;
822
823        selections_with_lost_position
824    }
825}
826
827impl<'a> Deref for MutableSelectionsCollection<'a> {
828    type Target = SelectionsCollection;
829    fn deref(&self) -> &Self::Target {
830        self.collection
831    }
832}
833
834// Panics if passed selections are not in order
835pub fn resolve_multiple<'a, D, I>(
836    selections: I,
837    snapshot: &MultiBufferSnapshot,
838) -> impl 'a + Iterator<Item = Selection<D>>
839where
840    D: TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
841    I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
842{
843    let (to_summarize, selections) = selections.into_iter().tee();
844    let mut summaries = snapshot
845        .summaries_for_anchors::<D, _>(
846            to_summarize
847                .flat_map(|s| [&s.start, &s.end])
848                .collect::<Vec<_>>(),
849        )
850        .into_iter();
851    selections.map(move |s| Selection {
852        id: s.id,
853        start: summaries.next().unwrap(),
854        end: summaries.next().unwrap(),
855        reversed: s.reversed,
856        goal: s.goal,
857    })
858}
859
860fn resolve<D: TextDimension + Ord + Sub<D, Output = D>>(
861    selection: &Selection<Anchor>,
862    buffer: &MultiBufferSnapshot,
863) -> Selection<D> {
864    selection.map(|p| p.summary::<D>(buffer))
865}