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.closest_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.closest_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        if cfg!(debug_assertions) {
 419            mutable_collection.disjoint.iter().for_each(|selection| {
 420                assert!(
 421                    snapshot.can_resolve(&selection.start),
 422                    "disjoint selection start is not resolvable for the given snapshot:\n{selection:?}",
 423                );
 424                assert!(
 425                    snapshot.can_resolve(&selection.end),
 426                    "disjoint selection end is not resolvable for the given snapshot: {selection:?}",
 427                );
 428            });
 429            if let Some(pending) = &mutable_collection.pending {
 430                let selection = &pending.selection;
 431                assert!(
 432                    snapshot.can_resolve(&selection.start),
 433                    "pending selection start is not resolvable for the given snapshot: {pending:?}",
 434                );
 435                assert!(
 436                    snapshot.can_resolve(&selection.end),
 437                    "pending selection end is not resolvable for the given snapshot: {pending:?}",
 438                );
 439            }
 440        }
 441        (mutable_collection.selections_changed, result)
 442    }
 443
 444    pub fn next_selection_id(&self) -> usize {
 445        self.next_selection_id
 446    }
 447
 448    pub fn line_mode(&self) -> bool {
 449        self.line_mode
 450    }
 451
 452    pub fn set_line_mode(&mut self, line_mode: bool) {
 453        self.line_mode = line_mode;
 454    }
 455
 456    pub fn select_mode(&self) -> &SelectMode {
 457        &self.select_mode
 458    }
 459
 460    pub fn set_select_mode(&mut self, select_mode: SelectMode) {
 461        self.select_mode = select_mode;
 462    }
 463
 464    pub fn is_extending(&self) -> bool {
 465        self.is_extending
 466    }
 467
 468    pub fn set_is_extending(&mut self, is_extending: bool) {
 469        self.is_extending = is_extending;
 470    }
 471}
 472
 473pub struct MutableSelectionsCollection<'snap, 'a> {
 474    collection: &'a mut SelectionsCollection,
 475    snapshot: &'snap DisplaySnapshot,
 476    selections_changed: bool,
 477}
 478
 479impl<'snap, 'a> fmt::Debug for MutableSelectionsCollection<'snap, 'a> {
 480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 481        f.debug_struct("MutableSelectionsCollection")
 482            .field("collection", &self.collection)
 483            .field("selections_changed", &self.selections_changed)
 484            .finish()
 485    }
 486}
 487
 488impl<'snap, 'a> MutableSelectionsCollection<'snap, 'a> {
 489    pub fn display_snapshot(&self) -> DisplaySnapshot {
 490        self.snapshot.clone()
 491    }
 492
 493    pub fn clear_disjoint(&mut self) {
 494        self.collection.disjoint = Arc::default();
 495    }
 496
 497    pub fn delete(&mut self, selection_id: usize) {
 498        let mut changed = false;
 499        self.collection.disjoint = self
 500            .disjoint
 501            .iter()
 502            .filter(|selection| {
 503                let found = selection.id == selection_id;
 504                changed |= found;
 505                !found
 506            })
 507            .cloned()
 508            .collect();
 509
 510        self.selections_changed |= changed;
 511    }
 512
 513    pub fn remove_selections_from_buffer(&mut self, buffer_id: language::BufferId) {
 514        let mut changed = false;
 515
 516        let filtered_selections: Arc<[Selection<Anchor>]> = {
 517            self.disjoint
 518                .iter()
 519                .filter(|selection| {
 520                    if let Some(selection_buffer_id) =
 521                        self.snapshot.buffer_id_for_anchor(selection.start)
 522                    {
 523                        let should_remove = selection_buffer_id == buffer_id;
 524                        changed |= should_remove;
 525                        !should_remove
 526                    } else {
 527                        true
 528                    }
 529                })
 530                .cloned()
 531                .collect()
 532        };
 533
 534        if filtered_selections.is_empty() {
 535            let default_anchor = self.snapshot.anchor_before(0);
 536            self.collection.disjoint = Arc::from([Selection {
 537                id: post_inc(&mut self.collection.next_selection_id),
 538                start: default_anchor,
 539                end: default_anchor,
 540                reversed: false,
 541                goal: SelectionGoal::None,
 542            }]);
 543        } else {
 544            self.collection.disjoint = filtered_selections;
 545        }
 546
 547        self.selections_changed |= changed;
 548    }
 549
 550    pub fn clear_pending(&mut self) {
 551        if self.collection.pending.is_some() {
 552            self.collection.pending = None;
 553            self.selections_changed = true;
 554        }
 555    }
 556
 557    pub(crate) fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
 558        self.collection.pending = Some(PendingSelection {
 559            selection: {
 560                let mut start = range.start;
 561                let mut end = range.end;
 562                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 563                    mem::swap(&mut start, &mut end);
 564                    true
 565                } else {
 566                    false
 567                };
 568                Selection {
 569                    id: post_inc(&mut self.collection.next_selection_id),
 570                    start,
 571                    end,
 572                    reversed,
 573                    goal: SelectionGoal::None,
 574                }
 575            },
 576            mode,
 577        });
 578        self.selections_changed = true;
 579    }
 580
 581    pub(crate) fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
 582        self.collection.pending = Some(PendingSelection { selection, mode });
 583        self.selections_changed = true;
 584    }
 585
 586    pub fn try_cancel(&mut self) -> bool {
 587        if let Some(pending) = self.collection.pending.take() {
 588            if self.disjoint.is_empty() {
 589                self.collection.disjoint = Arc::from([pending.selection]);
 590            }
 591            self.selections_changed = true;
 592            return true;
 593        }
 594
 595        let mut oldest = self.oldest_anchor().clone();
 596        if self.count() > 1 {
 597            self.collection.disjoint = Arc::from([oldest]);
 598            self.selections_changed = true;
 599            return true;
 600        }
 601
 602        if !oldest.start.cmp(&oldest.end, self.snapshot).is_eq() {
 603            let head = oldest.head();
 604            oldest.start = head;
 605            oldest.end = head;
 606            self.collection.disjoint = Arc::from([oldest]);
 607            self.selections_changed = true;
 608            return true;
 609        }
 610
 611        false
 612    }
 613
 614    pub fn insert_range<T>(&mut self, range: Range<T>)
 615    where
 616        T: 'a + ToOffset + ToPoint + TextDimension + Ord + Sub<T, Output = T> + std::marker::Copy,
 617    {
 618        let display_map = self.display_snapshot();
 619        let mut selections = self.collection.all(&display_map);
 620        let mut start = range.start.to_offset(self.snapshot);
 621        let mut end = range.end.to_offset(self.snapshot);
 622        let reversed = if start > end {
 623            mem::swap(&mut start, &mut end);
 624            true
 625        } else {
 626            false
 627        };
 628        selections.push(Selection {
 629            id: post_inc(&mut self.collection.next_selection_id),
 630            start,
 631            end,
 632            reversed,
 633            goal: SelectionGoal::None,
 634        });
 635        self.select(selections);
 636    }
 637
 638    pub fn select<T>(&mut self, selections: Vec<Selection<T>>)
 639    where
 640        T: ToOffset + std::marker::Copy + std::fmt::Debug,
 641    {
 642        let mut selections = selections
 643            .into_iter()
 644            .map(|selection| selection.map(|it| it.to_offset(self.snapshot)))
 645            .map(|mut selection| {
 646                if selection.start > selection.end {
 647                    mem::swap(&mut selection.start, &mut selection.end);
 648                    selection.reversed = true
 649                }
 650                selection
 651            })
 652            .collect::<Vec<_>>();
 653        selections.sort_unstable_by_key(|s| s.start);
 654        // Merge overlapping selections.
 655        let mut i = 1;
 656        while i < selections.len() {
 657            if selections[i].start <= selections[i - 1].end {
 658                let removed = selections.remove(i);
 659                if removed.start < selections[i - 1].start {
 660                    selections[i - 1].start = removed.start;
 661                }
 662                if selections[i - 1].end < removed.end {
 663                    selections[i - 1].end = removed.end;
 664                }
 665            } else {
 666                i += 1;
 667            }
 668        }
 669
 670        self.collection.disjoint = Arc::from_iter(
 671            selections
 672                .into_iter()
 673                .map(|selection| selection_to_anchor_selection(selection, self.snapshot)),
 674        );
 675        self.collection.pending = None;
 676        self.selections_changed = true;
 677    }
 678
 679    pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
 680        let map = self.display_snapshot();
 681        let resolved_selections =
 682            resolve_selections_wrapping_blocks::<usize, _>(&selections, &map).collect::<Vec<_>>();
 683        self.select(resolved_selections);
 684    }
 685
 686    pub fn select_ranges<I, T>(&mut self, ranges: I)
 687    where
 688        I: IntoIterator<Item = Range<T>>,
 689        T: ToOffset,
 690    {
 691        let ranges = ranges
 692            .into_iter()
 693            .map(|range| range.start.to_offset(self.snapshot)..range.end.to_offset(self.snapshot));
 694        self.select_offset_ranges(ranges);
 695    }
 696
 697    fn select_offset_ranges<I>(&mut self, ranges: I)
 698    where
 699        I: IntoIterator<Item = Range<usize>>,
 700    {
 701        let selections = ranges
 702            .into_iter()
 703            .map(|range| {
 704                let mut start = range.start;
 705                let mut end = range.end;
 706                let reversed = if start > end {
 707                    mem::swap(&mut start, &mut end);
 708                    true
 709                } else {
 710                    false
 711                };
 712                Selection {
 713                    id: post_inc(&mut self.collection.next_selection_id),
 714                    start,
 715                    end,
 716                    reversed,
 717                    goal: SelectionGoal::None,
 718                }
 719            })
 720            .collect::<Vec<_>>();
 721
 722        self.select(selections)
 723    }
 724
 725    pub fn select_anchor_ranges<I>(&mut self, ranges: I)
 726    where
 727        I: IntoIterator<Item = Range<Anchor>>,
 728    {
 729        let selections = ranges
 730            .into_iter()
 731            .map(|range| {
 732                let mut start = range.start;
 733                let mut end = range.end;
 734                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 735                    mem::swap(&mut start, &mut end);
 736                    true
 737                } else {
 738                    false
 739                };
 740                Selection {
 741                    id: post_inc(&mut self.collection.next_selection_id),
 742                    start,
 743                    end,
 744                    reversed,
 745                    goal: SelectionGoal::None,
 746                }
 747            })
 748            .collect::<Vec<_>>();
 749        self.select_anchors(selections)
 750    }
 751
 752    pub fn new_selection_id(&mut self) -> usize {
 753        post_inc(&mut self.next_selection_id)
 754    }
 755
 756    pub fn select_display_ranges<T>(&mut self, ranges: T)
 757    where
 758        T: IntoIterator<Item = Range<DisplayPoint>>,
 759    {
 760        let selections = ranges
 761            .into_iter()
 762            .map(|range| {
 763                let mut start = range.start;
 764                let mut end = range.end;
 765                let reversed = if start > end {
 766                    mem::swap(&mut start, &mut end);
 767                    true
 768                } else {
 769                    false
 770                };
 771                Selection {
 772                    id: post_inc(&mut self.collection.next_selection_id),
 773                    start: start.to_point(self.snapshot),
 774                    end: end.to_point(self.snapshot),
 775                    reversed,
 776                    goal: SelectionGoal::None,
 777                }
 778            })
 779            .collect();
 780        self.select(selections);
 781    }
 782
 783    pub fn reverse_selections(&mut self) {
 784        let mut new_selections: Vec<Selection<Point>> = Vec::new();
 785        let disjoint = self.disjoint.clone();
 786        for selection in disjoint
 787            .iter()
 788            .sorted_by(|first, second| Ord::cmp(&second.id, &first.id))
 789            .collect::<Vec<&Selection<Anchor>>>()
 790        {
 791            new_selections.push(Selection {
 792                id: self.new_selection_id(),
 793                start: selection
 794                    .start
 795                    .to_display_point(self.snapshot)
 796                    .to_point(self.snapshot),
 797                end: selection
 798                    .end
 799                    .to_display_point(self.snapshot)
 800                    .to_point(self.snapshot),
 801                reversed: selection.reversed,
 802                goal: selection.goal,
 803            });
 804        }
 805        self.select(new_selections);
 806    }
 807
 808    pub fn move_with(
 809        &mut self,
 810        mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
 811    ) {
 812        let mut changed = false;
 813        let display_map = self.display_snapshot();
 814        let selections = self.collection.all_display(&display_map);
 815        let selections = selections
 816            .into_iter()
 817            .map(|selection| {
 818                let mut moved_selection = selection.clone();
 819                move_selection(&display_map, &mut moved_selection);
 820                if selection != moved_selection {
 821                    changed = true;
 822                }
 823                moved_selection.map(|display_point| display_point.to_point(&display_map))
 824            })
 825            .collect();
 826
 827        if changed {
 828            self.select(selections)
 829        }
 830    }
 831
 832    pub fn move_offsets_with(
 833        &mut self,
 834        mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<usize>),
 835    ) {
 836        let mut changed = false;
 837        let display_map = self.display_snapshot();
 838        let selections = self
 839            .collection
 840            .all::<usize>(&display_map)
 841            .into_iter()
 842            .map(|selection| {
 843                let mut moved_selection = selection.clone();
 844                move_selection(self.snapshot, &mut moved_selection);
 845                if selection != moved_selection {
 846                    changed = true;
 847                }
 848                moved_selection
 849            })
 850            .collect();
 851
 852        if changed {
 853            self.select(selections)
 854        }
 855    }
 856
 857    pub fn move_heads_with(
 858        &mut self,
 859        mut update_head: impl FnMut(
 860            &DisplaySnapshot,
 861            DisplayPoint,
 862            SelectionGoal,
 863        ) -> (DisplayPoint, SelectionGoal),
 864    ) {
 865        self.move_with(|map, selection| {
 866            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
 867            selection.set_head(new_head, new_goal);
 868        });
 869    }
 870
 871    pub fn move_cursors_with(
 872        &mut self,
 873        mut update_cursor_position: impl FnMut(
 874            &DisplaySnapshot,
 875            DisplayPoint,
 876            SelectionGoal,
 877        ) -> (DisplayPoint, SelectionGoal),
 878    ) {
 879        self.move_with(|map, selection| {
 880            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
 881            selection.collapse_to(cursor, new_goal)
 882        });
 883    }
 884
 885    pub fn maybe_move_cursors_with(
 886        &mut self,
 887        mut update_cursor_position: impl FnMut(
 888            &DisplaySnapshot,
 889            DisplayPoint,
 890            SelectionGoal,
 891        ) -> Option<(DisplayPoint, SelectionGoal)>,
 892    ) {
 893        self.move_cursors_with(|map, point, goal| {
 894            update_cursor_position(map, point, goal).unwrap_or((point, goal))
 895        })
 896    }
 897
 898    pub fn replace_cursors_with(
 899        &mut self,
 900        find_replacement_cursors: impl FnOnce(&DisplaySnapshot) -> Vec<DisplayPoint>,
 901    ) {
 902        let new_selections = find_replacement_cursors(self.snapshot)
 903            .into_iter()
 904            .map(|cursor| {
 905                let cursor_point = cursor.to_point(self.snapshot);
 906                Selection {
 907                    id: post_inc(&mut self.collection.next_selection_id),
 908                    start: cursor_point,
 909                    end: cursor_point,
 910                    reversed: false,
 911                    goal: SelectionGoal::None,
 912                }
 913            })
 914            .collect();
 915        self.select(new_selections);
 916    }
 917
 918    /// Compute new ranges for any selections that were located in excerpts that have
 919    /// since been removed.
 920    ///
 921    /// Returns a `HashMap` indicating which selections whose former head position
 922    /// was no longer present. The keys of the map are selection ids. The values are
 923    /// the id of the new excerpt where the head of the selection has been moved.
 924    pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
 925        let mut pending = self.collection.pending.take();
 926        let mut selections_with_lost_position = HashMap::default();
 927
 928        let anchors_with_status = {
 929            let disjoint_anchors = self
 930                .disjoint
 931                .iter()
 932                .flat_map(|selection| [&selection.start, &selection.end]);
 933            self.snapshot.refresh_anchors(disjoint_anchors)
 934        };
 935        let adjusted_disjoint: Vec<_> = anchors_with_status
 936            .chunks(2)
 937            .map(|selection_anchors| {
 938                let (anchor_ix, start, kept_start) = selection_anchors[0];
 939                let (_, end, kept_end) = selection_anchors[1];
 940                let selection = &self.disjoint[anchor_ix / 2];
 941                let kept_head = if selection.reversed {
 942                    kept_start
 943                } else {
 944                    kept_end
 945                };
 946                if !kept_head {
 947                    selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
 948                }
 949
 950                Selection {
 951                    id: selection.id,
 952                    start,
 953                    end,
 954                    reversed: selection.reversed,
 955                    goal: selection.goal,
 956                }
 957            })
 958            .collect();
 959
 960        if !adjusted_disjoint.is_empty() {
 961            let map = self.display_snapshot();
 962            let resolved_selections =
 963                resolve_selections_wrapping_blocks(adjusted_disjoint.iter(), &map).collect();
 964            self.select::<usize>(resolved_selections);
 965        }
 966
 967        if let Some(pending) = pending.as_mut() {
 968            let anchors = self
 969                .snapshot
 970                .refresh_anchors([&pending.selection.start, &pending.selection.end]);
 971            let (_, start, kept_start) = anchors[0];
 972            let (_, end, kept_end) = anchors[1];
 973            let kept_head = if pending.selection.reversed {
 974                kept_start
 975            } else {
 976                kept_end
 977            };
 978            if !kept_head {
 979                selections_with_lost_position
 980                    .insert(pending.selection.id, pending.selection.head().excerpt_id);
 981            }
 982
 983            pending.selection.start = start;
 984            pending.selection.end = end;
 985        }
 986        self.collection.pending = pending;
 987        self.selections_changed = true;
 988
 989        selections_with_lost_position
 990    }
 991}
 992
 993impl Deref for MutableSelectionsCollection<'_, '_> {
 994    type Target = SelectionsCollection;
 995    fn deref(&self) -> &Self::Target {
 996        self.collection
 997    }
 998}
 999
1000impl DerefMut for MutableSelectionsCollection<'_, '_> {
1001    fn deref_mut(&mut self) -> &mut Self::Target {
1002        self.collection
1003    }
1004}
1005
1006fn selection_to_anchor_selection(
1007    selection: Selection<usize>,
1008    buffer: &MultiBufferSnapshot,
1009) -> Selection<Anchor> {
1010    let end_bias = if selection.start == selection.end {
1011        Bias::Right
1012    } else {
1013        Bias::Left
1014    };
1015    Selection {
1016        id: selection.id,
1017        start: buffer.anchor_after(selection.start),
1018        end: buffer.anchor_at(selection.end, end_bias),
1019        reversed: selection.reversed,
1020        goal: selection.goal,
1021    }
1022}
1023
1024fn resolve_selections_point<'a>(
1025    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1026    map: &'a DisplaySnapshot,
1027) -> impl 'a + Iterator<Item = Selection<Point>> {
1028    let (to_summarize, selections) = selections.into_iter().tee();
1029    let mut summaries = map
1030        .buffer_snapshot()
1031        .summaries_for_anchors::<Point, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
1032        .into_iter();
1033    selections.map(move |s| {
1034        let start = summaries.next().unwrap();
1035        let end = summaries.next().unwrap();
1036        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1037        Selection {
1038            id: s.id,
1039            start,
1040            end,
1041            reversed: s.reversed,
1042            goal: s.goal,
1043        }
1044    })
1045}
1046
1047/// Panics if passed selections are not in order
1048/// Resolves the anchors to display positions
1049fn resolve_selections_display<'a>(
1050    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1051    map: &'a DisplaySnapshot,
1052) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
1053    let selections = resolve_selections_point(selections, map).map(move |s| {
1054        let display_start = map.point_to_display_point(s.start, Bias::Left);
1055        let display_end = map.point_to_display_point(
1056            s.end,
1057            if s.start == s.end {
1058                Bias::Right
1059            } else {
1060                Bias::Left
1061            },
1062        );
1063        assert!(
1064            display_start <= display_end,
1065            "display_start: {:?}, display_end: {:?}",
1066            display_start,
1067            display_end
1068        );
1069        Selection {
1070            id: s.id,
1071            start: display_start,
1072            end: display_end,
1073            reversed: s.reversed,
1074            goal: s.goal,
1075        }
1076    });
1077    coalesce_selections(selections)
1078}
1079
1080/// Resolves the passed in anchors to [`TextDimension`]s `D`
1081/// wrapping around blocks inbetween.
1082///
1083/// # Panics
1084///
1085/// Panics if passed selections are not in order
1086pub(crate) fn resolve_selections_wrapping_blocks<'a, D, I>(
1087    selections: I,
1088    map: &'a DisplaySnapshot,
1089) -> impl 'a + Iterator<Item = Selection<D>>
1090where
1091    D: TextDimension + Ord + Sub<D, Output = D>,
1092    I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1093{
1094    // Transforms `Anchor -> DisplayPoint -> Point -> DisplayPoint -> D`
1095    // todo(lw): We should be able to short circuit the `Anchor -> DisplayPoint -> Point` to `Anchor -> Point`
1096    let (to_convert, selections) = resolve_selections_display(selections, map).tee();
1097    let mut converted_endpoints =
1098        map.buffer_snapshot()
1099            .dimensions_from_points::<D>(to_convert.flat_map(|s| {
1100                let start = map.display_point_to_point(s.start, Bias::Left);
1101                let end = map.display_point_to_point(s.end, Bias::Right);
1102                assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1103                [start, end]
1104            }));
1105    selections.map(move |s| {
1106        let start = converted_endpoints.next().unwrap();
1107        let end = converted_endpoints.next().unwrap();
1108        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1109        Selection {
1110            id: s.id,
1111            start,
1112            end,
1113            reversed: s.reversed,
1114            goal: s.goal,
1115        }
1116    })
1117}
1118
1119fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
1120    selections: impl Iterator<Item = Selection<D>>,
1121) -> impl Iterator<Item = Selection<D>> {
1122    let mut selections = selections.peekable();
1123    iter::from_fn(move || {
1124        let mut selection = selections.next()?;
1125        while let Some(next_selection) = selections.peek() {
1126            if selection.end >= next_selection.start {
1127                if selection.reversed == next_selection.reversed {
1128                    selection.end = cmp::max(selection.end, next_selection.end);
1129                    selections.next();
1130                } else {
1131                    selection.end = cmp::max(selection.start, next_selection.start);
1132                    break;
1133                }
1134            } else {
1135                break;
1136            }
1137        }
1138        assert!(
1139            selection.start <= selection.end,
1140            "selection.start: {:?}, selection.end: {:?}, selection.reversed: {:?}",
1141            selection.start,
1142            selection.end,
1143            selection.reversed
1144        );
1145        Some(selection)
1146    })
1147}