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 should_merge(
 140                        pending.start,
 141                        pending.end,
 142                        next_selection.start,
 143                        next_selection.end,
 144                        false,
 145                    ) {
 146                        let next_selection = disjoint.next().unwrap();
 147                        if next_selection.start < pending.start {
 148                            pending.start = next_selection.start;
 149                        }
 150                        if next_selection.end > pending.end {
 151                            pending.end = next_selection.end;
 152                        }
 153                    } else if next_selection.end < pending.start {
 154                        return disjoint.next();
 155                    } else {
 156                        break;
 157                    }
 158                }
 159
 160                pending_opt.take()
 161            } else {
 162                disjoint.next()
 163            }
 164        })
 165        .collect()
 166    }
 167
 168    /// Returns all of the selections, adjusted to take into account the selection line_mode
 169    pub fn all_adjusted(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<Point>> {
 170        let mut selections = self.all::<Point>(&snapshot);
 171        if self.line_mode {
 172            for selection in &mut selections {
 173                let new_range = snapshot.expand_to_line(selection.range());
 174                selection.start = new_range.start;
 175                selection.end = new_range.end;
 176            }
 177        }
 178        selections
 179    }
 180
 181    /// Returns the newest selection, adjusted to take into account the selection line_mode
 182    pub fn newest_adjusted(&self, snapshot: &DisplaySnapshot) -> Selection<Point> {
 183        let mut selection = self.newest::<Point>(&snapshot);
 184        if self.line_mode {
 185            let new_range = snapshot.expand_to_line(selection.range());
 186            selection.start = new_range.start;
 187            selection.end = new_range.end;
 188        }
 189        selection
 190    }
 191
 192    pub fn all_adjusted_display(
 193        &self,
 194        display_map: &DisplaySnapshot,
 195    ) -> Vec<Selection<DisplayPoint>> {
 196        if self.line_mode {
 197            let selections = self.all::<Point>(&display_map);
 198            let result = selections
 199                .into_iter()
 200                .map(|mut selection| {
 201                    let new_range = display_map.expand_to_line(selection.range());
 202                    selection.start = new_range.start;
 203                    selection.end = new_range.end;
 204                    selection.map(|point| point.to_display_point(&display_map))
 205                })
 206                .collect();
 207            result
 208        } else {
 209            self.all_display(display_map)
 210        }
 211    }
 212
 213    pub fn disjoint_in_range<D>(
 214        &self,
 215        range: Range<Anchor>,
 216        snapshot: &DisplaySnapshot,
 217    ) -> Vec<Selection<D>>
 218    where
 219        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord + std::fmt::Debug,
 220    {
 221        let start_ix = match self
 222            .disjoint
 223            .binary_search_by(|probe| probe.end.cmp(&range.start, snapshot.buffer_snapshot()))
 224        {
 225            Ok(ix) | Err(ix) => ix,
 226        };
 227        let end_ix = match self
 228            .disjoint
 229            .binary_search_by(|probe| probe.start.cmp(&range.end, snapshot.buffer_snapshot()))
 230        {
 231            Ok(ix) => ix + 1,
 232            Err(ix) => ix,
 233        };
 234        resolve_selections_wrapping_blocks(&self.disjoint[start_ix..end_ix], snapshot).collect()
 235    }
 236
 237    pub fn all_display(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<DisplayPoint>> {
 238        let disjoint_anchors = &self.disjoint;
 239        let mut disjoint =
 240            resolve_selections_display(disjoint_anchors.iter(), &snapshot).peekable();
 241        let mut pending_opt = resolve_selections_display(self.pending_anchor(), &snapshot).next();
 242        iter::from_fn(move || {
 243            if let Some(pending) = pending_opt.as_mut() {
 244                while let Some(next_selection) = disjoint.peek() {
 245                    if should_merge(
 246                        pending.start,
 247                        pending.end,
 248                        next_selection.start,
 249                        next_selection.end,
 250                        false,
 251                    ) {
 252                        let next_selection = disjoint.next().unwrap();
 253                        if next_selection.start < pending.start {
 254                            pending.start = next_selection.start;
 255                        }
 256                        if next_selection.end > pending.end {
 257                            pending.end = next_selection.end;
 258                        }
 259                    } else if next_selection.end < pending.start {
 260                        return disjoint.next();
 261                    } else {
 262                        break;
 263                    }
 264                }
 265
 266                pending_opt.take()
 267            } else {
 268                disjoint.next()
 269            }
 270        })
 271        .collect()
 272    }
 273
 274    pub fn newest_anchor(&self) -> &Selection<Anchor> {
 275        self.pending
 276            .as_ref()
 277            .map(|s| &s.selection)
 278            .or_else(|| self.disjoint.iter().max_by_key(|s| s.id))
 279            .unwrap()
 280    }
 281
 282    pub fn newest<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 283    where
 284        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 285    {
 286        resolve_selections_wrapping_blocks([self.newest_anchor()], &snapshot)
 287            .next()
 288            .unwrap()
 289    }
 290
 291    pub fn newest_display(&self, snapshot: &DisplaySnapshot) -> Selection<DisplayPoint> {
 292        resolve_selections_display([self.newest_anchor()], &snapshot)
 293            .next()
 294            .unwrap()
 295    }
 296
 297    pub fn oldest_anchor(&self) -> &Selection<Anchor> {
 298        self.disjoint
 299            .iter()
 300            .min_by_key(|s| s.id)
 301            .or_else(|| self.pending.as_ref().map(|p| &p.selection))
 302            .unwrap()
 303    }
 304
 305    pub fn oldest<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 306    where
 307        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 308    {
 309        resolve_selections_wrapping_blocks([self.oldest_anchor()], &snapshot)
 310            .next()
 311            .unwrap()
 312    }
 313
 314    pub fn first_anchor(&self) -> Selection<Anchor> {
 315        self.pending
 316            .as_ref()
 317            .map(|pending| pending.selection.clone())
 318            .unwrap_or_else(|| self.disjoint.first().cloned().unwrap())
 319    }
 320
 321    pub fn first<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 322    where
 323        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 324    {
 325        self.all(snapshot).first().unwrap().clone()
 326    }
 327
 328    pub fn last<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 329    where
 330        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 331    {
 332        self.all(snapshot).last().unwrap().clone()
 333    }
 334
 335    /// Returns a list of (potentially backwards!) ranges representing the selections.
 336    /// Useful for test assertions, but prefer `.all()` instead.
 337    #[cfg(any(test, feature = "test-support"))]
 338    pub fn ranges<D>(&self, snapshot: &DisplaySnapshot) -> Vec<Range<D>>
 339    where
 340        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 341    {
 342        self.all::<D>(snapshot)
 343            .iter()
 344            .map(|s| {
 345                if s.reversed {
 346                    s.end..s.start
 347                } else {
 348                    s.start..s.end
 349                }
 350            })
 351            .collect()
 352    }
 353
 354    #[cfg(any(test, feature = "test-support"))]
 355    pub fn display_ranges(&self, display_snapshot: &DisplaySnapshot) -> Vec<Range<DisplayPoint>> {
 356        self.disjoint_anchors_arc()
 357            .iter()
 358            .chain(self.pending_anchor())
 359            .map(|s| {
 360                if s.reversed {
 361                    s.end.to_display_point(display_snapshot)
 362                        ..s.start.to_display_point(display_snapshot)
 363                } else {
 364                    s.start.to_display_point(display_snapshot)
 365                        ..s.end.to_display_point(display_snapshot)
 366                }
 367            })
 368            .collect()
 369    }
 370
 371    /// Attempts to build a selection in the provided `DisplayRow` within the
 372    /// same range as the provided range of `Pixels`.
 373    /// Returns `None` if the range is not empty but it starts past the line's
 374    /// length, meaning that the line isn't long enough to be contained within
 375    /// part of the provided range.
 376    pub fn build_columnar_selection(
 377        &mut self,
 378        display_map: &DisplaySnapshot,
 379        row: DisplayRow,
 380        positions: &Range<Pixels>,
 381        reversed: bool,
 382        text_layout_details: &TextLayoutDetails,
 383    ) -> Option<Selection<Point>> {
 384        let is_empty = positions.start == positions.end;
 385        let line_len = display_map.line_len(row);
 386        let line = display_map.layout_row(row, text_layout_details);
 387        let start_col = line.closest_index_for_x(positions.start) as u32;
 388
 389        let (start, end) = if is_empty {
 390            let point = DisplayPoint::new(row, std::cmp::min(start_col, line_len));
 391            (point, point)
 392        } else {
 393            if start_col >= line_len {
 394                return None;
 395            }
 396            let start = DisplayPoint::new(row, start_col);
 397            let end_col = line.closest_index_for_x(positions.end) as u32;
 398            let end = DisplayPoint::new(row, end_col);
 399            (start, end)
 400        };
 401
 402        Some(Selection {
 403            id: post_inc(&mut self.next_selection_id),
 404            start: start.to_point(display_map),
 405            end: end.to_point(display_map),
 406            reversed,
 407            goal: SelectionGoal::HorizontalRange {
 408                start: positions.start.into(),
 409                end: positions.end.into(),
 410            },
 411        })
 412    }
 413
 414    /// Attempts to build a selection in the provided buffer row using the
 415    /// same buffer column range as specified.
 416    /// Returns `None` if the range is not empty but it starts past the line's
 417    /// length, meaning that the line isn't long enough to be contained within
 418    /// part of the provided range.
 419    pub fn build_columnar_selection_from_buffer_columns(
 420        &mut self,
 421        display_map: &DisplaySnapshot,
 422        buffer_row: u32,
 423        positions: &Range<u32>,
 424        reversed: bool,
 425        text_layout_details: &TextLayoutDetails,
 426    ) -> Option<Selection<Point>> {
 427        let is_empty = positions.start == positions.end;
 428        let line_len = display_map
 429            .buffer_snapshot()
 430            .line_len(multi_buffer::MultiBufferRow(buffer_row));
 431
 432        let (start, end) = if is_empty {
 433            let column = std::cmp::min(positions.start, line_len);
 434            let point = Point::new(buffer_row, column);
 435            (point, point)
 436        } else {
 437            if positions.start >= line_len {
 438                return None;
 439            }
 440
 441            let start = Point::new(buffer_row, positions.start);
 442            let end_column = std::cmp::min(positions.end, line_len);
 443            let end = Point::new(buffer_row, end_column);
 444            (start, end)
 445        };
 446
 447        let start_display_point = start.to_display_point(display_map);
 448        let end_display_point = end.to_display_point(display_map);
 449        let start_x = display_map.x_for_display_point(start_display_point, text_layout_details);
 450        let end_x = display_map.x_for_display_point(end_display_point, text_layout_details);
 451
 452        Some(Selection {
 453            id: post_inc(&mut self.next_selection_id),
 454            start,
 455            end,
 456            reversed,
 457            goal: SelectionGoal::HorizontalRange {
 458                start: start_x.min(end_x).into(),
 459                end: start_x.max(end_x).into(),
 460            },
 461        })
 462    }
 463
 464    pub fn change_with<R>(
 465        &mut self,
 466        snapshot: &DisplaySnapshot,
 467        change: impl FnOnce(&mut MutableSelectionsCollection<'_, '_>) -> R,
 468    ) -> (bool, R) {
 469        let mut mutable_collection = MutableSelectionsCollection {
 470            snapshot,
 471            collection: self,
 472            selections_changed: false,
 473        };
 474
 475        let result = change(&mut mutable_collection);
 476        assert!(
 477            !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
 478            "There must be at least one selection"
 479        );
 480        if cfg!(debug_assertions) {
 481            mutable_collection.disjoint.iter().for_each(|selection| {
 482                assert!(
 483                    snapshot.can_resolve(&selection.start),
 484                    "disjoint selection start is not resolvable for the given snapshot:\n{selection:?}, {excerpt:?}",
 485                    excerpt = snapshot.buffer_for_excerpt(selection.start.excerpt_id).map(|snapshot| snapshot.remote_id()),
 486                );
 487                assert!(
 488                    snapshot.can_resolve(&selection.end),
 489                    "disjoint selection end is not resolvable for the given snapshot: {selection:?}, {excerpt:?}",
 490                    excerpt = snapshot.buffer_for_excerpt(selection.end.excerpt_id).map(|snapshot| snapshot.remote_id()),
 491                );
 492            });
 493            if let Some(pending) = &mutable_collection.pending {
 494                let selection = &pending.selection;
 495                assert!(
 496                    snapshot.can_resolve(&selection.start),
 497                    "pending selection start is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
 498                    excerpt = snapshot
 499                        .buffer_for_excerpt(selection.start.excerpt_id)
 500                        .map(|snapshot| snapshot.remote_id()),
 501                );
 502                assert!(
 503                    snapshot.can_resolve(&selection.end),
 504                    "pending selection end is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
 505                    excerpt = snapshot
 506                        .buffer_for_excerpt(selection.end.excerpt_id)
 507                        .map(|snapshot| snapshot.remote_id()),
 508                );
 509            }
 510        }
 511        (mutable_collection.selections_changed, result)
 512    }
 513
 514    pub fn next_selection_id(&self) -> usize {
 515        self.next_selection_id
 516    }
 517
 518    pub fn line_mode(&self) -> bool {
 519        self.line_mode
 520    }
 521
 522    pub fn set_line_mode(&mut self, line_mode: bool) {
 523        self.line_mode = line_mode;
 524    }
 525
 526    pub fn select_mode(&self) -> &SelectMode {
 527        &self.select_mode
 528    }
 529
 530    pub fn set_select_mode(&mut self, select_mode: SelectMode) {
 531        self.select_mode = select_mode;
 532    }
 533
 534    pub fn is_extending(&self) -> bool {
 535        self.is_extending
 536    }
 537
 538    pub fn set_is_extending(&mut self, is_extending: bool) {
 539        self.is_extending = is_extending;
 540    }
 541}
 542
 543pub struct MutableSelectionsCollection<'snap, 'a> {
 544    collection: &'a mut SelectionsCollection,
 545    snapshot: &'snap DisplaySnapshot,
 546    selections_changed: bool,
 547}
 548
 549impl<'snap, 'a> fmt::Debug for MutableSelectionsCollection<'snap, 'a> {
 550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 551        f.debug_struct("MutableSelectionsCollection")
 552            .field("collection", &self.collection)
 553            .field("selections_changed", &self.selections_changed)
 554            .finish()
 555    }
 556}
 557
 558impl<'snap, 'a> MutableSelectionsCollection<'snap, 'a> {
 559    pub fn display_snapshot(&self) -> DisplaySnapshot {
 560        self.snapshot.clone()
 561    }
 562
 563    pub fn clear_disjoint(&mut self) {
 564        self.collection.disjoint = Arc::default();
 565    }
 566
 567    pub fn delete(&mut self, selection_id: usize) {
 568        let mut changed = false;
 569        self.collection.disjoint = self
 570            .disjoint
 571            .iter()
 572            .filter(|selection| {
 573                let found = selection.id == selection_id;
 574                changed |= found;
 575                !found
 576            })
 577            .cloned()
 578            .collect();
 579
 580        self.selections_changed |= changed;
 581    }
 582
 583    pub fn remove_selections_from_buffer(&mut self, buffer_id: language::BufferId) {
 584        let mut changed = false;
 585
 586        let filtered_selections: Arc<[Selection<Anchor>]> = {
 587            self.disjoint
 588                .iter()
 589                .filter(|selection| {
 590                    if let Some(selection_buffer_id) =
 591                        self.snapshot.buffer_id_for_anchor(selection.start)
 592                    {
 593                        let should_remove = selection_buffer_id == buffer_id;
 594                        changed |= should_remove;
 595                        !should_remove
 596                    } else {
 597                        true
 598                    }
 599                })
 600                .cloned()
 601                .collect()
 602        };
 603
 604        if filtered_selections.is_empty() {
 605            let buffer_snapshot = self.snapshot.buffer_snapshot();
 606            let anchor = buffer_snapshot
 607                .excerpts()
 608                .find(|(_, buffer, _)| buffer.remote_id() == buffer_id)
 609                .and_then(|(excerpt_id, _, range)| {
 610                    buffer_snapshot.anchor_in_excerpt(excerpt_id, range.context.start)
 611                })
 612                .unwrap_or_else(|| self.snapshot.anchor_before(MultiBufferOffset(0)));
 613            self.collection.disjoint = Arc::from([Selection {
 614                id: post_inc(&mut self.collection.next_selection_id),
 615                start: anchor,
 616                end: anchor,
 617                reversed: false,
 618                goal: SelectionGoal::None,
 619            }]);
 620        } else {
 621            self.collection.disjoint = filtered_selections;
 622        }
 623
 624        self.selections_changed |= changed;
 625    }
 626
 627    pub fn clear_pending(&mut self) {
 628        if self.collection.pending.is_some() {
 629            self.collection.pending = None;
 630            self.selections_changed = true;
 631        }
 632    }
 633
 634    pub(crate) fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
 635        self.collection.pending = Some(PendingSelection {
 636            selection: {
 637                let mut start = range.start;
 638                let mut end = range.end;
 639                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 640                    mem::swap(&mut start, &mut end);
 641                    true
 642                } else {
 643                    false
 644                };
 645                Selection {
 646                    id: post_inc(&mut self.collection.next_selection_id),
 647                    start,
 648                    end,
 649                    reversed,
 650                    goal: SelectionGoal::None,
 651                }
 652            },
 653            mode,
 654        });
 655        self.selections_changed = true;
 656    }
 657
 658    pub(crate) fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
 659        self.collection.pending = Some(PendingSelection { selection, mode });
 660        self.selections_changed = true;
 661    }
 662
 663    pub fn try_cancel(&mut self) -> bool {
 664        if let Some(pending) = self.collection.pending.take() {
 665            if self.disjoint.is_empty() {
 666                self.collection.disjoint = Arc::from([pending.selection]);
 667            }
 668            self.selections_changed = true;
 669            return true;
 670        }
 671
 672        let mut oldest = self.oldest_anchor().clone();
 673        if self.count() > 1 {
 674            self.collection.disjoint = Arc::from([oldest]);
 675            self.selections_changed = true;
 676            return true;
 677        }
 678
 679        if !oldest.start.cmp(&oldest.end, self.snapshot).is_eq() {
 680            let head = oldest.head();
 681            oldest.start = head;
 682            oldest.end = head;
 683            self.collection.disjoint = Arc::from([oldest]);
 684            self.selections_changed = true;
 685            return true;
 686        }
 687
 688        false
 689    }
 690
 691    pub fn insert_range<T>(&mut self, range: Range<T>)
 692    where
 693        T: ToOffset,
 694    {
 695        let display_map = self.display_snapshot();
 696        let mut selections = self.collection.all(&display_map);
 697        let mut start = range.start.to_offset(self.snapshot);
 698        let mut end = range.end.to_offset(self.snapshot);
 699        let reversed = if start > end {
 700            mem::swap(&mut start, &mut end);
 701            true
 702        } else {
 703            false
 704        };
 705        selections.push(Selection {
 706            id: post_inc(&mut self.collection.next_selection_id),
 707            start,
 708            end,
 709            reversed,
 710            goal: SelectionGoal::None,
 711        });
 712        self.select(selections);
 713    }
 714
 715    pub fn select<T>(&mut self, selections: Vec<Selection<T>>)
 716    where
 717        T: ToOffset + std::marker::Copy + std::fmt::Debug,
 718    {
 719        let mut selections = selections
 720            .into_iter()
 721            .map(|selection| selection.map(|it| it.to_offset(self.snapshot)))
 722            .map(|mut selection| {
 723                if selection.start > selection.end {
 724                    mem::swap(&mut selection.start, &mut selection.end);
 725                    selection.reversed = true
 726                }
 727                selection
 728            })
 729            .collect::<Vec<_>>();
 730        selections.sort_unstable_by_key(|s| s.start);
 731
 732        let mut i = 1;
 733        while i < selections.len() {
 734            let prev = &selections[i - 1];
 735            let current = &selections[i];
 736
 737            if should_merge(prev.start, prev.end, current.start, current.end, true) {
 738                let removed = selections.remove(i);
 739                if removed.start < selections[i - 1].start {
 740                    selections[i - 1].start = removed.start;
 741                }
 742                if selections[i - 1].end < removed.end {
 743                    selections[i - 1].end = removed.end;
 744                }
 745            } else {
 746                i += 1;
 747            }
 748        }
 749
 750        self.collection.disjoint = Arc::from_iter(
 751            selections
 752                .into_iter()
 753                .map(|selection| selection_to_anchor_selection(selection, self.snapshot)),
 754        );
 755        self.collection.pending = None;
 756        self.selections_changed = true;
 757    }
 758
 759    pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
 760        let map = self.display_snapshot();
 761        let resolved_selections =
 762            resolve_selections_wrapping_blocks::<MultiBufferOffset, _>(&selections, &map)
 763                .collect::<Vec<_>>();
 764        self.select(resolved_selections);
 765    }
 766
 767    pub fn select_ranges<I, T>(&mut self, ranges: I)
 768    where
 769        I: IntoIterator<Item = Range<T>>,
 770        T: ToOffset,
 771    {
 772        let ranges = ranges
 773            .into_iter()
 774            .map(|range| range.start.to_offset(self.snapshot)..range.end.to_offset(self.snapshot));
 775        self.select_offset_ranges(ranges);
 776    }
 777
 778    fn select_offset_ranges<I>(&mut self, ranges: I)
 779    where
 780        I: IntoIterator<Item = Range<MultiBufferOffset>>,
 781    {
 782        let selections = ranges
 783            .into_iter()
 784            .map(|range| {
 785                let mut start = range.start;
 786                let mut end = range.end;
 787                let reversed = if start > end {
 788                    mem::swap(&mut start, &mut end);
 789                    true
 790                } else {
 791                    false
 792                };
 793                Selection {
 794                    id: post_inc(&mut self.collection.next_selection_id),
 795                    start,
 796                    end,
 797                    reversed,
 798                    goal: SelectionGoal::None,
 799                }
 800            })
 801            .collect::<Vec<_>>();
 802
 803        self.select(selections)
 804    }
 805
 806    pub fn select_anchor_ranges<I>(&mut self, ranges: I)
 807    where
 808        I: IntoIterator<Item = Range<Anchor>>,
 809    {
 810        let selections = ranges
 811            .into_iter()
 812            .map(|range| {
 813                let mut start = range.start;
 814                let mut end = range.end;
 815                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 816                    mem::swap(&mut start, &mut end);
 817                    true
 818                } else {
 819                    false
 820                };
 821                Selection {
 822                    id: post_inc(&mut self.collection.next_selection_id),
 823                    start,
 824                    end,
 825                    reversed,
 826                    goal: SelectionGoal::None,
 827                }
 828            })
 829            .collect::<Vec<_>>();
 830        self.select_anchors(selections)
 831    }
 832
 833    pub fn new_selection_id(&mut self) -> usize {
 834        post_inc(&mut self.next_selection_id)
 835    }
 836
 837    pub fn select_display_ranges<T>(&mut self, ranges: T)
 838    where
 839        T: IntoIterator<Item = Range<DisplayPoint>>,
 840    {
 841        let selections = ranges
 842            .into_iter()
 843            .map(|range| {
 844                let mut start = range.start;
 845                let mut end = range.end;
 846                let reversed = if start > end {
 847                    mem::swap(&mut start, &mut end);
 848                    true
 849                } else {
 850                    false
 851                };
 852                Selection {
 853                    id: post_inc(&mut self.collection.next_selection_id),
 854                    start: start.to_point(self.snapshot),
 855                    end: end.to_point(self.snapshot),
 856                    reversed,
 857                    goal: SelectionGoal::None,
 858                }
 859            })
 860            .collect();
 861        self.select(selections);
 862    }
 863
 864    pub fn reverse_selections(&mut self) {
 865        let mut new_selections: Vec<Selection<Point>> = Vec::new();
 866        let disjoint = self.disjoint.clone();
 867        for selection in disjoint
 868            .iter()
 869            .sorted_by(|first, second| Ord::cmp(&second.id, &first.id))
 870            .collect::<Vec<&Selection<Anchor>>>()
 871        {
 872            new_selections.push(Selection {
 873                id: self.new_selection_id(),
 874                start: selection
 875                    .start
 876                    .to_display_point(self.snapshot)
 877                    .to_point(self.snapshot),
 878                end: selection
 879                    .end
 880                    .to_display_point(self.snapshot)
 881                    .to_point(self.snapshot),
 882                reversed: selection.reversed,
 883                goal: selection.goal,
 884            });
 885        }
 886        self.select(new_selections);
 887    }
 888
 889    pub fn move_with(
 890        &mut self,
 891        mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
 892    ) {
 893        let mut changed = false;
 894        let display_map = self.display_snapshot();
 895        let selections = self.collection.all_display(&display_map);
 896        let selections = selections
 897            .into_iter()
 898            .map(|selection| {
 899                let mut moved_selection = selection.clone();
 900                move_selection(&display_map, &mut moved_selection);
 901                if selection != moved_selection {
 902                    changed = true;
 903                }
 904                moved_selection.map(|display_point| display_point.to_point(&display_map))
 905            })
 906            .collect();
 907
 908        if changed {
 909            self.select(selections)
 910        }
 911    }
 912
 913    pub fn move_offsets_with(
 914        &mut self,
 915        mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<MultiBufferOffset>),
 916    ) {
 917        let mut changed = false;
 918        let display_map = self.display_snapshot();
 919        let selections = self
 920            .collection
 921            .all::<MultiBufferOffset>(&display_map)
 922            .into_iter()
 923            .map(|selection| {
 924                let mut moved_selection = selection.clone();
 925                move_selection(self.snapshot, &mut moved_selection);
 926                if selection != moved_selection {
 927                    changed = true;
 928                }
 929                moved_selection
 930            })
 931            .collect();
 932
 933        if changed {
 934            self.select(selections)
 935        }
 936    }
 937
 938    pub fn move_heads_with(
 939        &mut self,
 940        mut update_head: impl FnMut(
 941            &DisplaySnapshot,
 942            DisplayPoint,
 943            SelectionGoal,
 944        ) -> (DisplayPoint, SelectionGoal),
 945    ) {
 946        self.move_with(|map, selection| {
 947            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
 948            selection.set_head(new_head, new_goal);
 949        });
 950    }
 951
 952    pub fn move_cursors_with(
 953        &mut self,
 954        mut update_cursor_position: impl FnMut(
 955            &DisplaySnapshot,
 956            DisplayPoint,
 957            SelectionGoal,
 958        ) -> (DisplayPoint, SelectionGoal),
 959    ) {
 960        self.move_with(|map, selection| {
 961            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
 962            selection.collapse_to(cursor, new_goal)
 963        });
 964    }
 965
 966    pub fn maybe_move_cursors_with(
 967        &mut self,
 968        mut update_cursor_position: impl FnMut(
 969            &DisplaySnapshot,
 970            DisplayPoint,
 971            SelectionGoal,
 972        ) -> Option<(DisplayPoint, SelectionGoal)>,
 973    ) {
 974        self.move_cursors_with(|map, point, goal| {
 975            update_cursor_position(map, point, goal).unwrap_or((point, goal))
 976        })
 977    }
 978
 979    pub fn replace_cursors_with(
 980        &mut self,
 981        find_replacement_cursors: impl FnOnce(&DisplaySnapshot) -> Vec<DisplayPoint>,
 982    ) {
 983        let new_selections = find_replacement_cursors(self.snapshot)
 984            .into_iter()
 985            .map(|cursor| {
 986                let cursor_point = cursor.to_point(self.snapshot);
 987                Selection {
 988                    id: post_inc(&mut self.collection.next_selection_id),
 989                    start: cursor_point,
 990                    end: cursor_point,
 991                    reversed: false,
 992                    goal: SelectionGoal::None,
 993                }
 994            })
 995            .collect();
 996        self.select(new_selections);
 997    }
 998
 999    /// Compute new ranges for any selections that were located in excerpts that have
1000    /// since been removed.
1001    ///
1002    /// Returns a `HashMap` indicating which selections whose former head position
1003    /// was no longer present. The keys of the map are selection ids. The values are
1004    /// the id of the new excerpt where the head of the selection has been moved.
1005    pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
1006        let mut pending = self.collection.pending.take();
1007        let mut selections_with_lost_position = HashMap::default();
1008
1009        let anchors_with_status = {
1010            let disjoint_anchors = self
1011                .disjoint
1012                .iter()
1013                .flat_map(|selection| [&selection.start, &selection.end]);
1014            self.snapshot.refresh_anchors(disjoint_anchors)
1015        };
1016        let adjusted_disjoint: Vec<_> = anchors_with_status
1017            .chunks(2)
1018            .map(|selection_anchors| {
1019                let (anchor_ix, start, kept_start) = selection_anchors[0];
1020                let (_, end, kept_end) = selection_anchors[1];
1021                let selection = &self.disjoint[anchor_ix / 2];
1022                let kept_head = if selection.reversed {
1023                    kept_start
1024                } else {
1025                    kept_end
1026                };
1027                if !kept_head {
1028                    selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
1029                }
1030
1031                Selection {
1032                    id: selection.id,
1033                    start,
1034                    end,
1035                    reversed: selection.reversed,
1036                    goal: selection.goal,
1037                }
1038            })
1039            .collect();
1040
1041        if !adjusted_disjoint.is_empty() {
1042            let map = self.display_snapshot();
1043            let resolved_selections =
1044                resolve_selections_wrapping_blocks(adjusted_disjoint.iter(), &map).collect();
1045            self.select::<MultiBufferOffset>(resolved_selections);
1046        }
1047
1048        if let Some(pending) = pending.as_mut() {
1049            let anchors = self
1050                .snapshot
1051                .refresh_anchors([&pending.selection.start, &pending.selection.end]);
1052            let (_, start, kept_start) = anchors[0];
1053            let (_, end, kept_end) = anchors[1];
1054            let kept_head = if pending.selection.reversed {
1055                kept_start
1056            } else {
1057                kept_end
1058            };
1059            if !kept_head {
1060                selections_with_lost_position
1061                    .insert(pending.selection.id, pending.selection.head().excerpt_id);
1062            }
1063
1064            pending.selection.start = start;
1065            pending.selection.end = end;
1066        }
1067        self.collection.pending = pending;
1068        self.selections_changed = true;
1069
1070        selections_with_lost_position
1071    }
1072}
1073
1074impl Deref for MutableSelectionsCollection<'_, '_> {
1075    type Target = SelectionsCollection;
1076    fn deref(&self) -> &Self::Target {
1077        self.collection
1078    }
1079}
1080
1081impl DerefMut for MutableSelectionsCollection<'_, '_> {
1082    fn deref_mut(&mut self) -> &mut Self::Target {
1083        self.collection
1084    }
1085}
1086
1087fn selection_to_anchor_selection(
1088    selection: Selection<MultiBufferOffset>,
1089    buffer: &MultiBufferSnapshot,
1090) -> Selection<Anchor> {
1091    let end_bias = if selection.start == selection.end {
1092        Bias::Right
1093    } else {
1094        Bias::Left
1095    };
1096    Selection {
1097        id: selection.id,
1098        start: buffer.anchor_after(selection.start),
1099        end: buffer.anchor_at(selection.end, end_bias),
1100        reversed: selection.reversed,
1101        goal: selection.goal,
1102    }
1103}
1104
1105fn resolve_selections_point<'a>(
1106    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1107    map: &'a DisplaySnapshot,
1108) -> impl 'a + Iterator<Item = Selection<Point>> {
1109    let (to_summarize, selections) = selections.into_iter().tee();
1110    let mut summaries = map
1111        .buffer_snapshot()
1112        .summaries_for_anchors::<Point, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
1113        .into_iter();
1114    selections.map(move |s| {
1115        let start = summaries.next().unwrap();
1116        let end = summaries.next().unwrap();
1117        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1118        Selection {
1119            id: s.id,
1120            start,
1121            end,
1122            reversed: s.reversed,
1123            goal: s.goal,
1124        }
1125    })
1126}
1127
1128/// Panics if passed selections are not in order
1129/// Resolves the anchors to display positions
1130fn resolve_selections_display<'a>(
1131    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1132    map: &'a DisplaySnapshot,
1133) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
1134    let selections = resolve_selections_point(selections, map).map(move |s| {
1135        let display_start = map.point_to_display_point(s.start, Bias::Left);
1136        let display_end = map.point_to_display_point(
1137            s.end,
1138            if s.start == s.end {
1139                Bias::Right
1140            } else {
1141                Bias::Left
1142            },
1143        );
1144        assert!(
1145            display_start <= display_end,
1146            "display_start: {:?}, display_end: {:?}",
1147            display_start,
1148            display_end
1149        );
1150        Selection {
1151            id: s.id,
1152            start: display_start,
1153            end: display_end,
1154            reversed: s.reversed,
1155            goal: s.goal,
1156        }
1157    });
1158    coalesce_selections(selections)
1159}
1160
1161/// Resolves the passed in anchors to [`MultiBufferDimension`]s `D`
1162/// wrapping around blocks inbetween.
1163///
1164/// # Panics
1165///
1166/// Panics if passed selections are not in order
1167pub(crate) fn resolve_selections_wrapping_blocks<'a, D, I>(
1168    selections: I,
1169    map: &'a DisplaySnapshot,
1170) -> impl 'a + Iterator<Item = Selection<D>>
1171where
1172    D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
1173    I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1174{
1175    // Transforms `Anchor -> DisplayPoint -> Point -> DisplayPoint -> D`
1176    // todo(lw): We should be able to short circuit the `Anchor -> DisplayPoint -> Point` to `Anchor -> Point`
1177    let (to_convert, selections) = resolve_selections_display(selections, map).tee();
1178    let mut converted_endpoints =
1179        map.buffer_snapshot()
1180            .dimensions_from_points::<D>(to_convert.flat_map(|s| {
1181                let start = map.display_point_to_point(s.start, Bias::Left);
1182                let end = map.display_point_to_point(s.end, Bias::Right);
1183                assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1184                [start, end]
1185            }));
1186    selections.map(move |s| {
1187        let start = converted_endpoints.next().unwrap();
1188        let end = converted_endpoints.next().unwrap();
1189        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1190        Selection {
1191            id: s.id,
1192            start,
1193            end,
1194            reversed: s.reversed,
1195            goal: s.goal,
1196        }
1197    })
1198}
1199
1200fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
1201    selections: impl Iterator<Item = Selection<D>>,
1202) -> impl Iterator<Item = Selection<D>> {
1203    let mut selections = selections.peekable();
1204    iter::from_fn(move || {
1205        let mut selection = selections.next()?;
1206        while let Some(next_selection) = selections.peek() {
1207            if should_merge(
1208                selection.start,
1209                selection.end,
1210                next_selection.start,
1211                next_selection.end,
1212                true,
1213            ) {
1214                if selection.reversed == next_selection.reversed {
1215                    selection.end = cmp::max(selection.end, next_selection.end);
1216                    selections.next();
1217                } else {
1218                    selection.end = cmp::max(selection.start, next_selection.start);
1219                    break;
1220                }
1221            } else {
1222                break;
1223            }
1224        }
1225        assert!(
1226            selection.start <= selection.end,
1227            "selection.start: {:?}, selection.end: {:?}, selection.reversed: {:?}",
1228            selection.start,
1229            selection.end,
1230            selection.reversed
1231        );
1232        Some(selection)
1233    })
1234}
1235
1236/// Determines whether two selections should be merged into one.
1237///
1238/// Two selections should be merged when:
1239/// 1. They overlap: the selections share at least one position
1240/// 2. They have the same start position: one contains or equals the other
1241/// 3. A cursor touches a selection boundary: a zero-width selection (cursor) at the
1242///    start or end of another selection should be absorbed into it
1243///
1244/// Note: two selections that merely touch (one ends exactly where the other begins)
1245/// but don't share any positions remain separate, see: https://github.com/zed-industries/zed/issues/24748
1246fn should_merge<T: Ord + Copy>(a_start: T, a_end: T, b_start: T, b_end: T, sorted: bool) -> bool {
1247    let is_overlapping = if sorted {
1248        // When sorted, `a` starts before or at `b`, so overlap means `b` starts before `a` ends
1249        b_start < a_end
1250    } else {
1251        a_start < b_end && b_start < a_end
1252    };
1253
1254    // Selections starting at the same position should always merge (one contains the other)
1255    let same_start = a_start == b_start;
1256
1257    // A cursor (zero-width selection) touching another selection's boundary should merge.
1258    // This handles cases like a cursor at position X merging with a selection that
1259    // starts or ends at X.
1260    let is_cursor_a = a_start == a_end;
1261    let is_cursor_b = b_start == b_end;
1262    let cursor_at_boundary = (is_cursor_a && (a_start == b_start || a_end == b_end))
1263        || (is_cursor_b && (b_start == a_start || b_end == a_end));
1264
1265    is_overlapping || same_start || cursor_at_boundary
1266}