selections_collection.rs

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