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.pending
260            .as_ref()
261            .map(|pending| pending.selection.clone())
262            .unwrap_or_else(|| self.disjoint.first().cloned().unwrap())
263    }
264
265    pub fn first<D: TextDimension + Ord + Sub<D, Output = D>>(
266        &self,
267        cx: &AppContext,
268    ) -> Selection<D> {
269        self.all(cx).first().unwrap().clone()
270    }
271
272    pub fn last<D: TextDimension + Ord + Sub<D, Output = D>>(
273        &self,
274        cx: &AppContext,
275    ) -> Selection<D> {
276        self.all(cx).last().unwrap().clone()
277    }
278
279    pub fn disjoint_anchor_ranges(&self) -> Vec<Range<Anchor>> {
280        self.disjoint_anchors()
281            .iter()
282            .map(|s| s.start..s.end)
283            .collect()
284    }
285
286    #[cfg(any(test, feature = "test-support"))]
287    pub fn ranges<D: TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug>(
288        &self,
289        cx: &AppContext,
290    ) -> Vec<Range<D>> {
291        self.all::<D>(cx)
292            .iter()
293            .map(|s| {
294                if s.reversed {
295                    s.end.clone()..s.start.clone()
296                } else {
297                    s.start.clone()..s.end.clone()
298                }
299            })
300            .collect()
301    }
302
303    #[cfg(any(test, feature = "test-support"))]
304    pub fn display_ranges(&self, cx: &mut AppContext) -> Vec<Range<DisplayPoint>> {
305        let display_map = self.display_map(cx);
306        self.disjoint_anchors()
307            .iter()
308            .chain(self.pending_anchor().as_ref())
309            .map(|s| {
310                if s.reversed {
311                    s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
312                } else {
313                    s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
314                }
315            })
316            .collect()
317    }
318
319    pub fn build_columnar_selection(
320        &mut self,
321        display_map: &DisplaySnapshot,
322        row: DisplayRow,
323        positions: &Range<Pixels>,
324        reversed: bool,
325        text_layout_details: &TextLayoutDetails,
326    ) -> Option<Selection<Point>> {
327        let is_empty = positions.start == positions.end;
328        let line_len = display_map.line_len(row);
329
330        let line = display_map.layout_row(row, &text_layout_details);
331
332        let start_col = line.closest_index_for_x(positions.start) as u32;
333        if start_col < line_len || (is_empty && positions.start == line.width) {
334            let start = DisplayPoint::new(row, start_col);
335            let end_col = line.closest_index_for_x(positions.end) as u32;
336            let end = DisplayPoint::new(row, end_col);
337
338            Some(Selection {
339                id: post_inc(&mut self.next_selection_id),
340                start: start.to_point(display_map),
341                end: end.to_point(display_map),
342                reversed,
343                goal: SelectionGoal::HorizontalRange {
344                    start: positions.start.into(),
345                    end: positions.end.into(),
346                },
347            })
348        } else {
349            None
350        }
351    }
352
353    pub(crate) fn change_with<R>(
354        &mut self,
355        cx: &mut AppContext,
356        change: impl FnOnce(&mut MutableSelectionsCollection) -> R,
357    ) -> (bool, R) {
358        let mut mutable_collection = MutableSelectionsCollection {
359            collection: self,
360            selections_changed: false,
361            cx,
362        };
363
364        let result = change(&mut mutable_collection);
365        assert!(
366            !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
367            "There must be at least one selection"
368        );
369        (mutable_collection.selections_changed, result)
370    }
371}
372
373pub struct MutableSelectionsCollection<'a> {
374    collection: &'a mut SelectionsCollection,
375    selections_changed: bool,
376    cx: &'a mut AppContext,
377}
378
379impl<'a> MutableSelectionsCollection<'a> {
380    pub fn display_map(&mut self) -> DisplaySnapshot {
381        self.collection.display_map(self.cx)
382    }
383
384    fn buffer(&self) -> Ref<MultiBufferSnapshot> {
385        self.collection.buffer(self.cx)
386    }
387
388    pub fn clear_disjoint(&mut self) {
389        self.collection.disjoint = Arc::from([]);
390    }
391
392    pub fn delete(&mut self, selection_id: usize) {
393        let mut changed = false;
394        self.collection.disjoint = self
395            .disjoint
396            .iter()
397            .filter(|selection| {
398                let found = selection.id == selection_id;
399                changed |= found;
400                !found
401            })
402            .cloned()
403            .collect();
404
405        self.selections_changed |= changed;
406    }
407
408    pub fn clear_pending(&mut self) {
409        if self.collection.pending.is_some() {
410            self.collection.pending = None;
411            self.selections_changed = true;
412        }
413    }
414
415    pub(crate) fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
416        self.collection.pending = Some(PendingSelection {
417            selection: Selection {
418                id: post_inc(&mut self.collection.next_selection_id),
419                start: range.start,
420                end: range.end,
421                reversed: false,
422                goal: SelectionGoal::None,
423            },
424            mode,
425        });
426        self.selections_changed = true;
427    }
428
429    pub(crate) fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
430        self.collection.pending = Some(PendingSelection { selection, mode });
431        self.selections_changed = true;
432    }
433
434    pub fn try_cancel(&mut self) -> bool {
435        if let Some(pending) = self.collection.pending.take() {
436            if self.disjoint.is_empty() {
437                self.collection.disjoint = Arc::from([pending.selection]);
438            }
439            self.selections_changed = true;
440            return true;
441        }
442
443        let mut oldest = self.oldest_anchor().clone();
444        if self.count() > 1 {
445            self.collection.disjoint = Arc::from([oldest]);
446            self.selections_changed = true;
447            return true;
448        }
449
450        if !oldest.start.cmp(&oldest.end, &self.buffer()).is_eq() {
451            let head = oldest.head();
452            oldest.start = head;
453            oldest.end = head;
454            self.collection.disjoint = Arc::from([oldest]);
455            self.selections_changed = true;
456            return true;
457        }
458
459        false
460    }
461
462    pub fn insert_range<T>(&mut self, range: Range<T>)
463    where
464        T: 'a + ToOffset + ToPoint + TextDimension + Ord + Sub<T, Output = T> + std::marker::Copy,
465    {
466        let mut selections = self.all(self.cx);
467        let mut start = range.start.to_offset(&self.buffer());
468        let mut end = range.end.to_offset(&self.buffer());
469        let reversed = if start > end {
470            mem::swap(&mut start, &mut end);
471            true
472        } else {
473            false
474        };
475        selections.push(Selection {
476            id: post_inc(&mut self.collection.next_selection_id),
477            start,
478            end,
479            reversed,
480            goal: SelectionGoal::None,
481        });
482        self.select(selections);
483    }
484
485    pub fn select<T>(&mut self, mut selections: Vec<Selection<T>>)
486    where
487        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
488    {
489        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
490        selections.sort_unstable_by_key(|s| s.start);
491        // Merge overlapping selections.
492        let mut i = 1;
493        while i < selections.len() {
494            if selections[i - 1].end >= selections[i].start {
495                let removed = selections.remove(i);
496                if removed.start < selections[i - 1].start {
497                    selections[i - 1].start = removed.start;
498                }
499                if removed.end > selections[i - 1].end {
500                    selections[i - 1].end = removed.end;
501                }
502            } else {
503                i += 1;
504            }
505        }
506
507        self.collection.disjoint = Arc::from_iter(selections.into_iter().map(|selection| {
508            let end_bias = if selection.end > selection.start {
509                Bias::Left
510            } else {
511                Bias::Right
512            };
513            Selection {
514                id: selection.id,
515                start: buffer.anchor_after(selection.start),
516                end: buffer.anchor_at(selection.end, end_bias),
517                reversed: selection.reversed,
518                goal: selection.goal,
519            }
520        }));
521
522        self.collection.pending = None;
523        self.selections_changed = true;
524    }
525
526    pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
527        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
528        let resolved_selections =
529            resolve_multiple::<usize, _>(&selections, &buffer).collect::<Vec<_>>();
530        self.select(resolved_selections);
531    }
532
533    pub fn select_ranges<I, T>(&mut self, ranges: I)
534    where
535        I: IntoIterator<Item = Range<T>>,
536        T: ToOffset,
537    {
538        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
539        let ranges = ranges
540            .into_iter()
541            .map(|range| range.start.to_offset(&buffer)..range.end.to_offset(&buffer));
542        self.select_offset_ranges(ranges);
543    }
544
545    fn select_offset_ranges<I>(&mut self, ranges: I)
546    where
547        I: IntoIterator<Item = Range<usize>>,
548    {
549        let selections = ranges
550            .into_iter()
551            .map(|range| {
552                let mut start = range.start;
553                let mut end = range.end;
554                let reversed = if start > end {
555                    mem::swap(&mut start, &mut end);
556                    true
557                } else {
558                    false
559                };
560                Selection {
561                    id: post_inc(&mut self.collection.next_selection_id),
562                    start,
563                    end,
564                    reversed,
565                    goal: SelectionGoal::None,
566                }
567            })
568            .collect::<Vec<_>>();
569
570        self.select(selections)
571    }
572
573    pub fn select_anchor_ranges<I>(&mut self, ranges: I)
574    where
575        I: IntoIterator<Item = Range<Anchor>>,
576    {
577        let buffer = self.buffer.read(self.cx).snapshot(self.cx);
578        let selections = ranges
579            .into_iter()
580            .map(|range| {
581                let mut start = range.start;
582                let mut end = range.end;
583                let reversed = if start.cmp(&end, &buffer).is_gt() {
584                    mem::swap(&mut start, &mut end);
585                    true
586                } else {
587                    false
588                };
589                Selection {
590                    id: post_inc(&mut self.collection.next_selection_id),
591                    start,
592                    end,
593                    reversed,
594                    goal: SelectionGoal::None,
595                }
596            })
597            .collect::<Vec<_>>();
598        self.select_anchors(selections)
599    }
600
601    pub fn new_selection_id(&mut self) -> usize {
602        post_inc(&mut self.next_selection_id)
603    }
604
605    pub fn select_display_ranges<T>(&mut self, ranges: T)
606    where
607        T: IntoIterator<Item = Range<DisplayPoint>>,
608    {
609        let display_map = self.display_map();
610        let selections = ranges
611            .into_iter()
612            .map(|range| {
613                let mut start = range.start;
614                let mut end = range.end;
615                let reversed = if start > end {
616                    mem::swap(&mut start, &mut end);
617                    true
618                } else {
619                    false
620                };
621                Selection {
622                    id: post_inc(&mut self.collection.next_selection_id),
623                    start: start.to_point(&display_map),
624                    end: end.to_point(&display_map),
625                    reversed,
626                    goal: SelectionGoal::None,
627                }
628            })
629            .collect();
630        self.select(selections);
631    }
632
633    pub fn move_with(
634        &mut self,
635        mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
636    ) {
637        let mut changed = false;
638        let display_map = self.display_map();
639        let selections = self
640            .all::<Point>(self.cx)
641            .into_iter()
642            .map(|selection| {
643                let mut moved_selection =
644                    selection.map(|point| point.to_display_point(&display_map));
645                move_selection(&display_map, &mut moved_selection);
646                let moved_selection =
647                    moved_selection.map(|display_point| display_point.to_point(&display_map));
648                if selection != moved_selection {
649                    changed = true;
650                }
651                moved_selection
652            })
653            .collect();
654
655        if changed {
656            self.select(selections)
657        }
658    }
659
660    pub fn move_offsets_with(
661        &mut self,
662        mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<usize>),
663    ) {
664        let mut changed = false;
665        let snapshot = self.buffer().clone();
666        let selections = self
667            .all::<usize>(self.cx)
668            .into_iter()
669            .map(|selection| {
670                let mut moved_selection = selection.clone();
671                move_selection(&snapshot, &mut moved_selection);
672                if selection != moved_selection {
673                    changed = true;
674                }
675                moved_selection
676            })
677            .collect();
678        drop(snapshot);
679
680        if changed {
681            self.select(selections)
682        }
683    }
684
685    pub fn move_heads_with(
686        &mut self,
687        mut update_head: impl FnMut(
688            &DisplaySnapshot,
689            DisplayPoint,
690            SelectionGoal,
691        ) -> (DisplayPoint, SelectionGoal),
692    ) {
693        self.move_with(|map, selection| {
694            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
695            selection.set_head(new_head, new_goal);
696        });
697    }
698
699    pub fn move_cursors_with(
700        &mut self,
701        mut update_cursor_position: impl FnMut(
702            &DisplaySnapshot,
703            DisplayPoint,
704            SelectionGoal,
705        ) -> (DisplayPoint, SelectionGoal),
706    ) {
707        self.move_with(|map, selection| {
708            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
709            selection.collapse_to(cursor, new_goal)
710        });
711    }
712
713    pub fn maybe_move_cursors_with(
714        &mut self,
715        mut update_cursor_position: impl FnMut(
716            &DisplaySnapshot,
717            DisplayPoint,
718            SelectionGoal,
719        ) -> Option<(DisplayPoint, SelectionGoal)>,
720    ) {
721        self.move_cursors_with(|map, point, goal| {
722            update_cursor_position(map, point, goal).unwrap_or((point, goal))
723        })
724    }
725
726    pub fn replace_cursors_with(
727        &mut self,
728        mut find_replacement_cursors: impl FnMut(&DisplaySnapshot) -> Vec<DisplayPoint>,
729    ) {
730        let display_map = self.display_map();
731        let new_selections = find_replacement_cursors(&display_map)
732            .into_iter()
733            .map(|cursor| {
734                let cursor_point = cursor.to_point(&display_map);
735                Selection {
736                    id: post_inc(&mut self.collection.next_selection_id),
737                    start: cursor_point,
738                    end: cursor_point,
739                    reversed: false,
740                    goal: SelectionGoal::None,
741                }
742            })
743            .collect();
744        self.select(new_selections);
745    }
746
747    /// Compute new ranges for any selections that were located in excerpts that have
748    /// since been removed.
749    ///
750    /// Returns a `HashMap` indicating which selections whose former head position
751    /// was no longer present. The keys of the map are selection ids. The values are
752    /// the id of the new excerpt where the head of the selection has been moved.
753    pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
754        let mut pending = self.collection.pending.take();
755        let mut selections_with_lost_position = HashMap::default();
756
757        let anchors_with_status = {
758            let buffer = self.buffer();
759            let disjoint_anchors = self
760                .disjoint
761                .iter()
762                .flat_map(|selection| [&selection.start, &selection.end]);
763            buffer.refresh_anchors(disjoint_anchors)
764        };
765        let adjusted_disjoint: Vec<_> = anchors_with_status
766            .chunks(2)
767            .map(|selection_anchors| {
768                let (anchor_ix, start, kept_start) = selection_anchors[0];
769                let (_, end, kept_end) = selection_anchors[1];
770                let selection = &self.disjoint[anchor_ix / 2];
771                let kept_head = if selection.reversed {
772                    kept_start
773                } else {
774                    kept_end
775                };
776                if !kept_head {
777                    selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
778                }
779
780                Selection {
781                    id: selection.id,
782                    start,
783                    end,
784                    reversed: selection.reversed,
785                    goal: selection.goal,
786                }
787            })
788            .collect();
789
790        if !adjusted_disjoint.is_empty() {
791            let resolved_selections =
792                resolve_multiple(adjusted_disjoint.iter(), &self.buffer()).collect();
793            self.select::<usize>(resolved_selections);
794        }
795
796        if let Some(pending) = pending.as_mut() {
797            let buffer = self.buffer();
798            let anchors =
799                buffer.refresh_anchors([&pending.selection.start, &pending.selection.end]);
800            let (_, start, kept_start) = anchors[0];
801            let (_, end, kept_end) = anchors[1];
802            let kept_head = if pending.selection.reversed {
803                kept_start
804            } else {
805                kept_end
806            };
807            if !kept_head {
808                selections_with_lost_position
809                    .insert(pending.selection.id, pending.selection.head().excerpt_id);
810            }
811
812            pending.selection.start = start;
813            pending.selection.end = end;
814        }
815        self.collection.pending = pending;
816        self.selections_changed = true;
817
818        selections_with_lost_position
819    }
820}
821
822impl<'a> Deref for MutableSelectionsCollection<'a> {
823    type Target = SelectionsCollection;
824    fn deref(&self) -> &Self::Target {
825        self.collection
826    }
827}
828
829impl<'a> DerefMut for MutableSelectionsCollection<'a> {
830    fn deref_mut(&mut self) -> &mut Self::Target {
831        self.collection
832    }
833}
834
835// Panics if passed selections are not in order
836pub(crate) fn resolve_multiple<'a, D, I>(
837    selections: I,
838    snapshot: &MultiBufferSnapshot,
839) -> impl 'a + Iterator<Item = Selection<D>>
840where
841    D: TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
842    I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
843{
844    let (to_summarize, selections) = selections.into_iter().tee();
845    let mut summaries = snapshot
846        .summaries_for_anchors::<D, _>(
847            to_summarize
848                .flat_map(|s| [&s.start, &s.end])
849                .collect::<Vec<_>>(),
850        )
851        .into_iter();
852    selections.map(move |s| Selection {
853        id: s.id,
854        start: summaries.next().unwrap(),
855        end: summaries.next().unwrap(),
856        reversed: s.reversed,
857        goal: s.goal,
858    })
859}
860
861fn resolve<D: TextDimension + Ord + Sub<D, Output = D>>(
862    selection: &Selection<Anchor>,
863    buffer: &MultiBufferSnapshot,
864) -> Selection<D> {
865    selection.map(|p| p.summary::<D>(buffer))
866}