selections_collection.rs

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