selections_collection.rs

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