selections_collection.rs

   1use std::{
   2    cmp, fmt, iter, mem,
   3    ops::{AddAssign, 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};
  11use multi_buffer::{MultiBufferDimension, MultiBufferOffset};
  12use util::post_inc;
  13
  14use crate::{
  15    Anchor, DisplayPoint, DisplayRow, ExcerptId, MultiBufferSnapshot, SelectMode, ToOffset,
  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::<MultiBufferOffset>(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>(&self, snapshot: &DisplaySnapshot) -> Option<Selection<D>>
 117    where
 118        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 119    {
 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<D>(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<D>>
 128    where
 129        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 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<D>(
 208        &self,
 209        range: Range<Anchor>,
 210        snapshot: &DisplaySnapshot,
 211    ) -> Vec<Selection<D>>
 212    where
 213        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord + 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>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 271    where
 272        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 273    {
 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>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 294    where
 295        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 296    {
 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>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 310    where
 311        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 312    {
 313        self.all(snapshot).first().unwrap().clone()
 314    }
 315
 316    pub fn last<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 317    where
 318        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 319    {
 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>(&self, snapshot: &DisplaySnapshot) -> Vec<Range<D>>
 327    where
 328        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 329    {
 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        (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(MultiBufferOffset(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: ToOffset,
 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::<MultiBufferOffset, _>(&selections, &map)
 660                .collect::<Vec<_>>();
 661        self.select(resolved_selections);
 662    }
 663
 664    pub fn select_ranges<I, T>(&mut self, ranges: I)
 665    where
 666        I: IntoIterator<Item = Range<T>>,
 667        T: ToOffset,
 668    {
 669        let ranges = ranges
 670            .into_iter()
 671            .map(|range| range.start.to_offset(self.snapshot)..range.end.to_offset(self.snapshot));
 672        self.select_offset_ranges(ranges);
 673    }
 674
 675    fn select_offset_ranges<I>(&mut self, ranges: I)
 676    where
 677        I: IntoIterator<Item = Range<MultiBufferOffset>>,
 678    {
 679        let selections = ranges
 680            .into_iter()
 681            .map(|range| {
 682                let mut start = range.start;
 683                let mut end = range.end;
 684                let reversed = if start > end {
 685                    mem::swap(&mut start, &mut end);
 686                    true
 687                } else {
 688                    false
 689                };
 690                Selection {
 691                    id: post_inc(&mut self.collection.next_selection_id),
 692                    start,
 693                    end,
 694                    reversed,
 695                    goal: SelectionGoal::None,
 696                }
 697            })
 698            .collect::<Vec<_>>();
 699
 700        self.select(selections)
 701    }
 702
 703    pub fn select_anchor_ranges<I>(&mut self, ranges: I)
 704    where
 705        I: IntoIterator<Item = Range<Anchor>>,
 706    {
 707        let selections = ranges
 708            .into_iter()
 709            .map(|range| {
 710                let mut start = range.start;
 711                let mut end = range.end;
 712                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 713                    mem::swap(&mut start, &mut end);
 714                    true
 715                } else {
 716                    false
 717                };
 718                Selection {
 719                    id: post_inc(&mut self.collection.next_selection_id),
 720                    start,
 721                    end,
 722                    reversed,
 723                    goal: SelectionGoal::None,
 724                }
 725            })
 726            .collect::<Vec<_>>();
 727        self.select_anchors(selections)
 728    }
 729
 730    pub fn new_selection_id(&mut self) -> usize {
 731        post_inc(&mut self.next_selection_id)
 732    }
 733
 734    pub fn select_display_ranges<T>(&mut self, ranges: T)
 735    where
 736        T: IntoIterator<Item = Range<DisplayPoint>>,
 737    {
 738        let selections = ranges
 739            .into_iter()
 740            .map(|range| {
 741                let mut start = range.start;
 742                let mut end = range.end;
 743                let reversed = if start > end {
 744                    mem::swap(&mut start, &mut end);
 745                    true
 746                } else {
 747                    false
 748                };
 749                Selection {
 750                    id: post_inc(&mut self.collection.next_selection_id),
 751                    start: start.to_point(self.snapshot),
 752                    end: end.to_point(self.snapshot),
 753                    reversed,
 754                    goal: SelectionGoal::None,
 755                }
 756            })
 757            .collect();
 758        self.select(selections);
 759    }
 760
 761    pub fn reverse_selections(&mut self) {
 762        let mut new_selections: Vec<Selection<Point>> = Vec::new();
 763        let disjoint = self.disjoint.clone();
 764        for selection in disjoint
 765            .iter()
 766            .sorted_by(|first, second| Ord::cmp(&second.id, &first.id))
 767            .collect::<Vec<&Selection<Anchor>>>()
 768        {
 769            new_selections.push(Selection {
 770                id: self.new_selection_id(),
 771                start: selection
 772                    .start
 773                    .to_display_point(self.snapshot)
 774                    .to_point(self.snapshot),
 775                end: selection
 776                    .end
 777                    .to_display_point(self.snapshot)
 778                    .to_point(self.snapshot),
 779                reversed: selection.reversed,
 780                goal: selection.goal,
 781            });
 782        }
 783        self.select(new_selections);
 784    }
 785
 786    pub fn move_with(
 787        &mut self,
 788        mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
 789    ) {
 790        let mut changed = false;
 791        let display_map = self.display_snapshot();
 792        let selections = self.collection.all_display(&display_map);
 793        let selections = selections
 794            .into_iter()
 795            .map(|selection| {
 796                let mut moved_selection = selection.clone();
 797                move_selection(&display_map, &mut moved_selection);
 798                if selection != moved_selection {
 799                    changed = true;
 800                }
 801                moved_selection.map(|display_point| display_point.to_point(&display_map))
 802            })
 803            .collect();
 804
 805        if changed {
 806            self.select(selections)
 807        }
 808    }
 809
 810    pub fn move_offsets_with(
 811        &mut self,
 812        mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<MultiBufferOffset>),
 813    ) {
 814        let mut changed = false;
 815        let display_map = self.display_snapshot();
 816        let selections = self
 817            .collection
 818            .all::<MultiBufferOffset>(&display_map)
 819            .into_iter()
 820            .map(|selection| {
 821                let mut moved_selection = selection.clone();
 822                move_selection(self.snapshot, &mut moved_selection);
 823                if selection != moved_selection {
 824                    changed = true;
 825                }
 826                moved_selection
 827            })
 828            .collect();
 829
 830        if changed {
 831            self.select(selections)
 832        }
 833    }
 834
 835    pub fn move_heads_with(
 836        &mut self,
 837        mut update_head: impl FnMut(
 838            &DisplaySnapshot,
 839            DisplayPoint,
 840            SelectionGoal,
 841        ) -> (DisplayPoint, SelectionGoal),
 842    ) {
 843        self.move_with(|map, selection| {
 844            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
 845            selection.set_head(new_head, new_goal);
 846        });
 847    }
 848
 849    pub fn move_cursors_with(
 850        &mut self,
 851        mut update_cursor_position: impl FnMut(
 852            &DisplaySnapshot,
 853            DisplayPoint,
 854            SelectionGoal,
 855        ) -> (DisplayPoint, SelectionGoal),
 856    ) {
 857        self.move_with(|map, selection| {
 858            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
 859            selection.collapse_to(cursor, new_goal)
 860        });
 861    }
 862
 863    pub fn maybe_move_cursors_with(
 864        &mut self,
 865        mut update_cursor_position: impl FnMut(
 866            &DisplaySnapshot,
 867            DisplayPoint,
 868            SelectionGoal,
 869        ) -> Option<(DisplayPoint, SelectionGoal)>,
 870    ) {
 871        self.move_cursors_with(|map, point, goal| {
 872            update_cursor_position(map, point, goal).unwrap_or((point, goal))
 873        })
 874    }
 875
 876    pub fn replace_cursors_with(
 877        &mut self,
 878        find_replacement_cursors: impl FnOnce(&DisplaySnapshot) -> Vec<DisplayPoint>,
 879    ) {
 880        let new_selections = find_replacement_cursors(self.snapshot)
 881            .into_iter()
 882            .map(|cursor| {
 883                let cursor_point = cursor.to_point(self.snapshot);
 884                Selection {
 885                    id: post_inc(&mut self.collection.next_selection_id),
 886                    start: cursor_point,
 887                    end: cursor_point,
 888                    reversed: false,
 889                    goal: SelectionGoal::None,
 890                }
 891            })
 892            .collect();
 893        self.select(new_selections);
 894    }
 895
 896    /// Compute new ranges for any selections that were located in excerpts that have
 897    /// since been removed.
 898    ///
 899    /// Returns a `HashMap` indicating which selections whose former head position
 900    /// was no longer present. The keys of the map are selection ids. The values are
 901    /// the id of the new excerpt where the head of the selection has been moved.
 902    pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
 903        let mut pending = self.collection.pending.take();
 904        let mut selections_with_lost_position = HashMap::default();
 905
 906        let anchors_with_status = {
 907            let disjoint_anchors = self
 908                .disjoint
 909                .iter()
 910                .flat_map(|selection| [&selection.start, &selection.end]);
 911            self.snapshot.refresh_anchors(disjoint_anchors)
 912        };
 913        let adjusted_disjoint: Vec<_> = anchors_with_status
 914            .chunks(2)
 915            .map(|selection_anchors| {
 916                let (anchor_ix, start, kept_start) = selection_anchors[0];
 917                let (_, end, kept_end) = selection_anchors[1];
 918                let selection = &self.disjoint[anchor_ix / 2];
 919                let kept_head = if selection.reversed {
 920                    kept_start
 921                } else {
 922                    kept_end
 923                };
 924                if !kept_head {
 925                    selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
 926                }
 927
 928                Selection {
 929                    id: selection.id,
 930                    start,
 931                    end,
 932                    reversed: selection.reversed,
 933                    goal: selection.goal,
 934                }
 935            })
 936            .collect();
 937
 938        if !adjusted_disjoint.is_empty() {
 939            let map = self.display_snapshot();
 940            let resolved_selections =
 941                resolve_selections_wrapping_blocks(adjusted_disjoint.iter(), &map).collect();
 942            self.select::<MultiBufferOffset>(resolved_selections);
 943        }
 944
 945        if let Some(pending) = pending.as_mut() {
 946            let anchors = self
 947                .snapshot
 948                .refresh_anchors([&pending.selection.start, &pending.selection.end]);
 949            let (_, start, kept_start) = anchors[0];
 950            let (_, end, kept_end) = anchors[1];
 951            let kept_head = if pending.selection.reversed {
 952                kept_start
 953            } else {
 954                kept_end
 955            };
 956            if !kept_head {
 957                selections_with_lost_position
 958                    .insert(pending.selection.id, pending.selection.head().excerpt_id);
 959            }
 960
 961            pending.selection.start = start;
 962            pending.selection.end = end;
 963        }
 964        self.collection.pending = pending;
 965        self.selections_changed = true;
 966
 967        selections_with_lost_position
 968    }
 969}
 970
 971impl Deref for MutableSelectionsCollection<'_, '_> {
 972    type Target = SelectionsCollection;
 973    fn deref(&self) -> &Self::Target {
 974        self.collection
 975    }
 976}
 977
 978impl DerefMut for MutableSelectionsCollection<'_, '_> {
 979    fn deref_mut(&mut self) -> &mut Self::Target {
 980        self.collection
 981    }
 982}
 983
 984fn selection_to_anchor_selection(
 985    selection: Selection<MultiBufferOffset>,
 986    buffer: &MultiBufferSnapshot,
 987) -> Selection<Anchor> {
 988    let end_bias = if selection.start == selection.end {
 989        Bias::Right
 990    } else {
 991        Bias::Left
 992    };
 993    Selection {
 994        id: selection.id,
 995        start: buffer.anchor_after(selection.start),
 996        end: buffer.anchor_at(selection.end, end_bias),
 997        reversed: selection.reversed,
 998        goal: selection.goal,
 999    }
1000}
1001
1002fn resolve_selections_point<'a>(
1003    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1004    map: &'a DisplaySnapshot,
1005) -> impl 'a + Iterator<Item = Selection<Point>> {
1006    let (to_summarize, selections) = selections.into_iter().tee();
1007    let mut summaries = map
1008        .buffer_snapshot()
1009        .summaries_for_anchors::<Point, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
1010        .into_iter();
1011    selections.map(move |s| {
1012        let start = summaries.next().unwrap();
1013        let end = summaries.next().unwrap();
1014        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1015        Selection {
1016            id: s.id,
1017            start,
1018            end,
1019            reversed: s.reversed,
1020            goal: s.goal,
1021        }
1022    })
1023}
1024
1025/// Panics if passed selections are not in order
1026/// Resolves the anchors to display positions
1027fn resolve_selections_display<'a>(
1028    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1029    map: &'a DisplaySnapshot,
1030) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
1031    let selections = resolve_selections_point(selections, map).map(move |s| {
1032        let display_start = map.point_to_display_point(s.start, Bias::Left);
1033        let display_end = map.point_to_display_point(
1034            s.end,
1035            if s.start == s.end {
1036                Bias::Right
1037            } else {
1038                Bias::Left
1039            },
1040        );
1041        assert!(
1042            display_start <= display_end,
1043            "display_start: {:?}, display_end: {:?}",
1044            display_start,
1045            display_end
1046        );
1047        Selection {
1048            id: s.id,
1049            start: display_start,
1050            end: display_end,
1051            reversed: s.reversed,
1052            goal: s.goal,
1053        }
1054    });
1055    coalesce_selections(selections)
1056}
1057
1058/// Resolves the passed in anchors to [`MultiBufferDimension`]s `D`
1059/// wrapping around blocks inbetween.
1060///
1061/// # Panics
1062///
1063/// Panics if passed selections are not in order
1064pub(crate) fn resolve_selections_wrapping_blocks<'a, D, I>(
1065    selections: I,
1066    map: &'a DisplaySnapshot,
1067) -> impl 'a + Iterator<Item = Selection<D>>
1068where
1069    D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
1070    I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1071{
1072    // Transforms `Anchor -> DisplayPoint -> Point -> DisplayPoint -> D`
1073    // todo(lw): We should be able to short circuit the `Anchor -> DisplayPoint -> Point` to `Anchor -> Point`
1074    let (to_convert, selections) = resolve_selections_display(selections, map).tee();
1075    let mut converted_endpoints =
1076        map.buffer_snapshot()
1077            .dimensions_from_points::<D>(to_convert.flat_map(|s| {
1078                let start = map.display_point_to_point(s.start, Bias::Left);
1079                let end = map.display_point_to_point(s.end, Bias::Right);
1080                assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1081                [start, end]
1082            }));
1083    selections.map(move |s| {
1084        let start = converted_endpoints.next().unwrap();
1085        let end = converted_endpoints.next().unwrap();
1086        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1087        Selection {
1088            id: s.id,
1089            start,
1090            end,
1091            reversed: s.reversed,
1092            goal: s.goal,
1093        }
1094    })
1095}
1096
1097fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
1098    selections: impl Iterator<Item = Selection<D>>,
1099) -> impl Iterator<Item = Selection<D>> {
1100    let mut selections = selections.peekable();
1101    iter::from_fn(move || {
1102        let mut selection = selections.next()?;
1103        while let Some(next_selection) = selections.peek() {
1104            if selection.end >= next_selection.start {
1105                if selection.reversed == next_selection.reversed {
1106                    selection.end = cmp::max(selection.end, next_selection.end);
1107                    selections.next();
1108                } else {
1109                    selection.end = cmp::max(selection.start, next_selection.start);
1110                    break;
1111                }
1112            } else {
1113                break;
1114            }
1115        }
1116        assert!(
1117            selection.start <= selection.end,
1118            "selection.start: {:?}, selection.end: {:?}, selection.reversed: {:?}",
1119            selection.start,
1120            selection.end,
1121            selection.reversed
1122        );
1123        Some(selection)
1124    })
1125}