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