multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt, Offset};
   4use anyhow::{anyhow, Result};
   5use clock::ReplicaId;
   6use collections::{BTreeMap, Bound, HashMap, HashSet};
   7use futures::{channel::mpsc, SinkExt};
   8use git::diff::DiffHunk;
   9use gpui::{AppContext, EventEmitter, Model, ModelContext};
  10use itertools::Itertools;
  11use language::{
  12    char_kind,
  13    language_settings::{language_settings, LanguageSettings},
  14    AutoindentMode, Buffer, BufferChunks, BufferRow, BufferSnapshot, Capability, CharKind, Chunk,
  15    CursorShape, DiagnosticEntry, File, IndentGuide, IndentSize, Language, LanguageScope,
  16    OffsetRangeExt, OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension,
  17    ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId, Unclipped,
  18};
  19use smallvec::SmallVec;
  20use std::{
  21    any::type_name,
  22    borrow::Cow,
  23    cell::{Ref, RefCell},
  24    cmp, fmt,
  25    future::Future,
  26    io,
  27    iter::{self, FromIterator},
  28    mem,
  29    ops::{Range, RangeBounds, Sub},
  30    str,
  31    sync::Arc,
  32    time::{Duration, Instant},
  33};
  34use sum_tree::{Bias, Cursor, SumTree};
  35use text::{
  36    locator::Locator,
  37    subscription::{Subscription, Topic},
  38    BufferId, Edit, TextSummary,
  39};
  40use theme::SyntaxTheme;
  41
  42use util::post_inc;
  43
  44#[cfg(any(test, feature = "test-support"))]
  45use gpui::Context;
  46
  47const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
  48
  49#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
  50pub struct ExcerptId(usize);
  51
  52/// One or more [`Buffers`](Buffer) being edited in a single view.
  53///
  54/// See <https://zed.dev/features#multi-buffers>
  55pub struct MultiBuffer {
  56    /// A snapshot of the [`Excerpt`]s in the MultiBuffer.
  57    /// Use [`MultiBuffer::snapshot`] to get a up-to-date snapshot.
  58    snapshot: RefCell<MultiBufferSnapshot>,
  59    /// Contains the state of the buffers being edited
  60    buffers: RefCell<HashMap<BufferId, BufferState>>,
  61    subscriptions: Topic,
  62    /// If true, the multi-buffer only contains a single [`Buffer`] and a single [`Excerpt`]
  63    singleton: bool,
  64    replica_id: ReplicaId,
  65    history: History,
  66    title: Option<String>,
  67    capability: Capability,
  68}
  69
  70#[derive(Clone, Debug, PartialEq, Eq)]
  71pub enum Event {
  72    ExcerptsAdded {
  73        buffer: Model<Buffer>,
  74        predecessor: ExcerptId,
  75        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
  76    },
  77    ExcerptsRemoved {
  78        ids: Vec<ExcerptId>,
  79    },
  80    ExcerptsEdited {
  81        ids: Vec<ExcerptId>,
  82    },
  83    Edited {
  84        singleton_buffer_edited: bool,
  85    },
  86    TransactionUndone {
  87        transaction_id: TransactionId,
  88    },
  89    Reloaded,
  90    DiffBaseChanged,
  91    DiffUpdated {
  92        buffer: Model<Buffer>,
  93    },
  94    LanguageChanged,
  95    CapabilityChanged,
  96    Reparsed,
  97    Saved,
  98    FileHandleChanged,
  99    Closed,
 100    DirtyChanged,
 101    DiagnosticsUpdated,
 102}
 103
 104pub type MultiBufferPoint = Point;
 105
 106#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq, serde::Deserialize)]
 107#[serde(transparent)]
 108pub struct MultiBufferRow(pub u32);
 109
 110impl MultiBufferRow {
 111    pub const MIN: Self = Self(0);
 112    pub const MAX: Self = Self(u32::MAX);
 113}
 114
 115#[derive(Clone)]
 116struct History {
 117    next_transaction_id: TransactionId,
 118    undo_stack: Vec<Transaction>,
 119    redo_stack: Vec<Transaction>,
 120    transaction_depth: usize,
 121    group_interval: Duration,
 122}
 123
 124#[derive(Clone)]
 125struct Transaction {
 126    id: TransactionId,
 127    buffer_transactions: HashMap<BufferId, text::TransactionId>,
 128    first_edit_at: Instant,
 129    last_edit_at: Instant,
 130    suppress_grouping: bool,
 131}
 132
 133pub trait ToOffset: 'static + fmt::Debug {
 134    fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
 135}
 136
 137pub trait ToOffsetUtf16: 'static + fmt::Debug {
 138    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;
 139}
 140
 141pub trait ToPoint: 'static + fmt::Debug {
 142    fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
 143}
 144
 145pub trait ToPointUtf16: 'static + fmt::Debug {
 146    fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
 147}
 148
 149struct BufferState {
 150    buffer: Model<Buffer>,
 151    last_version: clock::Global,
 152    last_parse_count: usize,
 153    last_selections_update_count: usize,
 154    last_diagnostics_update_count: usize,
 155    last_file_update_count: usize,
 156    last_git_diff_update_count: usize,
 157    excerpts: Vec<Locator>,
 158    _subscriptions: [gpui::Subscription; 2],
 159}
 160
 161/// The contents of a [`MultiBuffer`] at a single point in time.
 162#[derive(Clone, Default)]
 163pub struct MultiBufferSnapshot {
 164    singleton: bool,
 165    excerpts: SumTree<Excerpt>,
 166    excerpt_ids: SumTree<ExcerptIdMapping>,
 167    parse_count: usize,
 168    diagnostics_update_count: usize,
 169    trailing_excerpt_update_count: usize,
 170    git_diff_update_count: usize,
 171    edit_count: usize,
 172    is_dirty: bool,
 173    has_conflict: bool,
 174    show_headers: bool,
 175}
 176
 177pub struct ExcerptInfo {
 178    pub id: ExcerptId,
 179    pub buffer: BufferSnapshot,
 180    pub buffer_id: BufferId,
 181    pub range: ExcerptRange<text::Anchor>,
 182}
 183
 184impl std::fmt::Debug for ExcerptInfo {
 185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 186        f.debug_struct(type_name::<Self>())
 187            .field("id", &self.id)
 188            .field("buffer_id", &self.buffer_id)
 189            .field("range", &self.range)
 190            .finish()
 191    }
 192}
 193
 194/// A boundary between [`Excerpt`]s in a [`MultiBuffer`]
 195#[derive(Debug)]
 196pub struct ExcerptBoundary {
 197    pub prev: Option<ExcerptInfo>,
 198    pub next: Option<ExcerptInfo>,
 199    /// The row in the `MultiBuffer` where the boundary is located
 200    pub row: MultiBufferRow,
 201}
 202
 203impl ExcerptBoundary {
 204    pub fn starts_new_buffer(&self) -> bool {
 205        match (self.prev.as_ref(), self.next.as_ref()) {
 206            (None, _) => true,
 207            (Some(_), None) => false,
 208            (Some(prev), Some(next)) => prev.buffer_id != next.buffer_id,
 209        }
 210    }
 211}
 212
 213/// A slice into a [`Buffer`] that is being edited in a [`MultiBuffer`].
 214#[derive(Clone)]
 215struct Excerpt {
 216    /// The unique identifier for this excerpt
 217    id: ExcerptId,
 218    /// The location of the excerpt in the [`MultiBuffer`]
 219    locator: Locator,
 220    /// The buffer being excerpted
 221    buffer_id: BufferId,
 222    /// A snapshot of the buffer being excerpted
 223    buffer: BufferSnapshot,
 224    /// The range of the buffer to be shown in the excerpt
 225    range: ExcerptRange<text::Anchor>,
 226    /// The last row in the excerpted slice of the buffer
 227    max_buffer_row: BufferRow,
 228    /// A summary of the text in the excerpt
 229    text_summary: TextSummary,
 230    has_trailing_newline: bool,
 231}
 232
 233/// A public view into an [`Excerpt`] in a [`MultiBuffer`].
 234///
 235/// Contains methods for getting the [`Buffer`] of the excerpt,
 236/// as well as mapping offsets to/from buffer and multibuffer coordinates.
 237#[derive(Clone)]
 238pub struct MultiBufferExcerpt<'a> {
 239    excerpt: &'a Excerpt,
 240    excerpt_offset: usize,
 241}
 242
 243#[derive(Clone, Debug)]
 244struct ExcerptIdMapping {
 245    id: ExcerptId,
 246    locator: Locator,
 247}
 248
 249/// A range of text from a single [`Buffer`], to be shown as an [`Excerpt`].
 250/// These ranges are relative to the buffer itself
 251#[derive(Clone, Debug, Eq, PartialEq)]
 252pub struct ExcerptRange<T> {
 253    /// The full range of text to be shown in the excerpt.
 254    pub context: Range<T>,
 255    /// The primary range of text to be highlighted in the excerpt.
 256    /// In a multi-buffer search, this would be the text that matched the search
 257    pub primary: Option<Range<T>>,
 258}
 259
 260#[derive(Clone, Debug, Default)]
 261struct ExcerptSummary {
 262    excerpt_id: ExcerptId,
 263    /// The location of the last [`Excerpt`] being summarized
 264    excerpt_locator: Locator,
 265    /// The maximum row of the [`Excerpt`]s being summarized
 266    max_buffer_row: MultiBufferRow,
 267    text: TextSummary,
 268}
 269
 270#[derive(Clone)]
 271pub struct MultiBufferRows<'a> {
 272    buffer_row_range: Range<u32>,
 273    excerpts: Cursor<'a, Excerpt, Point>,
 274}
 275
 276pub struct MultiBufferChunks<'a> {
 277    range: Range<usize>,
 278    excerpts: Cursor<'a, Excerpt, usize>,
 279    excerpt_chunks: Option<ExcerptChunks<'a>>,
 280    language_aware: bool,
 281}
 282
 283pub struct MultiBufferBytes<'a> {
 284    range: Range<usize>,
 285    excerpts: Cursor<'a, Excerpt, usize>,
 286    excerpt_bytes: Option<ExcerptBytes<'a>>,
 287    chunk: &'a [u8],
 288}
 289
 290pub struct ReversedMultiBufferBytes<'a> {
 291    range: Range<usize>,
 292    excerpts: Cursor<'a, Excerpt, usize>,
 293    excerpt_bytes: Option<ExcerptBytes<'a>>,
 294    chunk: &'a [u8],
 295}
 296
 297struct ExcerptChunks<'a> {
 298    content_chunks: BufferChunks<'a>,
 299    footer_height: usize,
 300}
 301
 302struct ExcerptBytes<'a> {
 303    content_bytes: text::Bytes<'a>,
 304    padding_height: usize,
 305    reversed: bool,
 306}
 307
 308pub enum ExpandExcerptDirection {
 309    Up,
 310    Down,
 311    UpAndDown,
 312}
 313
 314impl ExpandExcerptDirection {
 315    pub fn should_expand_up(&self) -> bool {
 316        match self {
 317            ExpandExcerptDirection::Up => true,
 318            ExpandExcerptDirection::Down => false,
 319            ExpandExcerptDirection::UpAndDown => true,
 320        }
 321    }
 322
 323    pub fn should_expand_down(&self) -> bool {
 324        match self {
 325            ExpandExcerptDirection::Up => false,
 326            ExpandExcerptDirection::Down => true,
 327            ExpandExcerptDirection::UpAndDown => true,
 328        }
 329    }
 330}
 331
 332#[derive(Clone, Debug, PartialEq)]
 333pub struct MultiBufferIndentGuide {
 334    pub multibuffer_row_range: Range<MultiBufferRow>,
 335    pub buffer: IndentGuide,
 336}
 337
 338impl std::ops::Deref for MultiBufferIndentGuide {
 339    type Target = IndentGuide;
 340
 341    fn deref(&self) -> &Self::Target {
 342        &self.buffer
 343    }
 344}
 345
 346impl MultiBuffer {
 347    pub fn new(replica_id: ReplicaId, capability: Capability) -> Self {
 348        Self {
 349            snapshot: RefCell::new(MultiBufferSnapshot {
 350                show_headers: true,
 351                ..MultiBufferSnapshot::default()
 352            }),
 353            buffers: RefCell::default(),
 354            subscriptions: Topic::default(),
 355            singleton: false,
 356            capability,
 357            replica_id,
 358            title: None,
 359            history: History {
 360                next_transaction_id: clock::Lamport::default(),
 361                undo_stack: Vec::new(),
 362                redo_stack: Vec::new(),
 363                transaction_depth: 0,
 364                group_interval: Duration::from_millis(300),
 365            },
 366        }
 367    }
 368
 369    pub fn without_headers(replica_id: ReplicaId, capability: Capability) -> Self {
 370        Self {
 371            snapshot: Default::default(),
 372            buffers: Default::default(),
 373            subscriptions: Default::default(),
 374            singleton: false,
 375            capability,
 376            replica_id,
 377            history: History {
 378                next_transaction_id: Default::default(),
 379                undo_stack: Default::default(),
 380                redo_stack: Default::default(),
 381                transaction_depth: 0,
 382                group_interval: Duration::from_millis(300),
 383            },
 384            title: Default::default(),
 385        }
 386    }
 387
 388    pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self {
 389        let mut buffers = HashMap::default();
 390        for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
 391            buffers.insert(
 392                *buffer_id,
 393                BufferState {
 394                    buffer: buffer_state.buffer.clone(),
 395                    last_version: buffer_state.last_version.clone(),
 396                    last_parse_count: buffer_state.last_parse_count,
 397                    last_selections_update_count: buffer_state.last_selections_update_count,
 398                    last_diagnostics_update_count: buffer_state.last_diagnostics_update_count,
 399                    last_file_update_count: buffer_state.last_file_update_count,
 400                    last_git_diff_update_count: buffer_state.last_git_diff_update_count,
 401                    excerpts: buffer_state.excerpts.clone(),
 402                    _subscriptions: [
 403                        new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()),
 404                        new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event),
 405                    ],
 406                },
 407            );
 408        }
 409        Self {
 410            snapshot: RefCell::new(self.snapshot.borrow().clone()),
 411            buffers: RefCell::new(buffers),
 412            subscriptions: Default::default(),
 413            singleton: self.singleton,
 414            capability: self.capability,
 415            replica_id: self.replica_id,
 416            history: self.history.clone(),
 417            title: self.title.clone(),
 418        }
 419    }
 420
 421    pub fn with_title(mut self, title: String) -> Self {
 422        self.title = Some(title);
 423        self
 424    }
 425
 426    pub fn read_only(&self) -> bool {
 427        self.capability == Capability::ReadOnly
 428    }
 429
 430    pub fn singleton(buffer: Model<Buffer>, cx: &mut ModelContext<Self>) -> Self {
 431        let mut this = Self::new(buffer.read(cx).replica_id(), buffer.read(cx).capability());
 432        this.singleton = true;
 433        this.push_excerpts(
 434            buffer,
 435            [ExcerptRange {
 436                context: text::Anchor::MIN..text::Anchor::MAX,
 437                primary: None,
 438            }],
 439            cx,
 440        );
 441        this.snapshot.borrow_mut().singleton = true;
 442        this
 443    }
 444
 445    pub fn replica_id(&self) -> ReplicaId {
 446        self.replica_id
 447    }
 448
 449    /// Returns an up-to-date snapshot of the MultiBuffer.
 450    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
 451        self.sync(cx);
 452        self.snapshot.borrow().clone()
 453    }
 454
 455    pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
 456        self.sync(cx);
 457        self.snapshot.borrow()
 458    }
 459
 460    pub fn as_singleton(&self) -> Option<Model<Buffer>> {
 461        if self.singleton {
 462            return Some(
 463                self.buffers
 464                    .borrow()
 465                    .values()
 466                    .next()
 467                    .unwrap()
 468                    .buffer
 469                    .clone(),
 470            );
 471        } else {
 472            None
 473        }
 474    }
 475
 476    pub fn is_singleton(&self) -> bool {
 477        self.singleton
 478    }
 479
 480    pub fn subscribe(&mut self) -> Subscription {
 481        self.subscriptions.subscribe()
 482    }
 483
 484    pub fn is_dirty(&self, cx: &AppContext) -> bool {
 485        self.read(cx).is_dirty()
 486    }
 487
 488    pub fn has_conflict(&self, cx: &AppContext) -> bool {
 489        self.read(cx).has_conflict()
 490    }
 491
 492    // The `is_empty` signature doesn't match what clippy expects
 493    #[allow(clippy::len_without_is_empty)]
 494    pub fn len(&self, cx: &AppContext) -> usize {
 495        self.read(cx).len()
 496    }
 497
 498    pub fn is_empty(&self, cx: &AppContext) -> bool {
 499        self.len(cx) != 0
 500    }
 501
 502    pub fn symbols_containing<T: ToOffset>(
 503        &self,
 504        offset: T,
 505        theme: Option<&SyntaxTheme>,
 506        cx: &AppContext,
 507    ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
 508        self.read(cx).symbols_containing(offset, theme)
 509    }
 510
 511    pub fn edit<I, S, T>(
 512        &mut self,
 513        edits: I,
 514        mut autoindent_mode: Option<AutoindentMode>,
 515        cx: &mut ModelContext<Self>,
 516    ) where
 517        I: IntoIterator<Item = (Range<S>, T)>,
 518        S: ToOffset,
 519        T: Into<Arc<str>>,
 520    {
 521        if self.read_only() {
 522            return;
 523        }
 524        if self.buffers.borrow().is_empty() {
 525            return;
 526        }
 527
 528        let snapshot = self.read(cx);
 529        let edits = edits.into_iter().map(|(range, new_text)| {
 530            let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
 531            if range.start > range.end {
 532                mem::swap(&mut range.start, &mut range.end);
 533            }
 534            (range, new_text)
 535        });
 536
 537        if let Some(buffer) = self.as_singleton() {
 538            return buffer.update(cx, |buffer, cx| {
 539                buffer.edit(edits, autoindent_mode, cx);
 540            });
 541        }
 542
 543        let original_indent_columns = match &mut autoindent_mode {
 544            Some(AutoindentMode::Block {
 545                original_indent_columns,
 546            }) => mem::take(original_indent_columns),
 547            _ => Default::default(),
 548        };
 549
 550        struct BufferEdit {
 551            range: Range<usize>,
 552            new_text: Arc<str>,
 553            is_insertion: bool,
 554            original_indent_column: u32,
 555        }
 556        let mut buffer_edits: HashMap<BufferId, Vec<BufferEdit>> = Default::default();
 557        let mut edited_excerpt_ids = Vec::new();
 558        let mut cursor = snapshot.excerpts.cursor::<usize>();
 559        for (ix, (range, new_text)) in edits.enumerate() {
 560            let new_text: Arc<str> = new_text.into();
 561            let original_indent_column = original_indent_columns.get(ix).copied().unwrap_or(0);
 562            cursor.seek(&range.start, Bias::Right, &());
 563            if cursor.item().is_none() && range.start == *cursor.start() {
 564                cursor.prev(&());
 565            }
 566            let start_excerpt = cursor.item().expect("start offset out of bounds");
 567            let start_overshoot = range.start - cursor.start();
 568            let buffer_start = start_excerpt
 569                .range
 570                .context
 571                .start
 572                .to_offset(&start_excerpt.buffer)
 573                + start_overshoot;
 574            edited_excerpt_ids.push(start_excerpt.id);
 575
 576            cursor.seek(&range.end, Bias::Right, &());
 577            if cursor.item().is_none() && range.end == *cursor.start() {
 578                cursor.prev(&());
 579            }
 580            let end_excerpt = cursor.item().expect("end offset out of bounds");
 581            let end_overshoot = range.end - cursor.start();
 582            let buffer_end = end_excerpt
 583                .range
 584                .context
 585                .start
 586                .to_offset(&end_excerpt.buffer)
 587                + end_overshoot;
 588
 589            if start_excerpt.id == end_excerpt.id {
 590                buffer_edits
 591                    .entry(start_excerpt.buffer_id)
 592                    .or_insert(Vec::new())
 593                    .push(BufferEdit {
 594                        range: buffer_start..buffer_end,
 595                        new_text,
 596                        is_insertion: true,
 597                        original_indent_column,
 598                    });
 599            } else {
 600                edited_excerpt_ids.push(end_excerpt.id);
 601                let start_excerpt_range = buffer_start
 602                    ..start_excerpt
 603                        .range
 604                        .context
 605                        .end
 606                        .to_offset(&start_excerpt.buffer);
 607                let end_excerpt_range = end_excerpt
 608                    .range
 609                    .context
 610                    .start
 611                    .to_offset(&end_excerpt.buffer)
 612                    ..buffer_end;
 613                buffer_edits
 614                    .entry(start_excerpt.buffer_id)
 615                    .or_insert(Vec::new())
 616                    .push(BufferEdit {
 617                        range: start_excerpt_range,
 618                        new_text: new_text.clone(),
 619                        is_insertion: true,
 620                        original_indent_column,
 621                    });
 622                buffer_edits
 623                    .entry(end_excerpt.buffer_id)
 624                    .or_insert(Vec::new())
 625                    .push(BufferEdit {
 626                        range: end_excerpt_range,
 627                        new_text: new_text.clone(),
 628                        is_insertion: false,
 629                        original_indent_column,
 630                    });
 631
 632                cursor.seek(&range.start, Bias::Right, &());
 633                cursor.next(&());
 634                while let Some(excerpt) = cursor.item() {
 635                    if excerpt.id == end_excerpt.id {
 636                        break;
 637                    }
 638                    buffer_edits
 639                        .entry(excerpt.buffer_id)
 640                        .or_insert(Vec::new())
 641                        .push(BufferEdit {
 642                            range: excerpt.range.context.to_offset(&excerpt.buffer),
 643                            new_text: new_text.clone(),
 644                            is_insertion: false,
 645                            original_indent_column,
 646                        });
 647                    edited_excerpt_ids.push(excerpt.id);
 648                    cursor.next(&());
 649                }
 650            }
 651        }
 652
 653        drop(cursor);
 654        drop(snapshot);
 655        // Non-generic part of edit, hoisted out to avoid blowing up LLVM IR.
 656        fn tail(
 657            this: &mut MultiBuffer,
 658            buffer_edits: HashMap<BufferId, Vec<BufferEdit>>,
 659            autoindent_mode: Option<AutoindentMode>,
 660            edited_excerpt_ids: Vec<ExcerptId>,
 661            cx: &mut ModelContext<MultiBuffer>,
 662        ) {
 663            for (buffer_id, mut edits) in buffer_edits {
 664                edits.sort_unstable_by_key(|edit| edit.range.start);
 665                this.buffers.borrow()[&buffer_id]
 666                    .buffer
 667                    .update(cx, |buffer, cx| {
 668                        let mut edits = edits.into_iter().peekable();
 669                        let mut insertions = Vec::new();
 670                        let mut original_indent_columns = Vec::new();
 671                        let mut deletions = Vec::new();
 672                        let empty_str: Arc<str> = "".into();
 673                        while let Some(BufferEdit {
 674                            mut range,
 675                            new_text,
 676                            mut is_insertion,
 677                            original_indent_column,
 678                        }) = edits.next()
 679                        {
 680                            while let Some(BufferEdit {
 681                                range: next_range,
 682                                is_insertion: next_is_insertion,
 683                                ..
 684                            }) = edits.peek()
 685                            {
 686                                if range.end >= next_range.start {
 687                                    range.end = cmp::max(next_range.end, range.end);
 688                                    is_insertion |= *next_is_insertion;
 689                                    edits.next();
 690                                } else {
 691                                    break;
 692                                }
 693                            }
 694
 695                            if is_insertion {
 696                                original_indent_columns.push(original_indent_column);
 697                                insertions.push((
 698                                    buffer.anchor_before(range.start)
 699                                        ..buffer.anchor_before(range.end),
 700                                    new_text.clone(),
 701                                ));
 702                            } else if !range.is_empty() {
 703                                deletions.push((
 704                                    buffer.anchor_before(range.start)
 705                                        ..buffer.anchor_before(range.end),
 706                                    empty_str.clone(),
 707                                ));
 708                            }
 709                        }
 710
 711                        let deletion_autoindent_mode =
 712                            if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
 713                                Some(AutoindentMode::Block {
 714                                    original_indent_columns: Default::default(),
 715                                })
 716                            } else {
 717                                None
 718                            };
 719                        let insertion_autoindent_mode =
 720                            if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
 721                                Some(AutoindentMode::Block {
 722                                    original_indent_columns,
 723                                })
 724                            } else {
 725                                None
 726                            };
 727
 728                        buffer.edit(deletions, deletion_autoindent_mode, cx);
 729                        buffer.edit(insertions, insertion_autoindent_mode, cx);
 730                    })
 731            }
 732
 733            cx.emit(Event::ExcerptsEdited {
 734                ids: edited_excerpt_ids,
 735            });
 736        }
 737        tail(self, buffer_edits, autoindent_mode, edited_excerpt_ids, cx);
 738    }
 739
 740    pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 741        self.start_transaction_at(Instant::now(), cx)
 742    }
 743
 744    pub fn start_transaction_at(
 745        &mut self,
 746        now: Instant,
 747        cx: &mut ModelContext<Self>,
 748    ) -> Option<TransactionId> {
 749        if let Some(buffer) = self.as_singleton() {
 750            return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 751        }
 752
 753        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 754            buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 755        }
 756        self.history.start_transaction(now)
 757    }
 758
 759    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 760        self.end_transaction_at(Instant::now(), cx)
 761    }
 762
 763    pub fn end_transaction_at(
 764        &mut self,
 765        now: Instant,
 766        cx: &mut ModelContext<Self>,
 767    ) -> Option<TransactionId> {
 768        if let Some(buffer) = self.as_singleton() {
 769            return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
 770        }
 771
 772        let mut buffer_transactions = HashMap::default();
 773        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 774            if let Some(transaction_id) =
 775                buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 776            {
 777                buffer_transactions.insert(buffer.read(cx).remote_id(), transaction_id);
 778            }
 779        }
 780
 781        if self.history.end_transaction(now, buffer_transactions) {
 782            let transaction_id = self.history.group().unwrap();
 783            Some(transaction_id)
 784        } else {
 785            None
 786        }
 787    }
 788
 789    pub fn merge_transactions(
 790        &mut self,
 791        transaction: TransactionId,
 792        destination: TransactionId,
 793        cx: &mut ModelContext<Self>,
 794    ) {
 795        if let Some(buffer) = self.as_singleton() {
 796            buffer.update(cx, |buffer, _| {
 797                buffer.merge_transactions(transaction, destination)
 798            });
 799        } else {
 800            if let Some(transaction) = self.history.forget(transaction) {
 801                if let Some(destination) = self.history.transaction_mut(destination) {
 802                    for (buffer_id, buffer_transaction_id) in transaction.buffer_transactions {
 803                        if let Some(destination_buffer_transaction_id) =
 804                            destination.buffer_transactions.get(&buffer_id)
 805                        {
 806                            if let Some(state) = self.buffers.borrow().get(&buffer_id) {
 807                                state.buffer.update(cx, |buffer, _| {
 808                                    buffer.merge_transactions(
 809                                        buffer_transaction_id,
 810                                        *destination_buffer_transaction_id,
 811                                    )
 812                                });
 813                            }
 814                        } else {
 815                            destination
 816                                .buffer_transactions
 817                                .insert(buffer_id, buffer_transaction_id);
 818                        }
 819                    }
 820                }
 821            }
 822        }
 823    }
 824
 825    pub fn finalize_last_transaction(&mut self, cx: &mut ModelContext<Self>) {
 826        self.history.finalize_last_transaction();
 827        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 828            buffer.update(cx, |buffer, _| {
 829                buffer.finalize_last_transaction();
 830            });
 831        }
 832    }
 833
 834    pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T, cx: &mut ModelContext<Self>)
 835    where
 836        T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
 837    {
 838        self.history
 839            .push_transaction(buffer_transactions, Instant::now(), cx);
 840        self.history.finalize_last_transaction();
 841    }
 842
 843    pub fn group_until_transaction(
 844        &mut self,
 845        transaction_id: TransactionId,
 846        cx: &mut ModelContext<Self>,
 847    ) {
 848        if let Some(buffer) = self.as_singleton() {
 849            buffer.update(cx, |buffer, _| {
 850                buffer.group_until_transaction(transaction_id)
 851            });
 852        } else {
 853            self.history.group_until(transaction_id);
 854        }
 855    }
 856
 857    pub fn set_active_selections(
 858        &mut self,
 859        selections: &[Selection<Anchor>],
 860        line_mode: bool,
 861        cursor_shape: CursorShape,
 862        cx: &mut ModelContext<Self>,
 863    ) {
 864        let mut selections_by_buffer: HashMap<BufferId, Vec<Selection<text::Anchor>>> =
 865            Default::default();
 866        let snapshot = self.read(cx);
 867        let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
 868        for selection in selections {
 869            let start_locator = snapshot.excerpt_locator_for_id(selection.start.excerpt_id);
 870            let end_locator = snapshot.excerpt_locator_for_id(selection.end.excerpt_id);
 871
 872            cursor.seek(&Some(start_locator), Bias::Left, &());
 873            while let Some(excerpt) = cursor.item() {
 874                if excerpt.locator > *end_locator {
 875                    break;
 876                }
 877
 878                let mut start = excerpt.range.context.start;
 879                let mut end = excerpt.range.context.end;
 880                if excerpt.id == selection.start.excerpt_id {
 881                    start = selection.start.text_anchor;
 882                }
 883                if excerpt.id == selection.end.excerpt_id {
 884                    end = selection.end.text_anchor;
 885                }
 886                selections_by_buffer
 887                    .entry(excerpt.buffer_id)
 888                    .or_default()
 889                    .push(Selection {
 890                        id: selection.id,
 891                        start,
 892                        end,
 893                        reversed: selection.reversed,
 894                        goal: selection.goal,
 895                    });
 896
 897                cursor.next(&());
 898            }
 899        }
 900
 901        for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
 902            if !selections_by_buffer.contains_key(buffer_id) {
 903                buffer_state
 904                    .buffer
 905                    .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 906            }
 907        }
 908
 909        for (buffer_id, mut selections) in selections_by_buffer {
 910            self.buffers.borrow()[&buffer_id]
 911                .buffer
 912                .update(cx, |buffer, cx| {
 913                    selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer));
 914                    let mut selections = selections.into_iter().peekable();
 915                    let merged_selections = Arc::from_iter(iter::from_fn(|| {
 916                        let mut selection = selections.next()?;
 917                        while let Some(next_selection) = selections.peek() {
 918                            if selection.end.cmp(&next_selection.start, buffer).is_ge() {
 919                                let next_selection = selections.next().unwrap();
 920                                if next_selection.end.cmp(&selection.end, buffer).is_ge() {
 921                                    selection.end = next_selection.end;
 922                                }
 923                            } else {
 924                                break;
 925                            }
 926                        }
 927                        Some(selection)
 928                    }));
 929                    buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx);
 930                });
 931        }
 932    }
 933
 934    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 935        for buffer in self.buffers.borrow().values() {
 936            buffer
 937                .buffer
 938                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 939        }
 940    }
 941
 942    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 943        let mut transaction_id = None;
 944        if let Some(buffer) = self.as_singleton() {
 945            transaction_id = buffer.update(cx, |buffer, cx| buffer.undo(cx));
 946        } else {
 947            while let Some(transaction) = self.history.pop_undo() {
 948                let mut undone = false;
 949                for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
 950                    if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
 951                        undone |= buffer.update(cx, |buffer, cx| {
 952                            let undo_to = *buffer_transaction_id;
 953                            if let Some(entry) = buffer.peek_undo_stack() {
 954                                *buffer_transaction_id = entry.transaction_id();
 955                            }
 956                            buffer.undo_to_transaction(undo_to, cx)
 957                        });
 958                    }
 959                }
 960
 961                if undone {
 962                    transaction_id = Some(transaction.id);
 963                    break;
 964                }
 965            }
 966        }
 967
 968        if let Some(transaction_id) = transaction_id {
 969            cx.emit(Event::TransactionUndone { transaction_id });
 970        }
 971
 972        transaction_id
 973    }
 974
 975    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 976        if let Some(buffer) = self.as_singleton() {
 977            return buffer.update(cx, |buffer, cx| buffer.redo(cx));
 978        }
 979
 980        while let Some(transaction) = self.history.pop_redo() {
 981            let mut redone = false;
 982            for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
 983                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
 984                    redone |= buffer.update(cx, |buffer, cx| {
 985                        let redo_to = *buffer_transaction_id;
 986                        if let Some(entry) = buffer.peek_redo_stack() {
 987                            *buffer_transaction_id = entry.transaction_id();
 988                        }
 989                        buffer.redo_to_transaction(redo_to, cx)
 990                    });
 991                }
 992            }
 993
 994            if redone {
 995                return Some(transaction.id);
 996            }
 997        }
 998
 999        None
1000    }
1001
1002    pub fn undo_transaction(&mut self, transaction_id: TransactionId, cx: &mut ModelContext<Self>) {
1003        if let Some(buffer) = self.as_singleton() {
1004            buffer.update(cx, |buffer, cx| buffer.undo_transaction(transaction_id, cx));
1005        } else if let Some(transaction) = self.history.remove_from_undo(transaction_id) {
1006            for (buffer_id, transaction_id) in &transaction.buffer_transactions {
1007                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
1008                    buffer.update(cx, |buffer, cx| {
1009                        buffer.undo_transaction(*transaction_id, cx)
1010                    });
1011                }
1012            }
1013        }
1014    }
1015
1016    pub fn stream_excerpts_with_context_lines(
1017        &mut self,
1018        buffer: Model<Buffer>,
1019        ranges: Vec<Range<text::Anchor>>,
1020        context_line_count: u32,
1021        cx: &mut ModelContext<Self>,
1022    ) -> mpsc::Receiver<Range<Anchor>> {
1023        let (buffer_id, buffer_snapshot) =
1024            buffer.update(cx, |buffer, _| (buffer.remote_id(), buffer.snapshot()));
1025
1026        let (mut tx, rx) = mpsc::channel(256);
1027        cx.spawn(move |this, mut cx| async move {
1028            let mut excerpt_ranges = Vec::new();
1029            let mut range_counts = Vec::new();
1030            cx.background_executor()
1031                .scoped(|scope| {
1032                    scope.spawn(async {
1033                        let (ranges, counts) =
1034                            build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
1035                        excerpt_ranges = ranges;
1036                        range_counts = counts;
1037                    });
1038                })
1039                .await;
1040
1041            let mut ranges = ranges.into_iter();
1042            let mut range_counts = range_counts.into_iter();
1043            for excerpt_ranges in excerpt_ranges.chunks(100) {
1044                let excerpt_ids = match this.update(&mut cx, |this, cx| {
1045                    this.push_excerpts(buffer.clone(), excerpt_ranges.iter().cloned(), cx)
1046                }) {
1047                    Ok(excerpt_ids) => excerpt_ids,
1048                    Err(_) => return,
1049                };
1050
1051                for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.by_ref())
1052                {
1053                    for range in ranges.by_ref().take(range_count) {
1054                        let start = Anchor {
1055                            buffer_id: Some(buffer_id),
1056                            excerpt_id: excerpt_id,
1057                            text_anchor: range.start,
1058                        };
1059                        let end = Anchor {
1060                            buffer_id: Some(buffer_id),
1061                            excerpt_id: excerpt_id,
1062                            text_anchor: range.end,
1063                        };
1064                        if tx.send(start..end).await.is_err() {
1065                            break;
1066                        }
1067                    }
1068                }
1069            }
1070        })
1071        .detach();
1072
1073        rx
1074    }
1075
1076    pub fn push_excerpts<O>(
1077        &mut self,
1078        buffer: Model<Buffer>,
1079        ranges: impl IntoIterator<Item = ExcerptRange<O>>,
1080        cx: &mut ModelContext<Self>,
1081    ) -> Vec<ExcerptId>
1082    where
1083        O: text::ToOffset,
1084    {
1085        self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
1086    }
1087
1088    pub fn push_excerpts_with_context_lines<O>(
1089        &mut self,
1090        buffer: Model<Buffer>,
1091        ranges: Vec<Range<O>>,
1092        context_line_count: u32,
1093        cx: &mut ModelContext<Self>,
1094    ) -> Vec<Range<Anchor>>
1095    where
1096        O: text::ToPoint + text::ToOffset,
1097    {
1098        let buffer_id = buffer.read(cx).remote_id();
1099        let buffer_snapshot = buffer.read(cx).snapshot();
1100        let (excerpt_ranges, range_counts) =
1101            build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
1102
1103        let excerpt_ids = self.push_excerpts(buffer, excerpt_ranges, cx);
1104
1105        let mut anchor_ranges = Vec::new();
1106        let mut ranges = ranges.into_iter();
1107        for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.into_iter()) {
1108            anchor_ranges.extend(ranges.by_ref().take(range_count).map(|range| {
1109                let start = Anchor {
1110                    buffer_id: Some(buffer_id),
1111                    excerpt_id,
1112                    text_anchor: buffer_snapshot.anchor_after(range.start),
1113                };
1114                let end = Anchor {
1115                    buffer_id: Some(buffer_id),
1116                    excerpt_id,
1117                    text_anchor: buffer_snapshot.anchor_after(range.end),
1118                };
1119                start..end
1120            }))
1121        }
1122        anchor_ranges
1123    }
1124
1125    pub fn insert_excerpts_after<O>(
1126        &mut self,
1127        prev_excerpt_id: ExcerptId,
1128        buffer: Model<Buffer>,
1129        ranges: impl IntoIterator<Item = ExcerptRange<O>>,
1130        cx: &mut ModelContext<Self>,
1131    ) -> Vec<ExcerptId>
1132    where
1133        O: text::ToOffset,
1134    {
1135        let mut ids = Vec::new();
1136        let mut next_excerpt_id =
1137            if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {
1138                last_entry.id.0 + 1
1139            } else {
1140                1
1141            };
1142        self.insert_excerpts_with_ids_after(
1143            prev_excerpt_id,
1144            buffer,
1145            ranges.into_iter().map(|range| {
1146                let id = ExcerptId(post_inc(&mut next_excerpt_id));
1147                ids.push(id);
1148                (id, range)
1149            }),
1150            cx,
1151        );
1152        ids
1153    }
1154
1155    pub fn insert_excerpts_with_ids_after<O>(
1156        &mut self,
1157        prev_excerpt_id: ExcerptId,
1158        buffer: Model<Buffer>,
1159        ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
1160        cx: &mut ModelContext<Self>,
1161    ) where
1162        O: text::ToOffset,
1163    {
1164        assert_eq!(self.history.transaction_depth, 0);
1165        let mut ranges = ranges.into_iter().peekable();
1166        if ranges.peek().is_none() {
1167            return Default::default();
1168        }
1169
1170        self.sync(cx);
1171
1172        let buffer_id = buffer.read(cx).remote_id();
1173        let buffer_snapshot = buffer.read(cx).snapshot();
1174
1175        let mut buffers = self.buffers.borrow_mut();
1176        let buffer_state = buffers.entry(buffer_id).or_insert_with(|| BufferState {
1177            last_version: buffer_snapshot.version().clone(),
1178            last_parse_count: buffer_snapshot.parse_count(),
1179            last_selections_update_count: buffer_snapshot.selections_update_count(),
1180            last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
1181            last_file_update_count: buffer_snapshot.file_update_count(),
1182            last_git_diff_update_count: buffer_snapshot.git_diff_update_count(),
1183            excerpts: Default::default(),
1184            _subscriptions: [
1185                cx.observe(&buffer, |_, _, cx| cx.notify()),
1186                cx.subscribe(&buffer, Self::on_buffer_event),
1187            ],
1188            buffer: buffer.clone(),
1189        });
1190
1191        let mut snapshot = self.snapshot.borrow_mut();
1192
1193        let mut prev_locator = snapshot.excerpt_locator_for_id(prev_excerpt_id).clone();
1194        let mut new_excerpt_ids = mem::take(&mut snapshot.excerpt_ids);
1195        let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1196        let mut new_excerpts = cursor.slice(&prev_locator, Bias::Right, &());
1197        prev_locator = cursor.start().unwrap_or(Locator::min_ref()).clone();
1198
1199        let edit_start = new_excerpts.summary().text.len;
1200        new_excerpts.update_last(
1201            |excerpt| {
1202                excerpt.has_trailing_newline = true;
1203            },
1204            &(),
1205        );
1206
1207        let next_locator = if let Some(excerpt) = cursor.item() {
1208            excerpt.locator.clone()
1209        } else {
1210            Locator::max()
1211        };
1212
1213        let mut excerpts = Vec::new();
1214        while let Some((id, range)) = ranges.next() {
1215            let locator = Locator::between(&prev_locator, &next_locator);
1216            if let Err(ix) = buffer_state.excerpts.binary_search(&locator) {
1217                buffer_state.excerpts.insert(ix, locator.clone());
1218            }
1219            let range = ExcerptRange {
1220                context: buffer_snapshot.anchor_before(&range.context.start)
1221                    ..buffer_snapshot.anchor_after(&range.context.end),
1222                primary: range.primary.map(|primary| {
1223                    buffer_snapshot.anchor_before(&primary.start)
1224                        ..buffer_snapshot.anchor_after(&primary.end)
1225                }),
1226            };
1227            excerpts.push((id, range.clone()));
1228            let excerpt = Excerpt::new(
1229                id,
1230                locator.clone(),
1231                buffer_id,
1232                buffer_snapshot.clone(),
1233                range,
1234                ranges.peek().is_some() || cursor.item().is_some(),
1235            );
1236            new_excerpts.push(excerpt, &());
1237            prev_locator = locator.clone();
1238
1239            if let Some(last_mapping_entry) = new_excerpt_ids.last() {
1240                assert!(id > last_mapping_entry.id, "excerpt ids must be increasing");
1241            }
1242            new_excerpt_ids.push(ExcerptIdMapping { id, locator }, &());
1243        }
1244
1245        let edit_end = new_excerpts.summary().text.len;
1246
1247        let suffix = cursor.suffix(&());
1248        let changed_trailing_excerpt = suffix.is_empty();
1249        new_excerpts.append(suffix, &());
1250        drop(cursor);
1251        snapshot.excerpts = new_excerpts;
1252        snapshot.excerpt_ids = new_excerpt_ids;
1253        if changed_trailing_excerpt {
1254            snapshot.trailing_excerpt_update_count += 1;
1255        }
1256
1257        self.subscriptions.publish_mut([Edit {
1258            old: edit_start..edit_start,
1259            new: edit_start..edit_end,
1260        }]);
1261        cx.emit(Event::Edited {
1262            singleton_buffer_edited: false,
1263        });
1264        cx.emit(Event::ExcerptsAdded {
1265            buffer,
1266            predecessor: prev_excerpt_id,
1267            excerpts,
1268        });
1269        cx.notify();
1270    }
1271
1272    pub fn clear(&mut self, cx: &mut ModelContext<Self>) {
1273        self.sync(cx);
1274        let ids = self.excerpt_ids();
1275        self.buffers.borrow_mut().clear();
1276        let mut snapshot = self.snapshot.borrow_mut();
1277        let prev_len = snapshot.len();
1278        snapshot.excerpts = Default::default();
1279        snapshot.trailing_excerpt_update_count += 1;
1280        snapshot.is_dirty = false;
1281        snapshot.has_conflict = false;
1282
1283        self.subscriptions.publish_mut([Edit {
1284            old: 0..prev_len,
1285            new: 0..0,
1286        }]);
1287        cx.emit(Event::Edited {
1288            singleton_buffer_edited: false,
1289        });
1290        cx.emit(Event::ExcerptsRemoved { ids });
1291        cx.notify();
1292    }
1293
1294    pub fn excerpts_for_buffer(
1295        &self,
1296        buffer: &Model<Buffer>,
1297        cx: &AppContext,
1298    ) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
1299        let mut excerpts = Vec::new();
1300        let snapshot = self.read(cx);
1301        let buffers = self.buffers.borrow();
1302        let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1303        for locator in buffers
1304            .get(&buffer.read(cx).remote_id())
1305            .map(|state| &state.excerpts)
1306            .into_iter()
1307            .flatten()
1308        {
1309            cursor.seek_forward(&Some(locator), Bias::Left, &());
1310            if let Some(excerpt) = cursor.item() {
1311                if excerpt.locator == *locator {
1312                    excerpts.push((excerpt.id, excerpt.range.clone()));
1313                }
1314            }
1315        }
1316
1317        excerpts
1318    }
1319
1320    pub fn excerpt_buffer_ids(&self) -> Vec<BufferId> {
1321        self.snapshot
1322            .borrow()
1323            .excerpts
1324            .iter()
1325            .map(|entry| entry.buffer_id)
1326            .collect()
1327    }
1328
1329    pub fn excerpt_ids(&self) -> Vec<ExcerptId> {
1330        self.snapshot
1331            .borrow()
1332            .excerpts
1333            .iter()
1334            .map(|entry| entry.id)
1335            .collect()
1336    }
1337
1338    pub fn excerpt_containing(
1339        &self,
1340        position: impl ToOffset,
1341        cx: &AppContext,
1342    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1343        let snapshot = self.read(cx);
1344        let position = position.to_offset(&snapshot);
1345
1346        let mut cursor = snapshot.excerpts.cursor::<usize>();
1347        cursor.seek(&position, Bias::Right, &());
1348        cursor
1349            .item()
1350            .or_else(|| snapshot.excerpts.last())
1351            .map(|excerpt| {
1352                (
1353                    excerpt.id,
1354                    self.buffers
1355                        .borrow()
1356                        .get(&excerpt.buffer_id)
1357                        .unwrap()
1358                        .buffer
1359                        .clone(),
1360                    excerpt.range.context.clone(),
1361                )
1362            })
1363    }
1364
1365    // If point is at the end of the buffer, the last excerpt is returned
1366    pub fn point_to_buffer_offset<T: ToOffset>(
1367        &self,
1368        point: T,
1369        cx: &AppContext,
1370    ) -> Option<(Model<Buffer>, usize, ExcerptId)> {
1371        let snapshot = self.read(cx);
1372        let offset = point.to_offset(&snapshot);
1373        let mut cursor = snapshot.excerpts.cursor::<usize>();
1374        cursor.seek(&offset, Bias::Right, &());
1375        if cursor.item().is_none() {
1376            cursor.prev(&());
1377        }
1378
1379        cursor.item().map(|excerpt| {
1380            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1381            let buffer_point = excerpt_start + offset - *cursor.start();
1382            let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1383
1384            (buffer, buffer_point, excerpt.id)
1385        })
1386    }
1387
1388    pub fn range_to_buffer_ranges<T: ToOffset>(
1389        &self,
1390        range: Range<T>,
1391        cx: &AppContext,
1392    ) -> Vec<(Model<Buffer>, Range<usize>, ExcerptId)> {
1393        let snapshot = self.read(cx);
1394        let start = range.start.to_offset(&snapshot);
1395        let end = range.end.to_offset(&snapshot);
1396
1397        let mut result = Vec::new();
1398        let mut cursor = snapshot.excerpts.cursor::<usize>();
1399        cursor.seek(&start, Bias::Right, &());
1400        if cursor.item().is_none() {
1401            cursor.prev(&());
1402        }
1403
1404        while let Some(excerpt) = cursor.item() {
1405            if *cursor.start() > end {
1406                break;
1407            }
1408
1409            let mut end_before_newline = cursor.end(&());
1410            if excerpt.has_trailing_newline {
1411                end_before_newline -= 1;
1412            }
1413            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1414            let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
1415            let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
1416            let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1417            result.push((buffer, start..end, excerpt.id));
1418            cursor.next(&());
1419        }
1420
1421        result
1422    }
1423
1424    pub fn remove_excerpts(
1425        &mut self,
1426        excerpt_ids: impl IntoIterator<Item = ExcerptId>,
1427        cx: &mut ModelContext<Self>,
1428    ) {
1429        self.sync(cx);
1430        let ids = excerpt_ids.into_iter().collect::<Vec<_>>();
1431        if ids.is_empty() {
1432            return;
1433        }
1434
1435        let mut buffers = self.buffers.borrow_mut();
1436        let mut snapshot = self.snapshot.borrow_mut();
1437        let mut new_excerpts = SumTree::new();
1438        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1439        let mut edits = Vec::new();
1440        let mut excerpt_ids = ids.iter().copied().peekable();
1441
1442        while let Some(excerpt_id) = excerpt_ids.next() {
1443            // Seek to the next excerpt to remove, preserving any preceding excerpts.
1444            let locator = snapshot.excerpt_locator_for_id(excerpt_id);
1445            new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1446
1447            if let Some(mut excerpt) = cursor.item() {
1448                if excerpt.id != excerpt_id {
1449                    continue;
1450                }
1451                let mut old_start = cursor.start().1;
1452
1453                // Skip over the removed excerpt.
1454                'remove_excerpts: loop {
1455                    if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
1456                        buffer_state.excerpts.retain(|l| l != &excerpt.locator);
1457                        if buffer_state.excerpts.is_empty() {
1458                            buffers.remove(&excerpt.buffer_id);
1459                        }
1460                    }
1461                    cursor.next(&());
1462
1463                    // Skip over any subsequent excerpts that are also removed.
1464                    if let Some(&next_excerpt_id) = excerpt_ids.peek() {
1465                        let next_locator = snapshot.excerpt_locator_for_id(next_excerpt_id);
1466                        if let Some(next_excerpt) = cursor.item() {
1467                            if next_excerpt.locator == *next_locator {
1468                                excerpt_ids.next();
1469                                excerpt = next_excerpt;
1470                                continue 'remove_excerpts;
1471                            }
1472                        }
1473                    }
1474
1475                    break;
1476                }
1477
1478                // When removing the last excerpt, remove the trailing newline from
1479                // the previous excerpt.
1480                if cursor.item().is_none() && old_start > 0 {
1481                    old_start -= 1;
1482                    new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
1483                }
1484
1485                // Push an edit for the removal of this run of excerpts.
1486                let old_end = cursor.start().1;
1487                let new_start = new_excerpts.summary().text.len;
1488                edits.push(Edit {
1489                    old: old_start..old_end,
1490                    new: new_start..new_start,
1491                });
1492            }
1493        }
1494        let suffix = cursor.suffix(&());
1495        let changed_trailing_excerpt = suffix.is_empty();
1496        new_excerpts.append(suffix, &());
1497        drop(cursor);
1498        snapshot.excerpts = new_excerpts;
1499
1500        if changed_trailing_excerpt {
1501            snapshot.trailing_excerpt_update_count += 1;
1502        }
1503
1504        self.subscriptions.publish_mut(edits);
1505        cx.emit(Event::Edited {
1506            singleton_buffer_edited: false,
1507        });
1508        cx.emit(Event::ExcerptsRemoved { ids });
1509        cx.notify();
1510    }
1511
1512    pub fn wait_for_anchors<'a>(
1513        &self,
1514        anchors: impl 'a + Iterator<Item = Anchor>,
1515        cx: &mut ModelContext<Self>,
1516    ) -> impl 'static + Future<Output = Result<()>> {
1517        let borrow = self.buffers.borrow();
1518        let mut error = None;
1519        let mut futures = Vec::new();
1520        for anchor in anchors {
1521            if let Some(buffer_id) = anchor.buffer_id {
1522                if let Some(buffer) = borrow.get(&buffer_id) {
1523                    buffer.buffer.update(cx, |buffer, _| {
1524                        futures.push(buffer.wait_for_anchors([anchor.text_anchor]))
1525                    });
1526                } else {
1527                    error = Some(anyhow!(
1528                        "buffer {buffer_id} is not part of this multi-buffer"
1529                    ));
1530                    break;
1531                }
1532            }
1533        }
1534        async move {
1535            if let Some(error) = error {
1536                Err(error)?;
1537            }
1538            for future in futures {
1539                future.await?;
1540            }
1541            Ok(())
1542        }
1543    }
1544
1545    pub fn text_anchor_for_position<T: ToOffset>(
1546        &self,
1547        position: T,
1548        cx: &AppContext,
1549    ) -> Option<(Model<Buffer>, language::Anchor)> {
1550        let snapshot = self.read(cx);
1551        let anchor = snapshot.anchor_before(position);
1552        let buffer = self
1553            .buffers
1554            .borrow()
1555            .get(&anchor.buffer_id?)?
1556            .buffer
1557            .clone();
1558        Some((buffer, anchor.text_anchor))
1559    }
1560
1561    fn on_buffer_event(
1562        &mut self,
1563        buffer: Model<Buffer>,
1564        event: &language::Event,
1565        cx: &mut ModelContext<Self>,
1566    ) {
1567        cx.emit(match event {
1568            language::Event::Edited => Event::Edited {
1569                singleton_buffer_edited: true,
1570            },
1571            language::Event::DirtyChanged => Event::DirtyChanged,
1572            language::Event::Saved => Event::Saved,
1573            language::Event::FileHandleChanged => Event::FileHandleChanged,
1574            language::Event::Reloaded => Event::Reloaded,
1575            language::Event::DiffBaseChanged => Event::DiffBaseChanged,
1576            language::Event::DiffUpdated => Event::DiffUpdated { buffer },
1577            language::Event::LanguageChanged => Event::LanguageChanged,
1578            language::Event::Reparsed => Event::Reparsed,
1579            language::Event::DiagnosticsUpdated => Event::DiagnosticsUpdated,
1580            language::Event::Closed => Event::Closed,
1581            language::Event::CapabilityChanged => {
1582                self.capability = buffer.read(cx).capability();
1583                Event::CapabilityChanged
1584            }
1585
1586            //
1587            language::Event::Operation(_) => return,
1588        });
1589    }
1590
1591    pub fn all_buffers(&self) -> HashSet<Model<Buffer>> {
1592        self.buffers
1593            .borrow()
1594            .values()
1595            .map(|state| state.buffer.clone())
1596            .collect()
1597    }
1598
1599    pub fn buffer(&self, buffer_id: BufferId) -> Option<Model<Buffer>> {
1600        self.buffers
1601            .borrow()
1602            .get(&buffer_id)
1603            .map(|state| state.buffer.clone())
1604    }
1605
1606    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1607        self.point_to_buffer_offset(point, cx)
1608            .and_then(|(buffer, offset, _)| buffer.read(cx).language_at(offset))
1609    }
1610
1611    pub fn settings_at<'a, T: ToOffset>(
1612        &self,
1613        point: T,
1614        cx: &'a AppContext,
1615    ) -> &'a LanguageSettings {
1616        let mut language = None;
1617        let mut file = None;
1618        if let Some((buffer, offset, _)) = self.point_to_buffer_offset(point, cx) {
1619            let buffer = buffer.read(cx);
1620            language = buffer.language_at(offset);
1621            file = buffer.file();
1622        }
1623        language_settings(language.as_ref(), file, cx)
1624    }
1625
1626    pub fn for_each_buffer(&self, mut f: impl FnMut(&Model<Buffer>)) {
1627        self.buffers
1628            .borrow()
1629            .values()
1630            .for_each(|state| f(&state.buffer))
1631    }
1632
1633    pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1634        if let Some(title) = self.title.as_ref() {
1635            return title.into();
1636        }
1637
1638        if let Some(buffer) = self.as_singleton() {
1639            if let Some(file) = buffer.read(cx).file() {
1640                return file.file_name(cx).to_string_lossy();
1641            }
1642        }
1643
1644        "untitled".into()
1645    }
1646
1647    pub fn set_title(&mut self, title: String, cx: &mut ModelContext<Self>) {
1648        self.title = Some(title);
1649        cx.notify();
1650    }
1651
1652    #[cfg(any(test, feature = "test-support"))]
1653    pub fn is_parsing(&self, cx: &AppContext) -> bool {
1654        self.as_singleton().unwrap().read(cx).is_parsing()
1655    }
1656
1657    pub fn expand_excerpts(
1658        &mut self,
1659        ids: impl IntoIterator<Item = ExcerptId>,
1660        line_count: u32,
1661        direction: ExpandExcerptDirection,
1662        cx: &mut ModelContext<Self>,
1663    ) {
1664        if line_count == 0 {
1665            return;
1666        }
1667        self.sync(cx);
1668
1669        let snapshot = self.snapshot(cx);
1670        let locators = snapshot.excerpt_locators_for_ids(ids);
1671        let mut new_excerpts = SumTree::new();
1672        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1673        let mut edits = Vec::<Edit<usize>>::new();
1674
1675        for locator in &locators {
1676            let prefix = cursor.slice(&Some(locator), Bias::Left, &());
1677            new_excerpts.append(prefix, &());
1678
1679            let mut excerpt = cursor.item().unwrap().clone();
1680            let old_text_len = excerpt.text_summary.len;
1681
1682            let up_line_count = if direction.should_expand_up() {
1683                line_count
1684            } else {
1685                0
1686            };
1687
1688            let start_row = excerpt
1689                .range
1690                .context
1691                .start
1692                .to_point(&excerpt.buffer)
1693                .row
1694                .saturating_sub(up_line_count);
1695            let start_point = Point::new(start_row, 0);
1696            excerpt.range.context.start = excerpt.buffer.anchor_before(start_point);
1697
1698            let down_line_count = if direction.should_expand_down() {
1699                line_count
1700            } else {
1701                0
1702            };
1703
1704            let mut end_point = excerpt.buffer.clip_point(
1705                excerpt.range.context.end.to_point(&excerpt.buffer)
1706                    + Point::new(down_line_count, 0),
1707                Bias::Left,
1708            );
1709            end_point.column = excerpt.buffer.line_len(end_point.row);
1710            excerpt.range.context.end = excerpt.buffer.anchor_after(end_point);
1711            excerpt.max_buffer_row = end_point.row;
1712
1713            excerpt.text_summary = excerpt
1714                .buffer
1715                .text_summary_for_range(excerpt.range.context.clone());
1716
1717            let new_start_offset = new_excerpts.summary().text.len;
1718            let old_start_offset = cursor.start().1;
1719            let edit = Edit {
1720                old: old_start_offset..old_start_offset + old_text_len,
1721                new: new_start_offset..new_start_offset + excerpt.text_summary.len,
1722            };
1723
1724            if let Some(last_edit) = edits.last_mut() {
1725                if last_edit.old.end == edit.old.start {
1726                    last_edit.old.end = edit.old.end;
1727                    last_edit.new.end = edit.new.end;
1728                } else {
1729                    edits.push(edit);
1730                }
1731            } else {
1732                edits.push(edit);
1733            }
1734
1735            new_excerpts.push(excerpt, &());
1736
1737            cursor.next(&());
1738        }
1739
1740        new_excerpts.append(cursor.suffix(&()), &());
1741
1742        drop(cursor);
1743        self.snapshot.borrow_mut().excerpts = new_excerpts;
1744
1745        self.subscriptions.publish_mut(edits);
1746        cx.emit(Event::Edited {
1747            singleton_buffer_edited: false,
1748        });
1749        cx.notify();
1750    }
1751
1752    fn sync(&self, cx: &AppContext) {
1753        let mut snapshot = self.snapshot.borrow_mut();
1754        let mut excerpts_to_edit = Vec::new();
1755        let mut reparsed = false;
1756        let mut diagnostics_updated = false;
1757        let mut git_diff_updated = false;
1758        let mut is_dirty = false;
1759        let mut has_conflict = false;
1760        let mut edited = false;
1761        let mut buffers = self.buffers.borrow_mut();
1762        for buffer_state in buffers.values_mut() {
1763            let buffer = buffer_state.buffer.read(cx);
1764            let version = buffer.version();
1765            let parse_count = buffer.parse_count();
1766            let selections_update_count = buffer.selections_update_count();
1767            let diagnostics_update_count = buffer.diagnostics_update_count();
1768            let file_update_count = buffer.file_update_count();
1769            let git_diff_update_count = buffer.git_diff_update_count();
1770
1771            let buffer_edited = version.changed_since(&buffer_state.last_version);
1772            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1773            let buffer_selections_updated =
1774                selections_update_count > buffer_state.last_selections_update_count;
1775            let buffer_diagnostics_updated =
1776                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1777            let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1778            let buffer_git_diff_updated =
1779                git_diff_update_count > buffer_state.last_git_diff_update_count;
1780            if buffer_edited
1781                || buffer_reparsed
1782                || buffer_selections_updated
1783                || buffer_diagnostics_updated
1784                || buffer_file_updated
1785                || buffer_git_diff_updated
1786            {
1787                buffer_state.last_version = version;
1788                buffer_state.last_parse_count = parse_count;
1789                buffer_state.last_selections_update_count = selections_update_count;
1790                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1791                buffer_state.last_file_update_count = file_update_count;
1792                buffer_state.last_git_diff_update_count = git_diff_update_count;
1793                excerpts_to_edit.extend(
1794                    buffer_state
1795                        .excerpts
1796                        .iter()
1797                        .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1798                );
1799            }
1800
1801            edited |= buffer_edited;
1802            reparsed |= buffer_reparsed;
1803            diagnostics_updated |= buffer_diagnostics_updated;
1804            git_diff_updated |= buffer_git_diff_updated;
1805            is_dirty |= buffer.is_dirty();
1806            has_conflict |= buffer.has_conflict();
1807        }
1808        if edited {
1809            snapshot.edit_count += 1;
1810        }
1811        if reparsed {
1812            snapshot.parse_count += 1;
1813        }
1814        if diagnostics_updated {
1815            snapshot.diagnostics_update_count += 1;
1816        }
1817        if git_diff_updated {
1818            snapshot.git_diff_update_count += 1;
1819        }
1820        snapshot.is_dirty = is_dirty;
1821        snapshot.has_conflict = has_conflict;
1822
1823        excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1824
1825        let mut edits = Vec::new();
1826        let mut new_excerpts = SumTree::new();
1827        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1828
1829        for (locator, buffer, buffer_edited) in excerpts_to_edit {
1830            new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1831            let old_excerpt = cursor.item().unwrap();
1832            let buffer = buffer.read(cx);
1833            let buffer_id = buffer.remote_id();
1834
1835            let mut new_excerpt;
1836            if buffer_edited {
1837                edits.extend(
1838                    buffer
1839                        .edits_since_in_range::<usize>(
1840                            old_excerpt.buffer.version(),
1841                            old_excerpt.range.context.clone(),
1842                        )
1843                        .map(|mut edit| {
1844                            let excerpt_old_start = cursor.start().1;
1845                            let excerpt_new_start = new_excerpts.summary().text.len;
1846                            edit.old.start += excerpt_old_start;
1847                            edit.old.end += excerpt_old_start;
1848                            edit.new.start += excerpt_new_start;
1849                            edit.new.end += excerpt_new_start;
1850                            edit
1851                        }),
1852                );
1853
1854                new_excerpt = Excerpt::new(
1855                    old_excerpt.id,
1856                    locator.clone(),
1857                    buffer_id,
1858                    buffer.snapshot(),
1859                    old_excerpt.range.clone(),
1860                    old_excerpt.has_trailing_newline,
1861                );
1862            } else {
1863                new_excerpt = old_excerpt.clone();
1864                new_excerpt.buffer = buffer.snapshot();
1865            }
1866
1867            new_excerpts.push(new_excerpt, &());
1868            cursor.next(&());
1869        }
1870        new_excerpts.append(cursor.suffix(&()), &());
1871
1872        drop(cursor);
1873        snapshot.excerpts = new_excerpts;
1874
1875        self.subscriptions.publish(edits);
1876    }
1877}
1878
1879#[cfg(any(test, feature = "test-support"))]
1880impl MultiBuffer {
1881    pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> Model<Self> {
1882        let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1883        cx.new_model(|cx| Self::singleton(buffer, cx))
1884    }
1885
1886    pub fn build_multi<const COUNT: usize>(
1887        excerpts: [(&str, Vec<Range<Point>>); COUNT],
1888        cx: &mut gpui::AppContext,
1889    ) -> Model<Self> {
1890        let multi = cx.new_model(|_| Self::new(0, Capability::ReadWrite));
1891        for (text, ranges) in excerpts {
1892            let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1893            let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
1894                context: range,
1895                primary: None,
1896            });
1897            multi.update(cx, |multi, cx| {
1898                multi.push_excerpts(buffer, excerpt_ranges, cx)
1899            });
1900        }
1901
1902        multi
1903    }
1904
1905    pub fn build_from_buffer(buffer: Model<Buffer>, cx: &mut gpui::AppContext) -> Model<Self> {
1906        cx.new_model(|cx| Self::singleton(buffer, cx))
1907    }
1908
1909    pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> Model<Self> {
1910        cx.new_model(|cx| {
1911            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
1912            let mutation_count = rng.gen_range(1..=5);
1913            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1914            multibuffer
1915        })
1916    }
1917
1918    pub fn randomly_edit(
1919        &mut self,
1920        rng: &mut impl rand::Rng,
1921        edit_count: usize,
1922        cx: &mut ModelContext<Self>,
1923    ) {
1924        use util::RandomCharIter;
1925
1926        let snapshot = self.read(cx);
1927        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1928        let mut last_end = None;
1929        for _ in 0..edit_count {
1930            if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1931                break;
1932            }
1933
1934            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1935            let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1936            let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1937            last_end = Some(end);
1938
1939            let mut range = start..end;
1940            if rng.gen_bool(0.2) {
1941                mem::swap(&mut range.start, &mut range.end);
1942            }
1943
1944            let new_text_len = rng.gen_range(0..10);
1945            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1946
1947            edits.push((range, new_text.into()));
1948        }
1949        log::info!("mutating multi-buffer with {:?}", edits);
1950        drop(snapshot);
1951
1952        self.edit(edits, None, cx);
1953    }
1954
1955    pub fn randomly_edit_excerpts(
1956        &mut self,
1957        rng: &mut impl rand::Rng,
1958        mutation_count: usize,
1959        cx: &mut ModelContext<Self>,
1960    ) {
1961        use rand::prelude::*;
1962        use std::env;
1963        use util::RandomCharIter;
1964
1965        let max_excerpts = env::var("MAX_EXCERPTS")
1966            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1967            .unwrap_or(5);
1968
1969        let mut buffers = Vec::new();
1970        for _ in 0..mutation_count {
1971            if rng.gen_bool(0.05) {
1972                log::info!("Clearing multi-buffer");
1973                self.clear(cx);
1974                continue;
1975            } else if rng.gen_bool(0.1) && !self.excerpt_ids().is_empty() {
1976                let ids = self.excerpt_ids();
1977                let mut excerpts = HashSet::default();
1978                for _ in 0..rng.gen_range(0..ids.len()) {
1979                    excerpts.extend(ids.choose(rng).copied());
1980                }
1981
1982                let line_count = rng.gen_range(0..5);
1983
1984                log::info!("Expanding excerpts {excerpts:?} by {line_count} lines");
1985
1986                self.expand_excerpts(
1987                    excerpts.iter().cloned(),
1988                    line_count,
1989                    ExpandExcerptDirection::UpAndDown,
1990                    cx,
1991                );
1992                continue;
1993            }
1994
1995            let excerpt_ids = self.excerpt_ids();
1996            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1997                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1998                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1999                    buffers.push(cx.new_model(|cx| Buffer::local(text, cx)));
2000                    let buffer = buffers.last().unwrap().read(cx);
2001                    log::info!(
2002                        "Creating new buffer {} with text: {:?}",
2003                        buffer.remote_id(),
2004                        buffer.text()
2005                    );
2006                    buffers.last().unwrap().clone()
2007                } else {
2008                    self.buffers
2009                        .borrow()
2010                        .values()
2011                        .choose(rng)
2012                        .unwrap()
2013                        .buffer
2014                        .clone()
2015                };
2016
2017                let buffer = buffer_handle.read(cx);
2018                let buffer_text = buffer.text();
2019                let ranges = (0..rng.gen_range(0..5))
2020                    .map(|_| {
2021                        let end_ix =
2022                            buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2023                        let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2024                        ExcerptRange {
2025                            context: start_ix..end_ix,
2026                            primary: None,
2027                        }
2028                    })
2029                    .collect::<Vec<_>>();
2030                log::info!(
2031                    "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
2032                    buffer_handle.read(cx).remote_id(),
2033                    ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
2034                    ranges
2035                        .iter()
2036                        .map(|r| &buffer_text[r.context.clone()])
2037                        .collect::<Vec<_>>()
2038                );
2039
2040                let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
2041                log::info!("Inserted with ids: {:?}", excerpt_id);
2042            } else {
2043                let remove_count = rng.gen_range(1..=excerpt_ids.len());
2044                let mut excerpts_to_remove = excerpt_ids
2045                    .choose_multiple(rng, remove_count)
2046                    .cloned()
2047                    .collect::<Vec<_>>();
2048                let snapshot = self.snapshot.borrow();
2049                excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2050                drop(snapshot);
2051                log::info!("Removing excerpts {:?}", excerpts_to_remove);
2052                self.remove_excerpts(excerpts_to_remove, cx);
2053            }
2054        }
2055    }
2056
2057    pub fn randomly_mutate(
2058        &mut self,
2059        rng: &mut impl rand::Rng,
2060        mutation_count: usize,
2061        cx: &mut ModelContext<Self>,
2062    ) {
2063        use rand::prelude::*;
2064
2065        if rng.gen_bool(0.7) || self.singleton {
2066            let buffer = self
2067                .buffers
2068                .borrow()
2069                .values()
2070                .choose(rng)
2071                .map(|state| state.buffer.clone());
2072
2073            if let Some(buffer) = buffer {
2074                buffer.update(cx, |buffer, cx| {
2075                    if rng.gen() {
2076                        buffer.randomly_edit(rng, mutation_count, cx);
2077                    } else {
2078                        buffer.randomly_undo_redo(rng, cx);
2079                    }
2080                });
2081            } else {
2082                self.randomly_edit(rng, mutation_count, cx);
2083            }
2084        } else {
2085            self.randomly_edit_excerpts(rng, mutation_count, cx);
2086        }
2087
2088        self.check_invariants(cx);
2089    }
2090
2091    fn check_invariants(&self, cx: &mut ModelContext<Self>) {
2092        let snapshot = self.read(cx);
2093        let excerpts = snapshot.excerpts.items(&());
2094        let excerpt_ids = snapshot.excerpt_ids.items(&());
2095
2096        for (ix, excerpt) in excerpts.iter().enumerate() {
2097            if ix == 0 {
2098                if excerpt.locator <= Locator::min() {
2099                    panic!("invalid first excerpt locator {:?}", excerpt.locator);
2100                }
2101            } else {
2102                if excerpt.locator <= excerpts[ix - 1].locator {
2103                    panic!("excerpts are out-of-order: {:?}", excerpts);
2104                }
2105            }
2106        }
2107
2108        for (ix, entry) in excerpt_ids.iter().enumerate() {
2109            if ix == 0 {
2110                if entry.id.cmp(&ExcerptId::min(), &snapshot).is_le() {
2111                    panic!("invalid first excerpt id {:?}", entry.id);
2112                }
2113            } else {
2114                if entry.id <= excerpt_ids[ix - 1].id {
2115                    panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
2116                }
2117            }
2118        }
2119    }
2120}
2121
2122impl EventEmitter<Event> for MultiBuffer {}
2123
2124impl MultiBufferSnapshot {
2125    pub fn text(&self) -> String {
2126        self.chunks(0..self.len(), false)
2127            .map(|chunk| chunk.text)
2128            .collect()
2129    }
2130
2131    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
2132        let mut offset = position.to_offset(self);
2133        let mut cursor = self.excerpts.cursor::<usize>();
2134        cursor.seek(&offset, Bias::Left, &());
2135        let mut excerpt_chunks = cursor.item().map(|excerpt| {
2136            let end_before_footer = cursor.start() + excerpt.text_summary.len;
2137            let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2138            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
2139            excerpt.buffer.reversed_chunks_in_range(start..end)
2140        });
2141        iter::from_fn(move || {
2142            if offset == *cursor.start() {
2143                cursor.prev(&());
2144                let excerpt = cursor.item()?;
2145                excerpt_chunks = Some(
2146                    excerpt
2147                        .buffer
2148                        .reversed_chunks_in_range(excerpt.range.context.clone()),
2149                );
2150            }
2151
2152            let excerpt = cursor.item().unwrap();
2153            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
2154                offset -= 1;
2155                Some("\n")
2156            } else {
2157                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
2158                offset -= chunk.len();
2159                Some(chunk)
2160            }
2161        })
2162        .flat_map(|c| c.chars().rev())
2163    }
2164
2165    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
2166        let offset = position.to_offset(self);
2167        self.text_for_range(offset..self.len())
2168            .flat_map(|chunk| chunk.chars())
2169    }
2170
2171    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
2172        self.chunks(range, false).map(|chunk| chunk.text)
2173    }
2174
2175    pub fn is_line_blank(&self, row: MultiBufferRow) -> bool {
2176        self.text_for_range(Point::new(row.0, 0)..Point::new(row.0, self.line_len(row)))
2177            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
2178    }
2179
2180    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
2181    where
2182        T: ToOffset,
2183    {
2184        let position = position.to_offset(self);
2185        position == self.clip_offset(position, Bias::Left)
2186            && self
2187                .bytes_in_range(position..self.len())
2188                .flatten()
2189                .copied()
2190                .take(needle.len())
2191                .eq(needle.bytes())
2192    }
2193
2194    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2195        let mut start = start.to_offset(self);
2196        let mut end = start;
2197        let mut next_chars = self.chars_at(start).peekable();
2198        let mut prev_chars = self.reversed_chars_at(start).peekable();
2199
2200        let scope = self.language_scope_at(start);
2201        let kind = |c| char_kind(&scope, c);
2202        let word_kind = cmp::max(
2203            prev_chars.peek().copied().map(kind),
2204            next_chars.peek().copied().map(kind),
2205        );
2206
2207        for ch in prev_chars {
2208            if Some(kind(ch)) == word_kind && ch != '\n' {
2209                start -= ch.len_utf8();
2210            } else {
2211                break;
2212            }
2213        }
2214
2215        for ch in next_chars {
2216            if Some(kind(ch)) == word_kind && ch != '\n' {
2217                end += ch.len_utf8();
2218            } else {
2219                break;
2220            }
2221        }
2222
2223        (start..end, word_kind)
2224    }
2225
2226    pub fn as_singleton(&self) -> Option<(&ExcerptId, BufferId, &BufferSnapshot)> {
2227        if self.singleton {
2228            self.excerpts
2229                .iter()
2230                .next()
2231                .map(|e| (&e.id, e.buffer_id, &e.buffer))
2232        } else {
2233            None
2234        }
2235    }
2236
2237    pub fn len(&self) -> usize {
2238        self.excerpts.summary().text.len
2239    }
2240
2241    pub fn is_empty(&self) -> bool {
2242        self.excerpts.summary().text.len == 0
2243    }
2244
2245    pub fn max_buffer_row(&self) -> MultiBufferRow {
2246        self.excerpts.summary().max_buffer_row
2247    }
2248
2249    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
2250        if let Some((_, _, buffer)) = self.as_singleton() {
2251            return buffer.clip_offset(offset, bias);
2252        }
2253
2254        let mut cursor = self.excerpts.cursor::<usize>();
2255        cursor.seek(&offset, Bias::Right, &());
2256        let overshoot = if let Some(excerpt) = cursor.item() {
2257            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2258            let buffer_offset = excerpt
2259                .buffer
2260                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
2261            buffer_offset.saturating_sub(excerpt_start)
2262        } else {
2263            0
2264        };
2265        cursor.start() + overshoot
2266    }
2267
2268    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
2269        if let Some((_, _, buffer)) = self.as_singleton() {
2270            return buffer.clip_point(point, bias);
2271        }
2272
2273        let mut cursor = self.excerpts.cursor::<Point>();
2274        cursor.seek(&point, Bias::Right, &());
2275        let overshoot = if let Some(excerpt) = cursor.item() {
2276            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2277            let buffer_point = excerpt
2278                .buffer
2279                .clip_point(excerpt_start + (point - cursor.start()), bias);
2280            buffer_point.saturating_sub(excerpt_start)
2281        } else {
2282            Point::zero()
2283        };
2284        *cursor.start() + overshoot
2285    }
2286
2287    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
2288        if let Some((_, _, buffer)) = self.as_singleton() {
2289            return buffer.clip_offset_utf16(offset, bias);
2290        }
2291
2292        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
2293        cursor.seek(&offset, Bias::Right, &());
2294        let overshoot = if let Some(excerpt) = cursor.item() {
2295            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2296            let buffer_offset = excerpt
2297                .buffer
2298                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
2299            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
2300        } else {
2301            OffsetUtf16(0)
2302        };
2303        *cursor.start() + overshoot
2304    }
2305
2306    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
2307        if let Some((_, _, buffer)) = self.as_singleton() {
2308            return buffer.clip_point_utf16(point, bias);
2309        }
2310
2311        let mut cursor = self.excerpts.cursor::<PointUtf16>();
2312        cursor.seek(&point.0, Bias::Right, &());
2313        let overshoot = if let Some(excerpt) = cursor.item() {
2314            let excerpt_start = excerpt
2315                .buffer
2316                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2317            let buffer_point = excerpt
2318                .buffer
2319                .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
2320            buffer_point.saturating_sub(excerpt_start)
2321        } else {
2322            PointUtf16::zero()
2323        };
2324        *cursor.start() + overshoot
2325    }
2326
2327    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
2328        let range = range.start.to_offset(self)..range.end.to_offset(self);
2329        let mut excerpts = self.excerpts.cursor::<usize>();
2330        excerpts.seek(&range.start, Bias::Right, &());
2331
2332        let mut chunk = &[][..];
2333        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2334            let mut excerpt_bytes = excerpt
2335                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
2336            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2337            Some(excerpt_bytes)
2338        } else {
2339            None
2340        };
2341        MultiBufferBytes {
2342            range,
2343            excerpts,
2344            excerpt_bytes,
2345            chunk,
2346        }
2347    }
2348
2349    pub fn reversed_bytes_in_range<T: ToOffset>(
2350        &self,
2351        range: Range<T>,
2352    ) -> ReversedMultiBufferBytes {
2353        let range = range.start.to_offset(self)..range.end.to_offset(self);
2354        let mut excerpts = self.excerpts.cursor::<usize>();
2355        excerpts.seek(&range.end, Bias::Left, &());
2356
2357        let mut chunk = &[][..];
2358        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2359            let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
2360                range.start.saturating_sub(*excerpts.start())..range.end - *excerpts.start(),
2361            );
2362            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2363            Some(excerpt_bytes)
2364        } else {
2365            None
2366        };
2367
2368        ReversedMultiBufferBytes {
2369            range,
2370            excerpts,
2371            excerpt_bytes,
2372            chunk,
2373        }
2374    }
2375
2376    pub fn buffer_rows(&self, start_row: MultiBufferRow) -> MultiBufferRows {
2377        let mut result = MultiBufferRows {
2378            buffer_row_range: 0..0,
2379            excerpts: self.excerpts.cursor(),
2380        };
2381        result.seek(start_row);
2382        result
2383    }
2384
2385    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
2386        let range = range.start.to_offset(self)..range.end.to_offset(self);
2387        let mut chunks = MultiBufferChunks {
2388            range: range.clone(),
2389            excerpts: self.excerpts.cursor(),
2390            excerpt_chunks: None,
2391            language_aware,
2392        };
2393        chunks.seek(range.start);
2394        chunks
2395    }
2396
2397    pub fn offset_to_point(&self, offset: usize) -> Point {
2398        if let Some((_, _, buffer)) = self.as_singleton() {
2399            return buffer.offset_to_point(offset);
2400        }
2401
2402        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2403        cursor.seek(&offset, Bias::Right, &());
2404        if let Some(excerpt) = cursor.item() {
2405            let (start_offset, start_point) = cursor.start();
2406            let overshoot = offset - start_offset;
2407            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2408            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2409            let buffer_point = excerpt
2410                .buffer
2411                .offset_to_point(excerpt_start_offset + overshoot);
2412            *start_point + (buffer_point - excerpt_start_point)
2413        } else {
2414            self.excerpts.summary().text.lines
2415        }
2416    }
2417
2418    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
2419        if let Some((_, _, buffer)) = self.as_singleton() {
2420            return buffer.offset_to_point_utf16(offset);
2421        }
2422
2423        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
2424        cursor.seek(&offset, Bias::Right, &());
2425        if let Some(excerpt) = cursor.item() {
2426            let (start_offset, start_point) = cursor.start();
2427            let overshoot = offset - start_offset;
2428            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2429            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2430            let buffer_point = excerpt
2431                .buffer
2432                .offset_to_point_utf16(excerpt_start_offset + overshoot);
2433            *start_point + (buffer_point - excerpt_start_point)
2434        } else {
2435            self.excerpts.summary().text.lines_utf16()
2436        }
2437    }
2438
2439    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
2440        if let Some((_, _, buffer)) = self.as_singleton() {
2441            return buffer.point_to_point_utf16(point);
2442        }
2443
2444        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
2445        cursor.seek(&point, Bias::Right, &());
2446        if let Some(excerpt) = cursor.item() {
2447            let (start_offset, start_point) = cursor.start();
2448            let overshoot = point - start_offset;
2449            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2450            let excerpt_start_point_utf16 =
2451                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2452            let buffer_point = excerpt
2453                .buffer
2454                .point_to_point_utf16(excerpt_start_point + overshoot);
2455            *start_point + (buffer_point - excerpt_start_point_utf16)
2456        } else {
2457            self.excerpts.summary().text.lines_utf16()
2458        }
2459    }
2460
2461    pub fn point_to_offset(&self, point: Point) -> usize {
2462        if let Some((_, _, buffer)) = self.as_singleton() {
2463            return buffer.point_to_offset(point);
2464        }
2465
2466        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2467        cursor.seek(&point, Bias::Right, &());
2468        if let Some(excerpt) = cursor.item() {
2469            let (start_point, start_offset) = cursor.start();
2470            let overshoot = point - start_point;
2471            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2472            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2473            let buffer_offset = excerpt
2474                .buffer
2475                .point_to_offset(excerpt_start_point + overshoot);
2476            *start_offset + buffer_offset - excerpt_start_offset
2477        } else {
2478            self.excerpts.summary().text.len
2479        }
2480    }
2481
2482    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2483        if let Some((_, _, buffer)) = self.as_singleton() {
2484            return buffer.offset_utf16_to_offset(offset_utf16);
2485        }
2486
2487        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2488        cursor.seek(&offset_utf16, Bias::Right, &());
2489        if let Some(excerpt) = cursor.item() {
2490            let (start_offset_utf16, start_offset) = cursor.start();
2491            let overshoot = offset_utf16 - start_offset_utf16;
2492            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2493            let excerpt_start_offset_utf16 =
2494                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2495            let buffer_offset = excerpt
2496                .buffer
2497                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2498            *start_offset + (buffer_offset - excerpt_start_offset)
2499        } else {
2500            self.excerpts.summary().text.len
2501        }
2502    }
2503
2504    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2505        if let Some((_, _, buffer)) = self.as_singleton() {
2506            return buffer.offset_to_offset_utf16(offset);
2507        }
2508
2509        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2510        cursor.seek(&offset, Bias::Right, &());
2511        if let Some(excerpt) = cursor.item() {
2512            let (start_offset, start_offset_utf16) = cursor.start();
2513            let overshoot = offset - start_offset;
2514            let excerpt_start_offset_utf16 =
2515                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2516            let excerpt_start_offset = excerpt
2517                .buffer
2518                .offset_utf16_to_offset(excerpt_start_offset_utf16);
2519            let buffer_offset_utf16 = excerpt
2520                .buffer
2521                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2522            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2523        } else {
2524            self.excerpts.summary().text.len_utf16
2525        }
2526    }
2527
2528    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2529        if let Some((_, _, buffer)) = self.as_singleton() {
2530            return buffer.point_utf16_to_offset(point);
2531        }
2532
2533        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2534        cursor.seek(&point, Bias::Right, &());
2535        if let Some(excerpt) = cursor.item() {
2536            let (start_point, start_offset) = cursor.start();
2537            let overshoot = point - start_point;
2538            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2539            let excerpt_start_point = excerpt
2540                .buffer
2541                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2542            let buffer_offset = excerpt
2543                .buffer
2544                .point_utf16_to_offset(excerpt_start_point + overshoot);
2545            *start_offset + (buffer_offset - excerpt_start_offset)
2546        } else {
2547            self.excerpts.summary().text.len
2548        }
2549    }
2550
2551    pub fn point_to_buffer_offset<T: ToOffset>(
2552        &self,
2553        point: T,
2554    ) -> Option<(&BufferSnapshot, usize)> {
2555        let offset = point.to_offset(self);
2556        let mut cursor = self.excerpts.cursor::<usize>();
2557        cursor.seek(&offset, Bias::Right, &());
2558        if cursor.item().is_none() {
2559            cursor.prev(&());
2560        }
2561
2562        cursor.item().map(|excerpt| {
2563            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2564            let buffer_point = excerpt_start + offset - *cursor.start();
2565            (&excerpt.buffer, buffer_point)
2566        })
2567    }
2568
2569    pub fn suggested_indents(
2570        &self,
2571        rows: impl IntoIterator<Item = u32>,
2572        cx: &AppContext,
2573    ) -> BTreeMap<MultiBufferRow, IndentSize> {
2574        let mut result = BTreeMap::new();
2575
2576        let mut rows_for_excerpt = Vec::new();
2577        let mut cursor = self.excerpts.cursor::<Point>();
2578        let mut rows = rows.into_iter().peekable();
2579        let mut prev_row = u32::MAX;
2580        let mut prev_language_indent_size = IndentSize::default();
2581
2582        while let Some(row) = rows.next() {
2583            cursor.seek(&Point::new(row, 0), Bias::Right, &());
2584            let excerpt = match cursor.item() {
2585                Some(excerpt) => excerpt,
2586                _ => continue,
2587            };
2588
2589            // Retrieve the language and indent size once for each disjoint region being indented.
2590            let single_indent_size = if row.saturating_sub(1) == prev_row {
2591                prev_language_indent_size
2592            } else {
2593                excerpt
2594                    .buffer
2595                    .language_indent_size_at(Point::new(row, 0), cx)
2596            };
2597            prev_language_indent_size = single_indent_size;
2598            prev_row = row;
2599
2600            let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2601            let start_multibuffer_row = cursor.start().row;
2602
2603            rows_for_excerpt.push(row);
2604            while let Some(next_row) = rows.peek().copied() {
2605                if cursor.end(&()).row > next_row {
2606                    rows_for_excerpt.push(next_row);
2607                    rows.next();
2608                } else {
2609                    break;
2610                }
2611            }
2612
2613            let buffer_rows = rows_for_excerpt
2614                .drain(..)
2615                .map(|row| start_buffer_row + row - start_multibuffer_row);
2616            let buffer_indents = excerpt
2617                .buffer
2618                .suggested_indents(buffer_rows, single_indent_size);
2619            let multibuffer_indents = buffer_indents.into_iter().map(|(row, indent)| {
2620                (
2621                    MultiBufferRow(start_multibuffer_row + row - start_buffer_row),
2622                    indent,
2623                )
2624            });
2625            result.extend(multibuffer_indents);
2626        }
2627
2628        result
2629    }
2630
2631    pub fn indent_size_for_line(&self, row: MultiBufferRow) -> IndentSize {
2632        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2633            let mut size = buffer.indent_size_for_line(range.start.row);
2634            size.len = size
2635                .len
2636                .min(range.end.column)
2637                .saturating_sub(range.start.column);
2638            size
2639        } else {
2640            IndentSize::spaces(0)
2641        }
2642    }
2643
2644    pub fn prev_non_blank_row(&self, mut row: MultiBufferRow) -> Option<MultiBufferRow> {
2645        while row.0 > 0 {
2646            row.0 -= 1;
2647            if !self.is_line_blank(row) {
2648                return Some(row);
2649            }
2650        }
2651        None
2652    }
2653
2654    pub fn line_len(&self, row: MultiBufferRow) -> u32 {
2655        if let Some((_, range)) = self.buffer_line_for_row(row) {
2656            range.end.column - range.start.column
2657        } else {
2658            0
2659        }
2660    }
2661
2662    pub fn buffer_line_for_row(
2663        &self,
2664        row: MultiBufferRow,
2665    ) -> Option<(&BufferSnapshot, Range<Point>)> {
2666        let mut cursor = self.excerpts.cursor::<Point>();
2667        let point = Point::new(row.0, 0);
2668        cursor.seek(&point, Bias::Right, &());
2669        if cursor.item().is_none() && *cursor.start() == point {
2670            cursor.prev(&());
2671        }
2672        if let Some(excerpt) = cursor.item() {
2673            let overshoot = row.0 - cursor.start().row;
2674            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2675            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2676            let buffer_row = excerpt_start.row + overshoot;
2677            let line_start = Point::new(buffer_row, 0);
2678            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2679            return Some((
2680                &excerpt.buffer,
2681                line_start.max(excerpt_start)..line_end.min(excerpt_end),
2682            ));
2683        }
2684        None
2685    }
2686
2687    pub fn max_point(&self) -> Point {
2688        self.text_summary().lines
2689    }
2690
2691    pub fn text_summary(&self) -> TextSummary {
2692        self.excerpts.summary().text.clone()
2693    }
2694
2695    pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2696    where
2697        D: TextDimension,
2698        O: ToOffset,
2699    {
2700        let mut summary = D::default();
2701        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2702        let mut cursor = self.excerpts.cursor::<usize>();
2703        cursor.seek(&range.start, Bias::Right, &());
2704        if let Some(excerpt) = cursor.item() {
2705            let mut end_before_newline = cursor.end(&());
2706            if excerpt.has_trailing_newline {
2707                end_before_newline -= 1;
2708            }
2709
2710            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2711            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2712            let end_in_excerpt =
2713                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2714            summary.add_assign(
2715                &excerpt
2716                    .buffer
2717                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2718            );
2719
2720            if range.end > end_before_newline {
2721                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2722            }
2723
2724            cursor.next(&());
2725        }
2726
2727        if range.end > *cursor.start() {
2728            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2729                &range.end,
2730                Bias::Right,
2731                &(),
2732            )));
2733            if let Some(excerpt) = cursor.item() {
2734                range.end = cmp::max(*cursor.start(), range.end);
2735
2736                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2737                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2738                summary.add_assign(
2739                    &excerpt
2740                        .buffer
2741                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2742                );
2743            }
2744        }
2745
2746        summary
2747    }
2748
2749    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2750    where
2751        D: TextDimension + Ord + Sub<D, Output = D>,
2752    {
2753        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2754        let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2755
2756        cursor.seek(locator, Bias::Left, &());
2757        if cursor.item().is_none() {
2758            cursor.next(&());
2759        }
2760
2761        let mut position = D::from_text_summary(&cursor.start().text);
2762        if let Some(excerpt) = cursor.item() {
2763            if excerpt.id == anchor.excerpt_id {
2764                let excerpt_buffer_start =
2765                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2766                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2767                let buffer_position = cmp::min(
2768                    excerpt_buffer_end,
2769                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2770                );
2771                if buffer_position > excerpt_buffer_start {
2772                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2773                }
2774            }
2775        }
2776        position
2777    }
2778
2779    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2780    where
2781        D: TextDimension + Ord + Sub<D, Output = D>,
2782        I: 'a + IntoIterator<Item = &'a Anchor>,
2783    {
2784        if let Some((_, _, buffer)) = self.as_singleton() {
2785            return buffer
2786                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2787                .collect();
2788        }
2789
2790        let mut anchors = anchors.into_iter().peekable();
2791        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2792        let mut summaries = Vec::new();
2793        while let Some(anchor) = anchors.peek() {
2794            let excerpt_id = anchor.excerpt_id;
2795            let excerpt_anchors = iter::from_fn(|| {
2796                let anchor = anchors.peek()?;
2797                if anchor.excerpt_id == excerpt_id {
2798                    Some(&anchors.next().unwrap().text_anchor)
2799                } else {
2800                    None
2801                }
2802            });
2803
2804            let locator = self.excerpt_locator_for_id(excerpt_id);
2805            cursor.seek_forward(locator, Bias::Left, &());
2806            if cursor.item().is_none() {
2807                cursor.next(&());
2808            }
2809
2810            let position = D::from_text_summary(&cursor.start().text);
2811            if let Some(excerpt) = cursor.item() {
2812                if excerpt.id == excerpt_id {
2813                    let excerpt_buffer_start =
2814                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2815                    let excerpt_buffer_end =
2816                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2817                    summaries.extend(
2818                        excerpt
2819                            .buffer
2820                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2821                            .map(move |summary| {
2822                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2823                                let mut position = position.clone();
2824                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2825                                if summary > excerpt_buffer_start {
2826                                    position.add_assign(&(summary - excerpt_buffer_start));
2827                                }
2828                                position
2829                            }),
2830                    );
2831                    continue;
2832                }
2833            }
2834
2835            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2836        }
2837
2838        summaries
2839    }
2840
2841    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2842    where
2843        I: 'a + IntoIterator<Item = &'a Anchor>,
2844    {
2845        let mut anchors = anchors.into_iter().enumerate().peekable();
2846        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2847        cursor.next(&());
2848
2849        let mut result = Vec::new();
2850
2851        while let Some((_, anchor)) = anchors.peek() {
2852            let old_excerpt_id = anchor.excerpt_id;
2853
2854            // Find the location where this anchor's excerpt should be.
2855            let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2856            cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2857
2858            if cursor.item().is_none() {
2859                cursor.next(&());
2860            }
2861
2862            let next_excerpt = cursor.item();
2863            let prev_excerpt = cursor.prev_item();
2864
2865            // Process all of the anchors for this excerpt.
2866            while let Some((_, anchor)) = anchors.peek() {
2867                if anchor.excerpt_id != old_excerpt_id {
2868                    break;
2869                }
2870                let (anchor_ix, anchor) = anchors.next().unwrap();
2871                let mut anchor = *anchor;
2872
2873                // Leave min and max anchors unchanged if invalid or
2874                // if the old excerpt still exists at this location
2875                let mut kept_position = next_excerpt
2876                    .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2877                    || old_excerpt_id == ExcerptId::max()
2878                    || old_excerpt_id == ExcerptId::min();
2879
2880                // If the old excerpt no longer exists at this location, then attempt to
2881                // find an equivalent position for this anchor in an adjacent excerpt.
2882                if !kept_position {
2883                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2884                        if excerpt.contains(&anchor) {
2885                            anchor.excerpt_id = excerpt.id;
2886                            kept_position = true;
2887                            break;
2888                        }
2889                    }
2890                }
2891
2892                // If there's no adjacent excerpt that contains the anchor's position,
2893                // then report that the anchor has lost its position.
2894                if !kept_position {
2895                    anchor = if let Some(excerpt) = next_excerpt {
2896                        let mut text_anchor = excerpt
2897                            .range
2898                            .context
2899                            .start
2900                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2901                        if text_anchor
2902                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2903                            .is_gt()
2904                        {
2905                            text_anchor = excerpt.range.context.end;
2906                        }
2907                        Anchor {
2908                            buffer_id: Some(excerpt.buffer_id),
2909                            excerpt_id: excerpt.id,
2910                            text_anchor,
2911                        }
2912                    } else if let Some(excerpt) = prev_excerpt {
2913                        let mut text_anchor = excerpt
2914                            .range
2915                            .context
2916                            .end
2917                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2918                        if text_anchor
2919                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2920                            .is_lt()
2921                        {
2922                            text_anchor = excerpt.range.context.start;
2923                        }
2924                        Anchor {
2925                            buffer_id: Some(excerpt.buffer_id),
2926                            excerpt_id: excerpt.id,
2927                            text_anchor,
2928                        }
2929                    } else if anchor.text_anchor.bias == Bias::Left {
2930                        Anchor::min()
2931                    } else {
2932                        Anchor::max()
2933                    };
2934                }
2935
2936                result.push((anchor_ix, anchor, kept_position));
2937            }
2938        }
2939        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2940        result
2941    }
2942
2943    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2944        self.anchor_at(position, Bias::Left)
2945    }
2946
2947    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2948        self.anchor_at(position, Bias::Right)
2949    }
2950
2951    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2952        let offset = position.to_offset(self);
2953        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2954            return Anchor {
2955                buffer_id: Some(buffer_id),
2956                excerpt_id: *excerpt_id,
2957                text_anchor: buffer.anchor_at(offset, bias),
2958            };
2959        }
2960
2961        let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2962        cursor.seek(&offset, Bias::Right, &());
2963        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2964            cursor.prev(&());
2965        }
2966        if let Some(excerpt) = cursor.item() {
2967            let mut overshoot = offset.saturating_sub(cursor.start().0);
2968            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2969                overshoot -= 1;
2970                bias = Bias::Right;
2971            }
2972
2973            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2974            let text_anchor =
2975                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2976            Anchor {
2977                buffer_id: Some(excerpt.buffer_id),
2978                excerpt_id: excerpt.id,
2979                text_anchor,
2980            }
2981        } else if offset == 0 && bias == Bias::Left {
2982            Anchor::min()
2983        } else {
2984            Anchor::max()
2985        }
2986    }
2987
2988    /// Returns an anchor for the given excerpt and text anchor,
2989    /// returns None if the excerpt_id is no longer valid.
2990    pub fn anchor_in_excerpt(
2991        &self,
2992        excerpt_id: ExcerptId,
2993        text_anchor: text::Anchor,
2994    ) -> Option<Anchor> {
2995        let locator = self.excerpt_locator_for_id(excerpt_id);
2996        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2997        cursor.seek(locator, Bias::Left, &());
2998        if let Some(excerpt) = cursor.item() {
2999            if excerpt.id == excerpt_id {
3000                let text_anchor = excerpt.clip_anchor(text_anchor);
3001                drop(cursor);
3002                return Some(Anchor {
3003                    buffer_id: Some(excerpt.buffer_id),
3004                    excerpt_id,
3005                    text_anchor,
3006                });
3007            }
3008        }
3009        None
3010    }
3011
3012    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
3013        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
3014            true
3015        } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
3016            excerpt.buffer.can_resolve(&anchor.text_anchor)
3017        } else {
3018            false
3019        }
3020    }
3021
3022    pub fn excerpts(
3023        &self,
3024    ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
3025        self.excerpts
3026            .iter()
3027            .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
3028    }
3029
3030    fn excerpts_for_range<T: ToOffset>(
3031        &self,
3032        range: Range<T>,
3033    ) -> impl Iterator<Item = (&Excerpt, usize)> + '_ {
3034        let range = range.start.to_offset(self)..range.end.to_offset(self);
3035
3036        let mut cursor = self.excerpts.cursor::<usize>();
3037        cursor.seek(&range.start, Bias::Right, &());
3038        cursor.prev(&());
3039
3040        iter::from_fn(move || {
3041            cursor.next(&());
3042            if cursor.start() < &range.end {
3043                cursor.item().map(|item| (item, *cursor.start()))
3044            } else {
3045                None
3046            }
3047        })
3048    }
3049
3050    pub fn excerpt_boundaries_in_range<R, T>(
3051        &self,
3052        range: R,
3053    ) -> impl Iterator<Item = ExcerptBoundary> + '_
3054    where
3055        R: RangeBounds<T>,
3056        T: ToOffset,
3057    {
3058        let start_offset;
3059        let start = match range.start_bound() {
3060            Bound::Included(start) => {
3061                start_offset = start.to_offset(self);
3062                Bound::Included(start_offset)
3063            }
3064            Bound::Excluded(start) => {
3065                start_offset = start.to_offset(self);
3066                Bound::Excluded(start_offset)
3067            }
3068            Bound::Unbounded => {
3069                start_offset = 0;
3070                Bound::Unbounded
3071            }
3072        };
3073        let end = match range.end_bound() {
3074            Bound::Included(end) => Bound::Included(end.to_offset(self)),
3075            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
3076            Bound::Unbounded => Bound::Unbounded,
3077        };
3078        let bounds = (start, end);
3079
3080        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
3081        cursor.seek(&start_offset, Bias::Right, &());
3082        if cursor.item().is_none() {
3083            cursor.prev(&());
3084        }
3085        if !bounds.contains(&cursor.start().0) {
3086            cursor.next(&());
3087        }
3088
3089        let mut visited_end = false;
3090        std::iter::from_fn(move || {
3091            if self.singleton {
3092                None
3093            } else if bounds.contains(&cursor.start().0) {
3094                let next = cursor.item().map(|excerpt| ExcerptInfo {
3095                    id: excerpt.id,
3096                    buffer: excerpt.buffer.clone(),
3097                    buffer_id: excerpt.buffer_id,
3098                    range: excerpt.range.clone(),
3099                });
3100
3101                if next.is_none() {
3102                    if visited_end {
3103                        return None;
3104                    } else {
3105                        visited_end = true;
3106                    }
3107                }
3108
3109                let prev = cursor.prev_item().map(|prev_excerpt| ExcerptInfo {
3110                    id: prev_excerpt.id,
3111                    buffer: prev_excerpt.buffer.clone(),
3112                    buffer_id: prev_excerpt.buffer_id,
3113                    range: prev_excerpt.range.clone(),
3114                });
3115                let row = MultiBufferRow(cursor.start().1.row);
3116
3117                cursor.next(&());
3118
3119                Some(ExcerptBoundary { row, prev, next })
3120            } else {
3121                None
3122            }
3123        })
3124    }
3125
3126    pub fn edit_count(&self) -> usize {
3127        self.edit_count
3128    }
3129
3130    pub fn parse_count(&self) -> usize {
3131        self.parse_count
3132    }
3133
3134    /// Returns the smallest enclosing bracket ranges containing the given range or
3135    /// None if no brackets contain range or the range is not contained in a single
3136    /// excerpt
3137    ///
3138    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3139    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3140        &self,
3141        range: Range<T>,
3142        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3143    ) -> Option<(Range<usize>, Range<usize>)> {
3144        let range = range.start.to_offset(self)..range.end.to_offset(self);
3145        let excerpt = self.excerpt_containing(range.clone())?;
3146
3147        // Filter to ranges contained in the excerpt
3148        let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
3149            excerpt.contains_buffer_range(open.start..close.end)
3150                && range_filter.map_or(true, |filter| {
3151                    filter(
3152                        excerpt.map_range_from_buffer(open),
3153                        excerpt.map_range_from_buffer(close),
3154                    )
3155                })
3156        };
3157
3158        let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
3159            excerpt.map_range_to_buffer(range),
3160            Some(&range_filter),
3161        )?;
3162
3163        Some((
3164            excerpt.map_range_from_buffer(open),
3165            excerpt.map_range_from_buffer(close),
3166        ))
3167    }
3168
3169    /// Returns enclosing bracket ranges containing the given range or returns None if the range is
3170    /// not contained in a single excerpt
3171    pub fn enclosing_bracket_ranges<T: ToOffset>(
3172        &self,
3173        range: Range<T>,
3174    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3175        let range = range.start.to_offset(self)..range.end.to_offset(self);
3176        let excerpt = self.excerpt_containing(range.clone())?;
3177
3178        Some(
3179            excerpt
3180                .buffer()
3181                .enclosing_bracket_ranges(excerpt.map_range_to_buffer(range))
3182                .filter_map(move |(open, close)| {
3183                    if excerpt.contains_buffer_range(open.start..close.end) {
3184                        Some((
3185                            excerpt.map_range_from_buffer(open),
3186                            excerpt.map_range_from_buffer(close),
3187                        ))
3188                    } else {
3189                        None
3190                    }
3191                }),
3192        )
3193    }
3194
3195    /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
3196    /// not contained in a single excerpt
3197    pub fn bracket_ranges<T: ToOffset>(
3198        &self,
3199        range: Range<T>,
3200    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3201        let range = range.start.to_offset(self)..range.end.to_offset(self);
3202        let excerpt = self.excerpt_containing(range.clone())?;
3203
3204        Some(
3205            excerpt
3206                .buffer()
3207                .bracket_ranges(excerpt.map_range_to_buffer(range))
3208                .filter_map(move |(start_bracket_range, close_bracket_range)| {
3209                    let buffer_range = start_bracket_range.start..close_bracket_range.end;
3210                    if excerpt.contains_buffer_range(buffer_range) {
3211                        Some((
3212                            excerpt.map_range_from_buffer(start_bracket_range),
3213                            excerpt.map_range_from_buffer(close_bracket_range),
3214                        ))
3215                    } else {
3216                        None
3217                    }
3218                }),
3219        )
3220    }
3221
3222    pub fn redacted_ranges<'a, T: ToOffset>(
3223        &'a self,
3224        range: Range<T>,
3225        redaction_enabled: impl Fn(Option<&Arc<dyn File>>) -> bool + 'a,
3226    ) -> impl Iterator<Item = Range<usize>> + 'a {
3227        let range = range.start.to_offset(self)..range.end.to_offset(self);
3228        self.excerpts_for_range(range.clone())
3229            .filter_map(move |(excerpt, excerpt_offset)| {
3230                redaction_enabled(excerpt.buffer.file()).then(move || {
3231                    let excerpt_buffer_start =
3232                        excerpt.range.context.start.to_offset(&excerpt.buffer);
3233
3234                    excerpt
3235                        .buffer
3236                        .redacted_ranges(excerpt.range.context.clone())
3237                        .map(move |mut redacted_range| {
3238                            // Re-base onto the excerpts coordinates in the multibuffer
3239                            redacted_range.start = excerpt_offset
3240                                + redacted_range.start.saturating_sub(excerpt_buffer_start);
3241                            redacted_range.end = excerpt_offset
3242                                + redacted_range.end.saturating_sub(excerpt_buffer_start);
3243
3244                            redacted_range
3245                        })
3246                        .skip_while(move |redacted_range| redacted_range.end < range.start)
3247                        .take_while(move |redacted_range| redacted_range.start < range.end)
3248                })
3249            })
3250            .flatten()
3251    }
3252
3253    pub fn runnable_ranges(
3254        &self,
3255        range: Range<Anchor>,
3256    ) -> impl Iterator<Item = language::RunnableRange> + '_ {
3257        let range = range.start.to_offset(self)..range.end.to_offset(self);
3258        self.excerpts_for_range(range.clone())
3259            .flat_map(move |(excerpt, excerpt_offset)| {
3260                let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3261
3262                excerpt
3263                    .buffer
3264                    .runnable_ranges(excerpt.range.context.clone())
3265                    .filter_map(move |mut runnable| {
3266                        // Re-base onto the excerpts coordinates in the multibuffer
3267                        //
3268                        // The node matching our runnables query might partially overlap with
3269                        // the provided range. If the run indicator is outside of excerpt bounds, do not actually show it.
3270                        if runnable.run_range.start < excerpt_buffer_start {
3271                            return None;
3272                        }
3273                        if language::ToPoint::to_point(&runnable.run_range.end, &excerpt.buffer).row
3274                            > excerpt.max_buffer_row
3275                        {
3276                            return None;
3277                        }
3278                        runnable.run_range.start =
3279                            excerpt_offset + runnable.run_range.start - excerpt_buffer_start;
3280                        runnable.run_range.end =
3281                            excerpt_offset + runnable.run_range.end - excerpt_buffer_start;
3282                        Some(runnable)
3283                    })
3284                    .skip_while(move |runnable| runnable.run_range.end < range.start)
3285                    .take_while(move |runnable| runnable.run_range.start < range.end)
3286            })
3287    }
3288
3289    pub fn indent_guides_in_range(
3290        &self,
3291        range: Range<Anchor>,
3292        ignore_disabled_for_language: bool,
3293        cx: &AppContext,
3294    ) -> Vec<MultiBufferIndentGuide> {
3295        // Fast path for singleton buffers, we can skip the conversion between offsets.
3296        if let Some((_, _, snapshot)) = self.as_singleton() {
3297            return snapshot
3298                .indent_guides_in_range(
3299                    range.start.text_anchor..range.end.text_anchor,
3300                    ignore_disabled_for_language,
3301                    cx,
3302                )
3303                .into_iter()
3304                .map(|guide| MultiBufferIndentGuide {
3305                    multibuffer_row_range: MultiBufferRow(guide.start_row)
3306                        ..MultiBufferRow(guide.end_row),
3307                    buffer: guide,
3308                })
3309                .collect();
3310        }
3311
3312        let range = range.start.to_offset(self)..range.end.to_offset(self);
3313
3314        self.excerpts_for_range(range.clone())
3315            .flat_map(move |(excerpt, excerpt_offset)| {
3316                let excerpt_buffer_start_row =
3317                    excerpt.range.context.start.to_point(&excerpt.buffer).row;
3318                let excerpt_offset_row = crate::ToPoint::to_point(&excerpt_offset, self).row;
3319
3320                excerpt
3321                    .buffer
3322                    .indent_guides_in_range(
3323                        excerpt.range.context.clone(),
3324                        ignore_disabled_for_language,
3325                        cx,
3326                    )
3327                    .into_iter()
3328                    .map(move |indent_guide| {
3329                        let start_row = excerpt_offset_row
3330                            + (indent_guide.start_row - excerpt_buffer_start_row);
3331                        let end_row =
3332                            excerpt_offset_row + (indent_guide.end_row - excerpt_buffer_start_row);
3333
3334                        MultiBufferIndentGuide {
3335                            multibuffer_row_range: MultiBufferRow(start_row)
3336                                ..MultiBufferRow(end_row),
3337                            buffer: indent_guide,
3338                        }
3339                    })
3340            })
3341            .collect()
3342    }
3343
3344    pub fn diagnostics_update_count(&self) -> usize {
3345        self.diagnostics_update_count
3346    }
3347
3348    pub fn git_diff_update_count(&self) -> usize {
3349        self.git_diff_update_count
3350    }
3351
3352    pub fn trailing_excerpt_update_count(&self) -> usize {
3353        self.trailing_excerpt_update_count
3354    }
3355
3356    pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
3357        self.point_to_buffer_offset(point)
3358            .and_then(|(buffer, _)| buffer.file())
3359    }
3360
3361    pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
3362        self.point_to_buffer_offset(point)
3363            .and_then(|(buffer, offset)| buffer.language_at(offset))
3364    }
3365
3366    pub fn settings_at<'a, T: ToOffset>(
3367        &'a self,
3368        point: T,
3369        cx: &'a AppContext,
3370    ) -> &'a LanguageSettings {
3371        let mut language = None;
3372        let mut file = None;
3373        if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
3374            language = buffer.language_at(offset);
3375            file = buffer.file();
3376        }
3377        language_settings(language, file, cx)
3378    }
3379
3380    pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
3381        self.point_to_buffer_offset(point)
3382            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
3383    }
3384
3385    pub fn language_indent_size_at<T: ToOffset>(
3386        &self,
3387        position: T,
3388        cx: &AppContext,
3389    ) -> Option<IndentSize> {
3390        let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
3391        Some(buffer_snapshot.language_indent_size_at(offset, cx))
3392    }
3393
3394    pub fn is_dirty(&self) -> bool {
3395        self.is_dirty
3396    }
3397
3398    pub fn has_conflict(&self) -> bool {
3399        self.has_conflict
3400    }
3401
3402    pub fn has_diagnostics(&self) -> bool {
3403        self.excerpts
3404            .iter()
3405            .any(|excerpt| excerpt.buffer.has_diagnostics())
3406    }
3407
3408    pub fn diagnostic_group<'a, O>(
3409        &'a self,
3410        group_id: usize,
3411    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3412    where
3413        O: text::FromAnchor + 'a,
3414    {
3415        self.as_singleton()
3416            .into_iter()
3417            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
3418    }
3419
3420    pub fn diagnostics_in_range<'a, T, O>(
3421        &'a self,
3422        range: Range<T>,
3423        reversed: bool,
3424    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3425    where
3426        T: 'a + ToOffset,
3427        O: 'a + text::FromAnchor + Ord,
3428    {
3429        self.as_singleton()
3430            .into_iter()
3431            .flat_map(move |(_, _, buffer)| {
3432                buffer.diagnostics_in_range(
3433                    range.start.to_offset(self)..range.end.to_offset(self),
3434                    reversed,
3435                )
3436            })
3437    }
3438
3439    pub fn has_git_diffs(&self) -> bool {
3440        for excerpt in self.excerpts.iter() {
3441            if excerpt.buffer.has_git_diff() {
3442                return true;
3443            }
3444        }
3445        false
3446    }
3447
3448    pub fn git_diff_hunks_in_range_rev(
3449        &self,
3450        row_range: Range<MultiBufferRow>,
3451    ) -> impl Iterator<Item = DiffHunk<MultiBufferRow>> + '_ {
3452        let mut cursor = self.excerpts.cursor::<Point>();
3453
3454        cursor.seek(&Point::new(row_range.end.0, 0), Bias::Left, &());
3455        if cursor.item().is_none() {
3456            cursor.prev(&());
3457        }
3458
3459        std::iter::from_fn(move || {
3460            let excerpt = cursor.item()?;
3461            let multibuffer_start = *cursor.start();
3462            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3463            if multibuffer_start.row >= row_range.end.0 {
3464                return None;
3465            }
3466
3467            let mut buffer_start = excerpt.range.context.start;
3468            let mut buffer_end = excerpt.range.context.end;
3469            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3470            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3471
3472            if row_range.start.0 > multibuffer_start.row {
3473                let buffer_start_point =
3474                    excerpt_start_point + Point::new(row_range.start.0 - multibuffer_start.row, 0);
3475                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3476            }
3477
3478            if row_range.end.0 < multibuffer_end.row {
3479                let buffer_end_point =
3480                    excerpt_start_point + Point::new(row_range.end.0 - multibuffer_start.row, 0);
3481                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3482            }
3483
3484            let buffer_hunks = excerpt
3485                .buffer
3486                .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
3487                .map(move |hunk| {
3488                    let start = multibuffer_start.row
3489                        + hunk
3490                            .associated_range
3491                            .start
3492                            .saturating_sub(excerpt_start_point.row);
3493                    let end = multibuffer_start.row
3494                        + hunk
3495                            .associated_range
3496                            .end
3497                            .min(excerpt_end_point.row + 1)
3498                            .saturating_sub(excerpt_start_point.row);
3499
3500                    DiffHunk {
3501                        associated_range: MultiBufferRow(start)..MultiBufferRow(end),
3502                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3503                        buffer_range: hunk.buffer_range.clone(),
3504                        buffer_id: hunk.buffer_id,
3505                    }
3506                });
3507
3508            cursor.prev(&());
3509
3510            Some(buffer_hunks)
3511        })
3512        .flatten()
3513    }
3514
3515    pub fn git_diff_hunks_in_range(
3516        &self,
3517        row_range: Range<MultiBufferRow>,
3518    ) -> impl Iterator<Item = DiffHunk<MultiBufferRow>> + '_ {
3519        let mut cursor = self.excerpts.cursor::<Point>();
3520
3521        cursor.seek(&Point::new(row_range.start.0, 0), Bias::Left, &());
3522
3523        std::iter::from_fn(move || {
3524            let excerpt = cursor.item()?;
3525            let multibuffer_start = *cursor.start();
3526            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3527            let mut buffer_start = excerpt.range.context.start;
3528            let mut buffer_end = excerpt.range.context.end;
3529
3530            let excerpt_rows = match multibuffer_start.row.cmp(&row_range.end.0) {
3531                cmp::Ordering::Less => {
3532                    let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3533                    let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3534
3535                    if row_range.start.0 > multibuffer_start.row {
3536                        let buffer_start_point = excerpt_start_point
3537                            + Point::new(row_range.start.0 - multibuffer_start.row, 0);
3538                        buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3539                    }
3540
3541                    if row_range.end.0 < multibuffer_end.row {
3542                        let buffer_end_point = excerpt_start_point
3543                            + Point::new(row_range.end.0 - multibuffer_start.row, 0);
3544                        buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3545                    }
3546                    excerpt_start_point.row..excerpt_end_point.row
3547                }
3548                cmp::Ordering::Equal if row_range.end.0 == 0 => {
3549                    buffer_end = buffer_start;
3550                    0..0
3551                }
3552                cmp::Ordering::Greater | cmp::Ordering::Equal => return None,
3553            };
3554
3555            let buffer_hunks = excerpt
3556                .buffer
3557                .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3558                .map(move |hunk| {
3559                    let buffer_range = if excerpt_rows.start == 0 && excerpt_rows.end == 0 {
3560                        MultiBufferRow(0)..MultiBufferRow(1)
3561                    } else {
3562                        let start = multibuffer_start.row
3563                            + hunk
3564                                .associated_range
3565                                .start
3566                                .saturating_sub(excerpt_rows.start);
3567                        let end = multibuffer_start.row
3568                            + hunk
3569                                .associated_range
3570                                .end
3571                                .min(excerpt_rows.end + 1)
3572                                .saturating_sub(excerpt_rows.start);
3573                        MultiBufferRow(start)..MultiBufferRow(end)
3574                    };
3575                    DiffHunk {
3576                        associated_range: buffer_range,
3577                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3578                        buffer_range: hunk.buffer_range.clone(),
3579                        buffer_id: hunk.buffer_id,
3580                    }
3581                });
3582
3583            cursor.next(&());
3584
3585            Some(buffer_hunks)
3586        })
3587        .flatten()
3588    }
3589
3590    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3591        let range = range.start.to_offset(self)..range.end.to_offset(self);
3592        let excerpt = self.excerpt_containing(range.clone())?;
3593
3594        let ancestor_buffer_range = excerpt
3595            .buffer()
3596            .range_for_syntax_ancestor(excerpt.map_range_to_buffer(range))?;
3597
3598        Some(excerpt.map_range_from_buffer(ancestor_buffer_range))
3599    }
3600
3601    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3602        let (excerpt_id, _, buffer) = self.as_singleton()?;
3603        let outline = buffer.outline(theme)?;
3604        Some(Outline::new(
3605            outline
3606                .items
3607                .into_iter()
3608                .flat_map(|item| {
3609                    Some(OutlineItem {
3610                        depth: item.depth,
3611                        range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
3612                            ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
3613                        text: item.text,
3614                        highlight_ranges: item.highlight_ranges,
3615                        name_ranges: item.name_ranges,
3616                    })
3617                })
3618                .collect(),
3619        ))
3620    }
3621
3622    pub fn symbols_containing<T: ToOffset>(
3623        &self,
3624        offset: T,
3625        theme: Option<&SyntaxTheme>,
3626    ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3627        let anchor = self.anchor_before(offset);
3628        let excerpt_id = anchor.excerpt_id;
3629        let excerpt = self.excerpt(excerpt_id)?;
3630        Some((
3631            excerpt.buffer_id,
3632            excerpt
3633                .buffer
3634                .symbols_containing(anchor.text_anchor, theme)
3635                .into_iter()
3636                .flatten()
3637                .flat_map(|item| {
3638                    Some(OutlineItem {
3639                        depth: item.depth,
3640                        range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3641                            ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3642                        text: item.text,
3643                        highlight_ranges: item.highlight_ranges,
3644                        name_ranges: item.name_ranges,
3645                    })
3646                })
3647                .collect(),
3648        ))
3649    }
3650
3651    fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3652        if id == ExcerptId::min() {
3653            Locator::min_ref()
3654        } else if id == ExcerptId::max() {
3655            Locator::max_ref()
3656        } else {
3657            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3658            cursor.seek(&id, Bias::Left, &());
3659            if let Some(entry) = cursor.item() {
3660                if entry.id == id {
3661                    return &entry.locator;
3662                }
3663            }
3664            panic!("invalid excerpt id {:?}", id)
3665        }
3666    }
3667
3668    // Returns the locators referenced by the given excerpt ids, sorted by locator.
3669    fn excerpt_locators_for_ids(
3670        &self,
3671        ids: impl IntoIterator<Item = ExcerptId>,
3672    ) -> SmallVec<[Locator; 1]> {
3673        let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
3674        sorted_ids.sort_unstable();
3675        let mut locators = SmallVec::new();
3676
3677        while sorted_ids.last() == Some(&ExcerptId::max()) {
3678            sorted_ids.pop();
3679            locators.push(Locator::max());
3680        }
3681
3682        let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
3683        if sorted_ids.peek() == Some(&ExcerptId::min()) {
3684            sorted_ids.next();
3685            locators.push(Locator::min());
3686        }
3687
3688        let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3689        for id in sorted_ids {
3690            if cursor.seek_forward(&id, Bias::Left, &()) {
3691                locators.push(cursor.item().unwrap().locator.clone());
3692            } else {
3693                panic!("invalid excerpt id {:?}", id);
3694            }
3695        }
3696
3697        locators.sort_unstable();
3698        locators
3699    }
3700
3701    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3702        Some(self.excerpt(excerpt_id)?.buffer_id)
3703    }
3704
3705    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3706        Some(&self.excerpt(excerpt_id)?.buffer)
3707    }
3708
3709    fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3710        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3711        let locator = self.excerpt_locator_for_id(excerpt_id);
3712        cursor.seek(&Some(locator), Bias::Left, &());
3713        if let Some(excerpt) = cursor.item() {
3714            if excerpt.id == excerpt_id {
3715                return Some(excerpt);
3716            }
3717        }
3718        None
3719    }
3720
3721    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3722    pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3723        let range = range.start.to_offset(self)..range.end.to_offset(self);
3724
3725        let mut cursor = self.excerpts.cursor::<usize>();
3726        cursor.seek(&range.start, Bias::Right, &());
3727        let start_excerpt = cursor.item()?;
3728
3729        if range.start == range.end {
3730            return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3731        }
3732
3733        cursor.seek(&range.end, Bias::Right, &());
3734        let end_excerpt = cursor.item()?;
3735
3736        if start_excerpt.id == end_excerpt.id {
3737            Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3738        } else {
3739            None
3740        }
3741    }
3742
3743    pub fn remote_selections_in_range<'a>(
3744        &'a self,
3745        range: &'a Range<Anchor>,
3746    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3747        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3748        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3749        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3750        cursor.seek(start_locator, Bias::Left, &());
3751        cursor
3752            .take_while(move |excerpt| excerpt.locator <= *end_locator)
3753            .flat_map(move |excerpt| {
3754                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3755                if excerpt.id == range.start.excerpt_id {
3756                    query_range.start = range.start.text_anchor;
3757                }
3758                if excerpt.id == range.end.excerpt_id {
3759                    query_range.end = range.end.text_anchor;
3760                }
3761
3762                excerpt
3763                    .buffer
3764                    .remote_selections_in_range(query_range)
3765                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3766                        selections.map(move |selection| {
3767                            let mut start = Anchor {
3768                                buffer_id: Some(excerpt.buffer_id),
3769                                excerpt_id: excerpt.id,
3770                                text_anchor: selection.start,
3771                            };
3772                            let mut end = Anchor {
3773                                buffer_id: Some(excerpt.buffer_id),
3774                                excerpt_id: excerpt.id,
3775                                text_anchor: selection.end,
3776                            };
3777                            if range.start.cmp(&start, self).is_gt() {
3778                                start = range.start;
3779                            }
3780                            if range.end.cmp(&end, self).is_lt() {
3781                                end = range.end;
3782                            }
3783
3784                            (
3785                                replica_id,
3786                                line_mode,
3787                                cursor_shape,
3788                                Selection {
3789                                    id: selection.id,
3790                                    start,
3791                                    end,
3792                                    reversed: selection.reversed,
3793                                    goal: selection.goal,
3794                                },
3795                            )
3796                        })
3797                    })
3798            })
3799    }
3800
3801    pub fn show_headers(&self) -> bool {
3802        self.show_headers
3803    }
3804}
3805
3806#[cfg(any(test, feature = "test-support"))]
3807impl MultiBufferSnapshot {
3808    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3809        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3810        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3811        start..end
3812    }
3813}
3814
3815impl History {
3816    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3817        self.transaction_depth += 1;
3818        if self.transaction_depth == 1 {
3819            let id = self.next_transaction_id.tick();
3820            self.undo_stack.push(Transaction {
3821                id,
3822                buffer_transactions: Default::default(),
3823                first_edit_at: now,
3824                last_edit_at: now,
3825                suppress_grouping: false,
3826            });
3827            Some(id)
3828        } else {
3829            None
3830        }
3831    }
3832
3833    fn end_transaction(
3834        &mut self,
3835        now: Instant,
3836        buffer_transactions: HashMap<BufferId, TransactionId>,
3837    ) -> bool {
3838        assert_ne!(self.transaction_depth, 0);
3839        self.transaction_depth -= 1;
3840        if self.transaction_depth == 0 {
3841            if buffer_transactions.is_empty() {
3842                self.undo_stack.pop();
3843                false
3844            } else {
3845                self.redo_stack.clear();
3846                let transaction = self.undo_stack.last_mut().unwrap();
3847                transaction.last_edit_at = now;
3848                for (buffer_id, transaction_id) in buffer_transactions {
3849                    transaction
3850                        .buffer_transactions
3851                        .entry(buffer_id)
3852                        .or_insert(transaction_id);
3853                }
3854                true
3855            }
3856        } else {
3857            false
3858        }
3859    }
3860
3861    fn push_transaction<'a, T>(
3862        &mut self,
3863        buffer_transactions: T,
3864        now: Instant,
3865        cx: &mut ModelContext<MultiBuffer>,
3866    ) where
3867        T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
3868    {
3869        assert_eq!(self.transaction_depth, 0);
3870        let transaction = Transaction {
3871            id: self.next_transaction_id.tick(),
3872            buffer_transactions: buffer_transactions
3873                .into_iter()
3874                .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3875                .collect(),
3876            first_edit_at: now,
3877            last_edit_at: now,
3878            suppress_grouping: false,
3879        };
3880        if !transaction.buffer_transactions.is_empty() {
3881            self.undo_stack.push(transaction);
3882            self.redo_stack.clear();
3883        }
3884    }
3885
3886    fn finalize_last_transaction(&mut self) {
3887        if let Some(transaction) = self.undo_stack.last_mut() {
3888            transaction.suppress_grouping = true;
3889        }
3890    }
3891
3892    fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
3893        if let Some(ix) = self
3894            .undo_stack
3895            .iter()
3896            .rposition(|transaction| transaction.id == transaction_id)
3897        {
3898            Some(self.undo_stack.remove(ix))
3899        } else if let Some(ix) = self
3900            .redo_stack
3901            .iter()
3902            .rposition(|transaction| transaction.id == transaction_id)
3903        {
3904            Some(self.redo_stack.remove(ix))
3905        } else {
3906            None
3907        }
3908    }
3909
3910    fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
3911        self.undo_stack
3912            .iter_mut()
3913            .find(|transaction| transaction.id == transaction_id)
3914            .or_else(|| {
3915                self.redo_stack
3916                    .iter_mut()
3917                    .find(|transaction| transaction.id == transaction_id)
3918            })
3919    }
3920
3921    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3922        assert_eq!(self.transaction_depth, 0);
3923        if let Some(transaction) = self.undo_stack.pop() {
3924            self.redo_stack.push(transaction);
3925            self.redo_stack.last_mut()
3926        } else {
3927            None
3928        }
3929    }
3930
3931    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3932        assert_eq!(self.transaction_depth, 0);
3933        if let Some(transaction) = self.redo_stack.pop() {
3934            self.undo_stack.push(transaction);
3935            self.undo_stack.last_mut()
3936        } else {
3937            None
3938        }
3939    }
3940
3941    fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
3942        let ix = self
3943            .undo_stack
3944            .iter()
3945            .rposition(|transaction| transaction.id == transaction_id)?;
3946        let transaction = self.undo_stack.remove(ix);
3947        self.redo_stack.push(transaction);
3948        self.redo_stack.last()
3949    }
3950
3951    fn group(&mut self) -> Option<TransactionId> {
3952        let mut count = 0;
3953        let mut transactions = self.undo_stack.iter();
3954        if let Some(mut transaction) = transactions.next_back() {
3955            while let Some(prev_transaction) = transactions.next_back() {
3956                if !prev_transaction.suppress_grouping
3957                    && transaction.first_edit_at - prev_transaction.last_edit_at
3958                        <= self.group_interval
3959                {
3960                    transaction = prev_transaction;
3961                    count += 1;
3962                } else {
3963                    break;
3964                }
3965            }
3966        }
3967        self.group_trailing(count)
3968    }
3969
3970    fn group_until(&mut self, transaction_id: TransactionId) {
3971        let mut count = 0;
3972        for transaction in self.undo_stack.iter().rev() {
3973            if transaction.id == transaction_id {
3974                self.group_trailing(count);
3975                break;
3976            } else if transaction.suppress_grouping {
3977                break;
3978            } else {
3979                count += 1;
3980            }
3981        }
3982    }
3983
3984    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3985        let new_len = self.undo_stack.len() - n;
3986        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3987        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3988            if let Some(transaction) = transactions_to_merge.last() {
3989                last_transaction.last_edit_at = transaction.last_edit_at;
3990            }
3991            for to_merge in transactions_to_merge {
3992                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3993                    last_transaction
3994                        .buffer_transactions
3995                        .entry(*buffer_id)
3996                        .or_insert(*transaction_id);
3997                }
3998            }
3999        }
4000
4001        self.undo_stack.truncate(new_len);
4002        self.undo_stack.last().map(|t| t.id)
4003    }
4004}
4005
4006impl Excerpt {
4007    fn new(
4008        id: ExcerptId,
4009        locator: Locator,
4010        buffer_id: BufferId,
4011        buffer: BufferSnapshot,
4012        range: ExcerptRange<text::Anchor>,
4013        has_trailing_newline: bool,
4014    ) -> Self {
4015        Excerpt {
4016            id,
4017            locator,
4018            max_buffer_row: range.context.end.to_point(&buffer).row,
4019            text_summary: buffer
4020                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
4021            buffer_id,
4022            buffer,
4023            range,
4024            has_trailing_newline,
4025        }
4026    }
4027
4028    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
4029        let content_start = self.range.context.start.to_offset(&self.buffer);
4030        let chunks_start = content_start + range.start;
4031        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
4032
4033        let footer_height = if self.has_trailing_newline
4034            && range.start <= self.text_summary.len
4035            && range.end > self.text_summary.len
4036        {
4037            1
4038        } else {
4039            0
4040        };
4041
4042        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
4043
4044        ExcerptChunks {
4045            content_chunks,
4046            footer_height,
4047        }
4048    }
4049
4050    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4051        let content_start = self.range.context.start.to_offset(&self.buffer);
4052        let bytes_start = content_start + range.start;
4053        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4054        let footer_height = if self.has_trailing_newline
4055            && range.start <= self.text_summary.len
4056            && range.end > self.text_summary.len
4057        {
4058            1
4059        } else {
4060            0
4061        };
4062        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
4063
4064        ExcerptBytes {
4065            content_bytes,
4066            padding_height: footer_height,
4067            reversed: false,
4068        }
4069    }
4070
4071    fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
4072        let content_start = self.range.context.start.to_offset(&self.buffer);
4073        let bytes_start = content_start + range.start;
4074        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
4075        let footer_height = if self.has_trailing_newline
4076            && range.start <= self.text_summary.len
4077            && range.end > self.text_summary.len
4078        {
4079            1
4080        } else {
4081            0
4082        };
4083        let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
4084
4085        ExcerptBytes {
4086            content_bytes,
4087            padding_height: footer_height,
4088            reversed: true,
4089        }
4090    }
4091
4092    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
4093        if text_anchor
4094            .cmp(&self.range.context.start, &self.buffer)
4095            .is_lt()
4096        {
4097            self.range.context.start
4098        } else if text_anchor
4099            .cmp(&self.range.context.end, &self.buffer)
4100            .is_gt()
4101        {
4102            self.range.context.end
4103        } else {
4104            text_anchor
4105        }
4106    }
4107
4108    fn contains(&self, anchor: &Anchor) -> bool {
4109        Some(self.buffer_id) == anchor.buffer_id
4110            && self
4111                .range
4112                .context
4113                .start
4114                .cmp(&anchor.text_anchor, &self.buffer)
4115                .is_le()
4116            && self
4117                .range
4118                .context
4119                .end
4120                .cmp(&anchor.text_anchor, &self.buffer)
4121                .is_ge()
4122    }
4123
4124    /// The [`Excerpt`]'s start offset in its [`Buffer`]
4125    fn buffer_start_offset(&self) -> usize {
4126        self.range.context.start.to_offset(&self.buffer)
4127    }
4128
4129    /// The [`Excerpt`]'s end offset in its [`Buffer`]
4130    fn buffer_end_offset(&self) -> usize {
4131        self.buffer_start_offset() + self.text_summary.len
4132    }
4133}
4134
4135impl<'a> MultiBufferExcerpt<'a> {
4136    fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
4137        MultiBufferExcerpt {
4138            excerpt,
4139            excerpt_offset,
4140        }
4141    }
4142
4143    pub fn buffer(&self) -> &'a BufferSnapshot {
4144        &self.excerpt.buffer
4145    }
4146
4147    /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
4148    pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
4149        self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
4150    }
4151
4152    /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
4153    pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
4154        self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
4155    }
4156
4157    /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
4158    pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
4159        let mut buffer_offset_in_excerpt =
4160            buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
4161        buffer_offset_in_excerpt =
4162            cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
4163
4164        self.excerpt_offset + buffer_offset_in_excerpt
4165    }
4166
4167    /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
4168    pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
4169        self.map_offset_from_buffer(buffer_range.start)
4170            ..self.map_offset_from_buffer(buffer_range.end)
4171    }
4172
4173    /// Returns true if the entirety of the given range is in the buffer's excerpt
4174    pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
4175        range.start >= self.excerpt.buffer_start_offset()
4176            && range.end <= self.excerpt.buffer_end_offset()
4177    }
4178}
4179
4180impl ExcerptId {
4181    pub fn min() -> Self {
4182        Self(0)
4183    }
4184
4185    pub fn max() -> Self {
4186        Self(usize::MAX)
4187    }
4188
4189    pub fn to_proto(&self) -> u64 {
4190        self.0 as _
4191    }
4192
4193    pub fn from_proto(proto: u64) -> Self {
4194        Self(proto as _)
4195    }
4196
4197    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
4198        let a = snapshot.excerpt_locator_for_id(*self);
4199        let b = snapshot.excerpt_locator_for_id(*other);
4200        a.cmp(b).then_with(|| self.0.cmp(&other.0))
4201    }
4202}
4203
4204impl Into<usize> for ExcerptId {
4205    fn into(self) -> usize {
4206        self.0
4207    }
4208}
4209
4210impl fmt::Debug for Excerpt {
4211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4212        f.debug_struct("Excerpt")
4213            .field("id", &self.id)
4214            .field("locator", &self.locator)
4215            .field("buffer_id", &self.buffer_id)
4216            .field("range", &self.range)
4217            .field("text_summary", &self.text_summary)
4218            .field("has_trailing_newline", &self.has_trailing_newline)
4219            .finish()
4220    }
4221}
4222
4223impl sum_tree::Item for Excerpt {
4224    type Summary = ExcerptSummary;
4225
4226    fn summary(&self) -> Self::Summary {
4227        let mut text = self.text_summary.clone();
4228        if self.has_trailing_newline {
4229            text += TextSummary::from("\n");
4230        }
4231        ExcerptSummary {
4232            excerpt_id: self.id,
4233            excerpt_locator: self.locator.clone(),
4234            max_buffer_row: MultiBufferRow(self.max_buffer_row),
4235            text,
4236        }
4237    }
4238}
4239
4240impl sum_tree::Item for ExcerptIdMapping {
4241    type Summary = ExcerptId;
4242
4243    fn summary(&self) -> Self::Summary {
4244        self.id
4245    }
4246}
4247
4248impl sum_tree::KeyedItem for ExcerptIdMapping {
4249    type Key = ExcerptId;
4250
4251    fn key(&self) -> Self::Key {
4252        self.id
4253    }
4254}
4255
4256impl sum_tree::Summary for ExcerptId {
4257    type Context = ();
4258
4259    fn add_summary(&mut self, other: &Self, _: &()) {
4260        *self = *other;
4261    }
4262}
4263
4264impl sum_tree::Summary for ExcerptSummary {
4265    type Context = ();
4266
4267    fn add_summary(&mut self, summary: &Self, _: &()) {
4268        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
4269        self.excerpt_locator = summary.excerpt_locator.clone();
4270        self.text.add_summary(&summary.text, &());
4271        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
4272    }
4273}
4274
4275impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
4276    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4277        *self += &summary.text;
4278    }
4279}
4280
4281impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
4282    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4283        *self += summary.text.len;
4284    }
4285}
4286
4287impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
4288    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4289        Ord::cmp(self, &cursor_location.text.len)
4290    }
4291}
4292
4293impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
4294    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
4295        Ord::cmp(&Some(self), cursor_location)
4296    }
4297}
4298
4299impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
4300    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4301        Ord::cmp(self, &cursor_location.excerpt_locator)
4302    }
4303}
4304
4305impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
4306    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4307        *self += summary.text.len_utf16;
4308    }
4309}
4310
4311impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
4312    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4313        *self += summary.text.lines;
4314    }
4315}
4316
4317impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
4318    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4319        *self += summary.text.lines_utf16()
4320    }
4321}
4322
4323impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
4324    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4325        *self = Some(&summary.excerpt_locator);
4326    }
4327}
4328
4329impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
4330    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4331        *self = Some(summary.excerpt_id);
4332    }
4333}
4334
4335impl<'a> MultiBufferRows<'a> {
4336    pub fn seek(&mut self, row: MultiBufferRow) {
4337        self.buffer_row_range = 0..0;
4338
4339        self.excerpts
4340            .seek_forward(&Point::new(row.0, 0), Bias::Right, &());
4341        if self.excerpts.item().is_none() {
4342            self.excerpts.prev(&());
4343
4344            if self.excerpts.item().is_none() && row.0 == 0 {
4345                self.buffer_row_range = 0..1;
4346                return;
4347            }
4348        }
4349
4350        if let Some(excerpt) = self.excerpts.item() {
4351            let overshoot = row.0 - self.excerpts.start().row;
4352            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4353            self.buffer_row_range.start = excerpt_start + overshoot;
4354            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4355        }
4356    }
4357}
4358
4359impl<'a> Iterator for MultiBufferRows<'a> {
4360    type Item = Option<u32>;
4361
4362    fn next(&mut self) -> Option<Self::Item> {
4363        loop {
4364            if !self.buffer_row_range.is_empty() {
4365                let row = Some(self.buffer_row_range.start);
4366                self.buffer_row_range.start += 1;
4367                return Some(row);
4368            }
4369            self.excerpts.item()?;
4370            self.excerpts.next(&());
4371            let excerpt = self.excerpts.item()?;
4372            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4373            self.buffer_row_range.end =
4374                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4375        }
4376    }
4377}
4378
4379impl<'a> MultiBufferChunks<'a> {
4380    pub fn offset(&self) -> usize {
4381        self.range.start
4382    }
4383
4384    pub fn seek(&mut self, offset: usize) {
4385        self.range.start = offset;
4386        self.excerpts.seek(&offset, Bias::Right, &());
4387        if let Some(excerpt) = self.excerpts.item() {
4388            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4389                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
4390                self.language_aware,
4391            ));
4392        } else {
4393            self.excerpt_chunks = None;
4394        }
4395    }
4396}
4397
4398impl<'a> Iterator for MultiBufferChunks<'a> {
4399    type Item = Chunk<'a>;
4400
4401    fn next(&mut self) -> Option<Self::Item> {
4402        if self.range.is_empty() {
4403            None
4404        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4405            self.range.start += chunk.text.len();
4406            Some(chunk)
4407        } else {
4408            self.excerpts.next(&());
4409            let excerpt = self.excerpts.item()?;
4410            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4411                0..self.range.end - self.excerpts.start(),
4412                self.language_aware,
4413            ));
4414            self.next()
4415        }
4416    }
4417}
4418
4419impl<'a> MultiBufferBytes<'a> {
4420    fn consume(&mut self, len: usize) {
4421        self.range.start += len;
4422        self.chunk = &self.chunk[len..];
4423
4424        if !self.range.is_empty() && self.chunk.is_empty() {
4425            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4426                self.chunk = chunk;
4427            } else {
4428                self.excerpts.next(&());
4429                if let Some(excerpt) = self.excerpts.item() {
4430                    let mut excerpt_bytes =
4431                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4432                    self.chunk = excerpt_bytes.next().unwrap();
4433                    self.excerpt_bytes = Some(excerpt_bytes);
4434                }
4435            }
4436        }
4437    }
4438}
4439
4440impl<'a> Iterator for MultiBufferBytes<'a> {
4441    type Item = &'a [u8];
4442
4443    fn next(&mut self) -> Option<Self::Item> {
4444        let chunk = self.chunk;
4445        if chunk.is_empty() {
4446            None
4447        } else {
4448            self.consume(chunk.len());
4449            Some(chunk)
4450        }
4451    }
4452}
4453
4454impl<'a> io::Read for MultiBufferBytes<'a> {
4455    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4456        let len = cmp::min(buf.len(), self.chunk.len());
4457        buf[..len].copy_from_slice(&self.chunk[..len]);
4458        if len > 0 {
4459            self.consume(len);
4460        }
4461        Ok(len)
4462    }
4463}
4464
4465impl<'a> ReversedMultiBufferBytes<'a> {
4466    fn consume(&mut self, len: usize) {
4467        self.range.end -= len;
4468        self.chunk = &self.chunk[..self.chunk.len() - len];
4469
4470        if !self.range.is_empty() && self.chunk.is_empty() {
4471            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4472                self.chunk = chunk;
4473            } else {
4474                self.excerpts.prev(&());
4475                if let Some(excerpt) = self.excerpts.item() {
4476                    let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
4477                        self.range.start.saturating_sub(*self.excerpts.start())..usize::MAX,
4478                    );
4479                    self.chunk = excerpt_bytes.next().unwrap();
4480                    self.excerpt_bytes = Some(excerpt_bytes);
4481                }
4482            }
4483        } else {
4484        }
4485    }
4486}
4487
4488impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4489    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4490        let len = cmp::min(buf.len(), self.chunk.len());
4491        buf[..len].copy_from_slice(&self.chunk[..len]);
4492        buf[..len].reverse();
4493        if len > 0 {
4494            self.consume(len);
4495        }
4496        Ok(len)
4497    }
4498}
4499impl<'a> Iterator for ExcerptBytes<'a> {
4500    type Item = &'a [u8];
4501
4502    fn next(&mut self) -> Option<Self::Item> {
4503        if self.reversed && self.padding_height > 0 {
4504            let result = &NEWLINES[..self.padding_height];
4505            self.padding_height = 0;
4506            return Some(result);
4507        }
4508
4509        if let Some(chunk) = self.content_bytes.next() {
4510            if !chunk.is_empty() {
4511                return Some(chunk);
4512            }
4513        }
4514
4515        if self.padding_height > 0 {
4516            let result = &NEWLINES[..self.padding_height];
4517            self.padding_height = 0;
4518            return Some(result);
4519        }
4520
4521        None
4522    }
4523}
4524
4525impl<'a> Iterator for ExcerptChunks<'a> {
4526    type Item = Chunk<'a>;
4527
4528    fn next(&mut self) -> Option<Self::Item> {
4529        if let Some(chunk) = self.content_chunks.next() {
4530            return Some(chunk);
4531        }
4532
4533        if self.footer_height > 0 {
4534            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4535            self.footer_height = 0;
4536            return Some(Chunk {
4537                text,
4538                ..Default::default()
4539            });
4540        }
4541
4542        None
4543    }
4544}
4545
4546impl ToOffset for Point {
4547    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4548        snapshot.point_to_offset(*self)
4549    }
4550}
4551
4552impl ToOffset for usize {
4553    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4554        assert!(*self <= snapshot.len(), "offset is out of range");
4555        *self
4556    }
4557}
4558
4559impl ToOffset for OffsetUtf16 {
4560    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4561        snapshot.offset_utf16_to_offset(*self)
4562    }
4563}
4564
4565impl ToOffset for PointUtf16 {
4566    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4567        snapshot.point_utf16_to_offset(*self)
4568    }
4569}
4570
4571impl ToOffsetUtf16 for OffsetUtf16 {
4572    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4573        *self
4574    }
4575}
4576
4577impl ToOffsetUtf16 for usize {
4578    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4579        snapshot.offset_to_offset_utf16(*self)
4580    }
4581}
4582
4583impl ToPoint for usize {
4584    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
4585        snapshot.offset_to_point(*self)
4586    }
4587}
4588
4589impl ToPoint for Point {
4590    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
4591        *self
4592    }
4593}
4594
4595impl ToPointUtf16 for usize {
4596    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4597        snapshot.offset_to_point_utf16(*self)
4598    }
4599}
4600
4601impl ToPointUtf16 for Point {
4602    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4603        snapshot.point_to_point_utf16(*self)
4604    }
4605}
4606
4607impl ToPointUtf16 for PointUtf16 {
4608    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
4609        *self
4610    }
4611}
4612
4613fn build_excerpt_ranges<T>(
4614    buffer: &BufferSnapshot,
4615    ranges: &[Range<T>],
4616    context_line_count: u32,
4617) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
4618where
4619    T: text::ToPoint,
4620{
4621    let max_point = buffer.max_point();
4622    let mut range_counts = Vec::new();
4623    let mut excerpt_ranges = Vec::new();
4624    let mut range_iter = ranges
4625        .iter()
4626        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
4627        .peekable();
4628    while let Some(range) = range_iter.next() {
4629        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
4630        let row = (range.end.row + context_line_count).min(max_point.row);
4631        let mut excerpt_end = Point::new(row, buffer.line_len(row));
4632
4633        let mut ranges_in_excerpt = 1;
4634
4635        while let Some(next_range) = range_iter.peek() {
4636            if next_range.start.row <= excerpt_end.row + context_line_count {
4637                let row = (next_range.end.row + context_line_count).min(max_point.row);
4638                excerpt_end = Point::new(row, buffer.line_len(row));
4639
4640                ranges_in_excerpt += 1;
4641                range_iter.next();
4642            } else {
4643                break;
4644            }
4645        }
4646
4647        excerpt_ranges.push(ExcerptRange {
4648            context: excerpt_start..excerpt_end,
4649            primary: Some(range),
4650        });
4651        range_counts.push(ranges_in_excerpt);
4652    }
4653
4654    (excerpt_ranges, range_counts)
4655}
4656
4657#[cfg(test)]
4658mod tests {
4659    use super::*;
4660    use futures::StreamExt;
4661    use gpui::{AppContext, Context, TestAppContext};
4662    use language::{Buffer, Rope};
4663    use parking_lot::RwLock;
4664    use rand::prelude::*;
4665    use settings::SettingsStore;
4666    use std::env;
4667    use util::test::sample_text;
4668
4669    #[ctor::ctor]
4670    fn init_logger() {
4671        if std::env::var("RUST_LOG").is_ok() {
4672            env_logger::init();
4673        }
4674    }
4675
4676    #[gpui::test]
4677    fn test_singleton(cx: &mut AppContext) {
4678        let buffer = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4679        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4680
4681        let snapshot = multibuffer.read(cx).snapshot(cx);
4682        assert_eq!(snapshot.text(), buffer.read(cx).text());
4683
4684        assert_eq!(
4685            snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4686            (0..buffer.read(cx).row_count())
4687                .map(Some)
4688                .collect::<Vec<_>>()
4689        );
4690
4691        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4692        let snapshot = multibuffer.read(cx).snapshot(cx);
4693
4694        assert_eq!(snapshot.text(), buffer.read(cx).text());
4695        assert_eq!(
4696            snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4697            (0..buffer.read(cx).row_count())
4698                .map(Some)
4699                .collect::<Vec<_>>()
4700        );
4701    }
4702
4703    #[gpui::test]
4704    fn test_remote(cx: &mut AppContext) {
4705        let host_buffer = cx.new_model(|cx| Buffer::local("a", cx));
4706        let guest_buffer = cx.new_model(|cx| {
4707            let state = host_buffer.read(cx).to_proto();
4708            let ops = cx
4709                .background_executor()
4710                .block(host_buffer.read(cx).serialize_ops(None, cx));
4711            let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
4712            buffer
4713                .apply_ops(
4714                    ops.into_iter()
4715                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
4716                    cx,
4717                )
4718                .unwrap();
4719            buffer
4720        });
4721        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4722        let snapshot = multibuffer.read(cx).snapshot(cx);
4723        assert_eq!(snapshot.text(), "a");
4724
4725        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4726        let snapshot = multibuffer.read(cx).snapshot(cx);
4727        assert_eq!(snapshot.text(), "ab");
4728
4729        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4730        let snapshot = multibuffer.read(cx).snapshot(cx);
4731        assert_eq!(snapshot.text(), "abc");
4732    }
4733
4734    #[gpui::test]
4735    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4736        let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4737        let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
4738        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4739
4740        let events = Arc::new(RwLock::new(Vec::<Event>::new()));
4741        multibuffer.update(cx, |_, cx| {
4742            let events = events.clone();
4743            cx.subscribe(&multibuffer, move |_, _, event, _| {
4744                if let Event::Edited { .. } = event {
4745                    events.write().push(event.clone())
4746                }
4747            })
4748            .detach();
4749        });
4750
4751        let subscription = multibuffer.update(cx, |multibuffer, cx| {
4752            let subscription = multibuffer.subscribe();
4753            multibuffer.push_excerpts(
4754                buffer_1.clone(),
4755                [ExcerptRange {
4756                    context: Point::new(1, 2)..Point::new(2, 5),
4757                    primary: None,
4758                }],
4759                cx,
4760            );
4761            assert_eq!(
4762                subscription.consume().into_inner(),
4763                [Edit {
4764                    old: 0..0,
4765                    new: 0..10
4766                }]
4767            );
4768
4769            multibuffer.push_excerpts(
4770                buffer_1.clone(),
4771                [ExcerptRange {
4772                    context: Point::new(3, 3)..Point::new(4, 4),
4773                    primary: None,
4774                }],
4775                cx,
4776            );
4777            multibuffer.push_excerpts(
4778                buffer_2.clone(),
4779                [ExcerptRange {
4780                    context: Point::new(3, 1)..Point::new(3, 3),
4781                    primary: None,
4782                }],
4783                cx,
4784            );
4785            assert_eq!(
4786                subscription.consume().into_inner(),
4787                [Edit {
4788                    old: 10..10,
4789                    new: 10..22
4790                }]
4791            );
4792
4793            subscription
4794        });
4795
4796        // Adding excerpts emits an edited event.
4797        assert_eq!(
4798            events.read().as_slice(),
4799            &[
4800                Event::Edited {
4801                    singleton_buffer_edited: false
4802                },
4803                Event::Edited {
4804                    singleton_buffer_edited: false
4805                },
4806                Event::Edited {
4807                    singleton_buffer_edited: false
4808                }
4809            ]
4810        );
4811
4812        let snapshot = multibuffer.read(cx).snapshot(cx);
4813        assert_eq!(
4814            snapshot.text(),
4815            concat!(
4816                "bbbb\n",  // Preserve newlines
4817                "ccccc\n", //
4818                "ddd\n",   //
4819                "eeee\n",  //
4820                "jj"       //
4821            )
4822        );
4823        assert_eq!(
4824            snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
4825            [Some(1), Some(2), Some(3), Some(4), Some(3)]
4826        );
4827        assert_eq!(
4828            snapshot.buffer_rows(MultiBufferRow(2)).collect::<Vec<_>>(),
4829            [Some(3), Some(4), Some(3)]
4830        );
4831        assert_eq!(
4832            snapshot.buffer_rows(MultiBufferRow(4)).collect::<Vec<_>>(),
4833            [Some(3)]
4834        );
4835        assert_eq!(
4836            snapshot.buffer_rows(MultiBufferRow(5)).collect::<Vec<_>>(),
4837            []
4838        );
4839
4840        assert_eq!(
4841            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4842            &[
4843                (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
4844                (MultiBufferRow(2), "ddd\neeee".to_string(), false),
4845                (MultiBufferRow(4), "jj".to_string(), true),
4846            ]
4847        );
4848        assert_eq!(
4849            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4850            &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
4851        );
4852        assert_eq!(
4853            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4854            &[]
4855        );
4856        assert_eq!(
4857            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4858            &[]
4859        );
4860        assert_eq!(
4861            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4862            &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4863        );
4864        assert_eq!(
4865            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4866            &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4867        );
4868        assert_eq!(
4869            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4870            &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
4871        );
4872        assert_eq!(
4873            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4874            &[(MultiBufferRow(4), "jj".to_string(), true)]
4875        );
4876        assert_eq!(
4877            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4878            &[]
4879        );
4880
4881        buffer_1.update(cx, |buffer, cx| {
4882            let text = "\n";
4883            buffer.edit(
4884                [
4885                    (Point::new(0, 0)..Point::new(0, 0), text),
4886                    (Point::new(2, 1)..Point::new(2, 3), text),
4887                ],
4888                None,
4889                cx,
4890            );
4891        });
4892
4893        let snapshot = multibuffer.read(cx).snapshot(cx);
4894        assert_eq!(
4895            snapshot.text(),
4896            concat!(
4897                "bbbb\n", // Preserve newlines
4898                "c\n",    //
4899                "cc\n",   //
4900                "ddd\n",  //
4901                "eeee\n", //
4902                "jj"      //
4903            )
4904        );
4905
4906        assert_eq!(
4907            subscription.consume().into_inner(),
4908            [Edit {
4909                old: 6..8,
4910                new: 6..7
4911            }]
4912        );
4913
4914        let snapshot = multibuffer.read(cx).snapshot(cx);
4915        assert_eq!(
4916            snapshot.clip_point(Point::new(0, 5), Bias::Left),
4917            Point::new(0, 4)
4918        );
4919        assert_eq!(
4920            snapshot.clip_point(Point::new(0, 5), Bias::Right),
4921            Point::new(0, 4)
4922        );
4923        assert_eq!(
4924            snapshot.clip_point(Point::new(5, 1), Bias::Right),
4925            Point::new(5, 1)
4926        );
4927        assert_eq!(
4928            snapshot.clip_point(Point::new(5, 2), Bias::Right),
4929            Point::new(5, 2)
4930        );
4931        assert_eq!(
4932            snapshot.clip_point(Point::new(5, 3), Bias::Right),
4933            Point::new(5, 2)
4934        );
4935
4936        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4937            let (buffer_2_excerpt_id, _) =
4938                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4939            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4940            multibuffer.snapshot(cx)
4941        });
4942
4943        assert_eq!(
4944            snapshot.text(),
4945            concat!(
4946                "bbbb\n", // Preserve newlines
4947                "c\n",    //
4948                "cc\n",   //
4949                "ddd\n",  //
4950                "eeee",   //
4951            )
4952        );
4953
4954        fn boundaries_in_range(
4955            range: Range<Point>,
4956            snapshot: &MultiBufferSnapshot,
4957        ) -> Vec<(MultiBufferRow, String, bool)> {
4958            snapshot
4959                .excerpt_boundaries_in_range(range)
4960                .filter_map(|boundary| {
4961                    let starts_new_buffer = boundary.starts_new_buffer();
4962                    boundary.next.map(|next| {
4963                        (
4964                            boundary.row,
4965                            next.buffer
4966                                .text_for_range(next.range.context)
4967                                .collect::<String>(),
4968                            starts_new_buffer,
4969                        )
4970                    })
4971                })
4972                .collect::<Vec<_>>()
4973        }
4974    }
4975
4976    #[gpui::test]
4977    fn test_excerpt_events(cx: &mut AppContext) {
4978        let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
4979        let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
4980
4981        let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4982        let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4983        let follower_edit_event_count = Arc::new(RwLock::new(0));
4984
4985        follower_multibuffer.update(cx, |_, cx| {
4986            let follower_edit_event_count = follower_edit_event_count.clone();
4987            cx.subscribe(
4988                &leader_multibuffer,
4989                move |follower, _, event, cx| match event.clone() {
4990                    Event::ExcerptsAdded {
4991                        buffer,
4992                        predecessor,
4993                        excerpts,
4994                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4995                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4996                    Event::Edited { .. } => {
4997                        *follower_edit_event_count.write() += 1;
4998                    }
4999                    _ => {}
5000                },
5001            )
5002            .detach();
5003        });
5004
5005        leader_multibuffer.update(cx, |leader, cx| {
5006            leader.push_excerpts(
5007                buffer_1.clone(),
5008                [
5009                    ExcerptRange {
5010                        context: 0..8,
5011                        primary: None,
5012                    },
5013                    ExcerptRange {
5014                        context: 12..16,
5015                        primary: None,
5016                    },
5017                ],
5018                cx,
5019            );
5020            leader.insert_excerpts_after(
5021                leader.excerpt_ids()[0],
5022                buffer_2.clone(),
5023                [
5024                    ExcerptRange {
5025                        context: 0..5,
5026                        primary: None,
5027                    },
5028                    ExcerptRange {
5029                        context: 10..15,
5030                        primary: None,
5031                    },
5032                ],
5033                cx,
5034            )
5035        });
5036        assert_eq!(
5037            leader_multibuffer.read(cx).snapshot(cx).text(),
5038            follower_multibuffer.read(cx).snapshot(cx).text(),
5039        );
5040        assert_eq!(*follower_edit_event_count.read(), 2);
5041
5042        leader_multibuffer.update(cx, |leader, cx| {
5043            let excerpt_ids = leader.excerpt_ids();
5044            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
5045        });
5046        assert_eq!(
5047            leader_multibuffer.read(cx).snapshot(cx).text(),
5048            follower_multibuffer.read(cx).snapshot(cx).text(),
5049        );
5050        assert_eq!(*follower_edit_event_count.read(), 3);
5051
5052        // Removing an empty set of excerpts is a noop.
5053        leader_multibuffer.update(cx, |leader, cx| {
5054            leader.remove_excerpts([], cx);
5055        });
5056        assert_eq!(
5057            leader_multibuffer.read(cx).snapshot(cx).text(),
5058            follower_multibuffer.read(cx).snapshot(cx).text(),
5059        );
5060        assert_eq!(*follower_edit_event_count.read(), 3);
5061
5062        // Adding an empty set of excerpts is a noop.
5063        leader_multibuffer.update(cx, |leader, cx| {
5064            leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
5065        });
5066        assert_eq!(
5067            leader_multibuffer.read(cx).snapshot(cx).text(),
5068            follower_multibuffer.read(cx).snapshot(cx).text(),
5069        );
5070        assert_eq!(*follower_edit_event_count.read(), 3);
5071
5072        leader_multibuffer.update(cx, |leader, cx| {
5073            leader.clear(cx);
5074        });
5075        assert_eq!(
5076            leader_multibuffer.read(cx).snapshot(cx).text(),
5077            follower_multibuffer.read(cx).snapshot(cx).text(),
5078        );
5079        assert_eq!(*follower_edit_event_count.read(), 4);
5080    }
5081
5082    #[gpui::test]
5083    fn test_expand_excerpts(cx: &mut AppContext) {
5084        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5085        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5086
5087        multibuffer.update(cx, |multibuffer, cx| {
5088            multibuffer.push_excerpts_with_context_lines(
5089                buffer.clone(),
5090                vec![
5091                    // Note that in this test, this first excerpt
5092                    // does not contain a new line
5093                    Point::new(3, 2)..Point::new(3, 3),
5094                    Point::new(7, 1)..Point::new(7, 3),
5095                    Point::new(15, 0)..Point::new(15, 0),
5096                ],
5097                1,
5098                cx,
5099            )
5100        });
5101
5102        let snapshot = multibuffer.read(cx).snapshot(cx);
5103
5104        assert_eq!(
5105            snapshot.text(),
5106            concat!(
5107                "ccc\n", //
5108                "ddd\n", //
5109                "eee",   //
5110                "\n",    // End of excerpt
5111                "ggg\n", //
5112                "hhh\n", //
5113                "iii",   //
5114                "\n",    // End of excerpt
5115                "ooo\n", //
5116                "ppp\n", //
5117                "qqq",   // End of excerpt
5118            )
5119        );
5120        drop(snapshot);
5121
5122        multibuffer.update(cx, |multibuffer, cx| {
5123            multibuffer.expand_excerpts(
5124                multibuffer.excerpt_ids(),
5125                1,
5126                ExpandExcerptDirection::UpAndDown,
5127                cx,
5128            )
5129        });
5130
5131        let snapshot = multibuffer.read(cx).snapshot(cx);
5132
5133        // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
5134        // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
5135        // that are tracking excerpt ids.
5136        assert_eq!(
5137            snapshot.text(),
5138            concat!(
5139                "bbb\n", //
5140                "ccc\n", //
5141                "ddd\n", //
5142                "eee\n", //
5143                "fff\n", // End of excerpt
5144                "fff\n", //
5145                "ggg\n", //
5146                "hhh\n", //
5147                "iii\n", //
5148                "jjj\n", // End of excerpt
5149                "nnn\n", //
5150                "ooo\n", //
5151                "ppp\n", //
5152                "qqq\n", //
5153                "rrr",   // End of excerpt
5154            )
5155        );
5156    }
5157
5158    #[gpui::test]
5159    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
5160        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5161        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5162        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5163            multibuffer.push_excerpts_with_context_lines(
5164                buffer.clone(),
5165                vec![
5166                    // Note that in this test, this first excerpt
5167                    // does contain a new line
5168                    Point::new(3, 2)..Point::new(4, 2),
5169                    Point::new(7, 1)..Point::new(7, 3),
5170                    Point::new(15, 0)..Point::new(15, 0),
5171                ],
5172                2,
5173                cx,
5174            )
5175        });
5176
5177        let snapshot = multibuffer.read(cx).snapshot(cx);
5178        assert_eq!(
5179            snapshot.text(),
5180            concat!(
5181                "bbb\n", // Preserve newlines
5182                "ccc\n", //
5183                "ddd\n", //
5184                "eee\n", //
5185                "fff\n", //
5186                "ggg\n", //
5187                "hhh\n", //
5188                "iii\n", //
5189                "jjj\n", //
5190                "nnn\n", //
5191                "ooo\n", //
5192                "ppp\n", //
5193                "qqq\n", //
5194                "rrr",   //
5195            )
5196        );
5197
5198        assert_eq!(
5199            anchor_ranges
5200                .iter()
5201                .map(|range| range.to_point(&snapshot))
5202                .collect::<Vec<_>>(),
5203            vec![
5204                Point::new(2, 2)..Point::new(3, 2),
5205                Point::new(6, 1)..Point::new(6, 3),
5206                Point::new(11, 0)..Point::new(11, 0)
5207            ]
5208        );
5209    }
5210
5211    #[gpui::test]
5212    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
5213        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5214        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5215        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5216            let snapshot = buffer.read(cx);
5217            let ranges = vec![
5218                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
5219                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
5220                snapshot.anchor_before(Point::new(15, 0))
5221                    ..snapshot.anchor_before(Point::new(15, 0)),
5222            ];
5223            multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
5224        });
5225
5226        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
5227
5228        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
5229        assert_eq!(
5230            snapshot.text(),
5231            concat!(
5232                "bbb\n", //
5233                "ccc\n", //
5234                "ddd\n", //
5235                "eee\n", //
5236                "fff\n", //
5237                "ggg\n", //
5238                "hhh\n", //
5239                "iii\n", //
5240                "jjj\n", //
5241                "nnn\n", //
5242                "ooo\n", //
5243                "ppp\n", //
5244                "qqq\n", //
5245                "rrr",   //
5246            )
5247        );
5248
5249        assert_eq!(
5250            anchor_ranges
5251                .iter()
5252                .map(|range| range.to_point(&snapshot))
5253                .collect::<Vec<_>>(),
5254            vec![
5255                Point::new(2, 2)..Point::new(3, 2),
5256                Point::new(6, 1)..Point::new(6, 3),
5257                Point::new(11, 0)..Point::new(11, 0)
5258            ]
5259        );
5260    }
5261
5262    #[gpui::test]
5263    fn test_empty_multibuffer(cx: &mut AppContext) {
5264        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5265
5266        let snapshot = multibuffer.read(cx).snapshot(cx);
5267        assert_eq!(snapshot.text(), "");
5268        assert_eq!(
5269            snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5270            &[Some(0)]
5271        );
5272        assert_eq!(
5273            snapshot.buffer_rows(MultiBufferRow(1)).collect::<Vec<_>>(),
5274            &[]
5275        );
5276    }
5277
5278    #[gpui::test]
5279    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
5280        let buffer = cx.new_model(|cx| Buffer::local("abcd", cx));
5281        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5282        let old_snapshot = multibuffer.read(cx).snapshot(cx);
5283        buffer.update(cx, |buffer, cx| {
5284            buffer.edit([(0..0, "X")], None, cx);
5285            buffer.edit([(5..5, "Y")], None, cx);
5286        });
5287        let new_snapshot = multibuffer.read(cx).snapshot(cx);
5288
5289        assert_eq!(old_snapshot.text(), "abcd");
5290        assert_eq!(new_snapshot.text(), "XabcdY");
5291
5292        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5293        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5294        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
5295        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
5296    }
5297
5298    #[gpui::test]
5299    fn test_multibuffer_anchors(cx: &mut AppContext) {
5300        let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5301        let buffer_2 = cx.new_model(|cx| Buffer::local("efghi", cx));
5302        let multibuffer = cx.new_model(|cx| {
5303            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
5304            multibuffer.push_excerpts(
5305                buffer_1.clone(),
5306                [ExcerptRange {
5307                    context: 0..4,
5308                    primary: None,
5309                }],
5310                cx,
5311            );
5312            multibuffer.push_excerpts(
5313                buffer_2.clone(),
5314                [ExcerptRange {
5315                    context: 0..5,
5316                    primary: None,
5317                }],
5318                cx,
5319            );
5320            multibuffer
5321        });
5322        let old_snapshot = multibuffer.read(cx).snapshot(cx);
5323
5324        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
5325        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
5326        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5327        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5328        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5329        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5330
5331        buffer_1.update(cx, |buffer, cx| {
5332            buffer.edit([(0..0, "W")], None, cx);
5333            buffer.edit([(5..5, "X")], None, cx);
5334        });
5335        buffer_2.update(cx, |buffer, cx| {
5336            buffer.edit([(0..0, "Y")], None, cx);
5337            buffer.edit([(6..6, "Z")], None, cx);
5338        });
5339        let new_snapshot = multibuffer.read(cx).snapshot(cx);
5340
5341        assert_eq!(old_snapshot.text(), "abcd\nefghi");
5342        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
5343
5344        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5345        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5346        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
5347        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
5348        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
5349        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
5350        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
5351        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
5352        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
5353        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
5354    }
5355
5356    #[gpui::test]
5357    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
5358        let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5359        let buffer_2 = cx.new_model(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
5360        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5361
5362        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
5363        // Add an excerpt from buffer 1 that spans this new insertion.
5364        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
5365        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
5366            multibuffer
5367                .push_excerpts(
5368                    buffer_1.clone(),
5369                    [ExcerptRange {
5370                        context: 0..7,
5371                        primary: None,
5372                    }],
5373                    cx,
5374                )
5375                .pop()
5376                .unwrap()
5377        });
5378
5379        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
5380        assert_eq!(snapshot_1.text(), "abcd123");
5381
5382        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
5383        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
5384            multibuffer.remove_excerpts([excerpt_id_1], cx);
5385            let mut ids = multibuffer
5386                .push_excerpts(
5387                    buffer_2.clone(),
5388                    [
5389                        ExcerptRange {
5390                            context: 0..4,
5391                            primary: None,
5392                        },
5393                        ExcerptRange {
5394                            context: 6..10,
5395                            primary: None,
5396                        },
5397                        ExcerptRange {
5398                            context: 12..16,
5399                            primary: None,
5400                        },
5401                    ],
5402                    cx,
5403                )
5404                .into_iter();
5405            (ids.next().unwrap(), ids.next().unwrap())
5406        });
5407        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
5408        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
5409
5410        // The old excerpt id doesn't get reused.
5411        assert_ne!(excerpt_id_2, excerpt_id_1);
5412
5413        // Resolve some anchors from the previous snapshot in the new snapshot.
5414        // The current excerpts are from a different buffer, so we don't attempt to
5415        // resolve the old text anchor in the new buffer.
5416        assert_eq!(
5417            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
5418            0
5419        );
5420        assert_eq!(
5421            snapshot_2.summaries_for_anchors::<usize, _>(&[
5422                snapshot_1.anchor_before(2),
5423                snapshot_1.anchor_after(3)
5424            ]),
5425            vec![0, 0]
5426        );
5427
5428        // Refresh anchors from the old snapshot. The return value indicates that both
5429        // anchors lost their original excerpt.
5430        let refresh =
5431            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5432        assert_eq!(
5433            refresh,
5434            &[
5435                (0, snapshot_2.anchor_before(0), false),
5436                (1, snapshot_2.anchor_after(0), false),
5437            ]
5438        );
5439
5440        // Replace the middle excerpt with a smaller excerpt in buffer 2,
5441        // that intersects the old excerpt.
5442        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5443            multibuffer.remove_excerpts([excerpt_id_3], cx);
5444            multibuffer
5445                .insert_excerpts_after(
5446                    excerpt_id_2,
5447                    buffer_2.clone(),
5448                    [ExcerptRange {
5449                        context: 5..8,
5450                        primary: None,
5451                    }],
5452                    cx,
5453                )
5454                .pop()
5455                .unwrap()
5456        });
5457
5458        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5459        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5460        assert_ne!(excerpt_id_5, excerpt_id_3);
5461
5462        // Resolve some anchors from the previous snapshot in the new snapshot.
5463        // The third anchor can't be resolved, since its excerpt has been removed,
5464        // so it resolves to the same position as its predecessor.
5465        let anchors = [
5466            snapshot_2.anchor_before(0),
5467            snapshot_2.anchor_after(2),
5468            snapshot_2.anchor_after(6),
5469            snapshot_2.anchor_after(14),
5470        ];
5471        assert_eq!(
5472            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5473            &[0, 2, 9, 13]
5474        );
5475
5476        let new_anchors = snapshot_3.refresh_anchors(&anchors);
5477        assert_eq!(
5478            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5479            &[(0, true), (1, true), (2, true), (3, true)]
5480        );
5481        assert_eq!(
5482            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5483            &[0, 2, 7, 13]
5484        );
5485    }
5486
5487    #[gpui::test(iterations = 100)]
5488    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5489        let operations = env::var("OPERATIONS")
5490            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5491            .unwrap_or(10);
5492
5493        let mut buffers: Vec<Model<Buffer>> = Vec::new();
5494        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5495        let mut excerpt_ids = Vec::<ExcerptId>::new();
5496        let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5497        let mut anchors = Vec::new();
5498        let mut old_versions = Vec::new();
5499
5500        for _ in 0..operations {
5501            match rng.gen_range(0..100) {
5502                0..=14 if !buffers.is_empty() => {
5503                    let buffer = buffers.choose(&mut rng).unwrap();
5504                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5505                }
5506                15..=19 if !expected_excerpts.is_empty() => {
5507                    multibuffer.update(cx, |multibuffer, cx| {
5508                        let ids = multibuffer.excerpt_ids();
5509                        let mut excerpts = HashSet::default();
5510                        for _ in 0..rng.gen_range(0..ids.len()) {
5511                            excerpts.extend(ids.choose(&mut rng).copied());
5512                        }
5513
5514                        let line_count = rng.gen_range(0..5);
5515
5516                        let excerpt_ixs = excerpts
5517                            .iter()
5518                            .map(|id| excerpt_ids.iter().position(|i| i == id).unwrap())
5519                            .collect::<Vec<_>>();
5520                        log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
5521                        multibuffer.expand_excerpts(
5522                            excerpts.iter().cloned(),
5523                            line_count,
5524                            ExpandExcerptDirection::UpAndDown,
5525                            cx,
5526                        );
5527
5528                        if line_count > 0 {
5529                            for id in excerpts {
5530                                let excerpt_ix = excerpt_ids.iter().position(|&i| i == id).unwrap();
5531                                let (buffer, range) = &mut expected_excerpts[excerpt_ix];
5532                                let snapshot = buffer.read(cx).snapshot();
5533                                let mut point_range = range.to_point(&snapshot);
5534                                point_range.start =
5535                                    Point::new(point_range.start.row.saturating_sub(line_count), 0);
5536                                point_range.end = snapshot.clip_point(
5537                                    Point::new(point_range.end.row + line_count, 0),
5538                                    Bias::Left,
5539                                );
5540                                point_range.end.column = snapshot.line_len(point_range.end.row);
5541                                *range = snapshot.anchor_before(point_range.start)
5542                                    ..snapshot.anchor_after(point_range.end);
5543                            }
5544                        }
5545                    });
5546                }
5547                20..=29 if !expected_excerpts.is_empty() => {
5548                    let mut ids_to_remove = vec![];
5549                    for _ in 0..rng.gen_range(1..=3) {
5550                        if expected_excerpts.is_empty() {
5551                            break;
5552                        }
5553
5554                        let ix = rng.gen_range(0..expected_excerpts.len());
5555                        ids_to_remove.push(excerpt_ids.remove(ix));
5556                        let (buffer, range) = expected_excerpts.remove(ix);
5557                        let buffer = buffer.read(cx);
5558                        log::info!(
5559                            "Removing excerpt {}: {:?}",
5560                            ix,
5561                            buffer
5562                                .text_for_range(range.to_offset(buffer))
5563                                .collect::<String>(),
5564                        );
5565                    }
5566                    let snapshot = multibuffer.read(cx).read(cx);
5567                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
5568                    drop(snapshot);
5569                    multibuffer.update(cx, |multibuffer, cx| {
5570                        multibuffer.remove_excerpts(ids_to_remove, cx)
5571                    });
5572                }
5573                30..=39 if !expected_excerpts.is_empty() => {
5574                    let multibuffer = multibuffer.read(cx).read(cx);
5575                    let offset =
5576                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
5577                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
5578                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
5579                    anchors.push(multibuffer.anchor_at(offset, bias));
5580                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
5581                }
5582                40..=44 if !anchors.is_empty() => {
5583                    let multibuffer = multibuffer.read(cx).read(cx);
5584                    let prev_len = anchors.len();
5585                    anchors = multibuffer
5586                        .refresh_anchors(&anchors)
5587                        .into_iter()
5588                        .map(|a| a.1)
5589                        .collect();
5590
5591                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
5592                    // overshoot its boundaries.
5593                    assert_eq!(anchors.len(), prev_len);
5594                    for anchor in &anchors {
5595                        if anchor.excerpt_id == ExcerptId::min()
5596                            || anchor.excerpt_id == ExcerptId::max()
5597                        {
5598                            continue;
5599                        }
5600
5601                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
5602                        assert_eq!(excerpt.id, anchor.excerpt_id);
5603                        assert!(excerpt.contains(anchor));
5604                    }
5605                }
5606                _ => {
5607                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
5608                        let base_text = util::RandomCharIter::new(&mut rng)
5609                            .take(25)
5610                            .collect::<String>();
5611
5612                        buffers.push(cx.new_model(|cx| Buffer::local(base_text, cx)));
5613                        buffers.last().unwrap()
5614                    } else {
5615                        buffers.choose(&mut rng).unwrap()
5616                    };
5617
5618                    let buffer = buffer_handle.read(cx);
5619                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
5620                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5621                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
5622                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
5623                    let prev_excerpt_id = excerpt_ids
5624                        .get(prev_excerpt_ix)
5625                        .cloned()
5626                        .unwrap_or_else(ExcerptId::max);
5627                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
5628
5629                    log::info!(
5630                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
5631                        excerpt_ix,
5632                        expected_excerpts.len(),
5633                        buffer_handle.read(cx).remote_id(),
5634                        buffer.text(),
5635                        start_ix..end_ix,
5636                        &buffer.text()[start_ix..end_ix]
5637                    );
5638
5639                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
5640                        multibuffer
5641                            .insert_excerpts_after(
5642                                prev_excerpt_id,
5643                                buffer_handle.clone(),
5644                                [ExcerptRange {
5645                                    context: start_ix..end_ix,
5646                                    primary: None,
5647                                }],
5648                                cx,
5649                            )
5650                            .pop()
5651                            .unwrap()
5652                    });
5653
5654                    excerpt_ids.insert(excerpt_ix, excerpt_id);
5655                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5656                }
5657            }
5658
5659            if rng.gen_bool(0.3) {
5660                multibuffer.update(cx, |multibuffer, cx| {
5661                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5662                })
5663            }
5664
5665            let snapshot = multibuffer.read(cx).snapshot(cx);
5666
5667            let mut excerpt_starts = Vec::new();
5668            let mut expected_text = String::new();
5669            let mut expected_buffer_rows = Vec::new();
5670            for (buffer, range) in &expected_excerpts {
5671                let buffer = buffer.read(cx);
5672                let buffer_range = range.to_offset(buffer);
5673
5674                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5675                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5676                expected_text.push('\n');
5677
5678                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5679                    ..=buffer.offset_to_point(buffer_range.end).row;
5680                for row in buffer_row_range {
5681                    expected_buffer_rows.push(Some(row));
5682                }
5683            }
5684            // Remove final trailing newline.
5685            if !expected_excerpts.is_empty() {
5686                expected_text.pop();
5687            }
5688
5689            // Always report one buffer row
5690            if expected_buffer_rows.is_empty() {
5691                expected_buffer_rows.push(Some(0));
5692            }
5693
5694            assert_eq!(snapshot.text(), expected_text);
5695            log::info!("MultiBuffer text: {:?}", expected_text);
5696
5697            assert_eq!(
5698                snapshot.buffer_rows(MultiBufferRow(0)).collect::<Vec<_>>(),
5699                expected_buffer_rows,
5700            );
5701
5702            for _ in 0..5 {
5703                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5704                assert_eq!(
5705                    snapshot
5706                        .buffer_rows(MultiBufferRow(start_row as u32))
5707                        .collect::<Vec<_>>(),
5708                    &expected_buffer_rows[start_row..],
5709                    "buffer_rows({})",
5710                    start_row
5711                );
5712            }
5713
5714            assert_eq!(
5715                snapshot.max_buffer_row().0,
5716                expected_buffer_rows.into_iter().flatten().max().unwrap()
5717            );
5718
5719            let mut excerpt_starts = excerpt_starts.into_iter();
5720            for (buffer, range) in &expected_excerpts {
5721                let buffer = buffer.read(cx);
5722                let buffer_id = buffer.remote_id();
5723                let buffer_range = range.to_offset(buffer);
5724                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5725                let buffer_start_point_utf16 =
5726                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5727
5728                let excerpt_start = excerpt_starts.next().unwrap();
5729                let mut offset = excerpt_start.len;
5730                let mut buffer_offset = buffer_range.start;
5731                let mut point = excerpt_start.lines;
5732                let mut buffer_point = buffer_start_point;
5733                let mut point_utf16 = excerpt_start.lines_utf16();
5734                let mut buffer_point_utf16 = buffer_start_point_utf16;
5735                for ch in buffer
5736                    .snapshot()
5737                    .chunks(buffer_range.clone(), false)
5738                    .flat_map(|c| c.text.chars())
5739                {
5740                    for _ in 0..ch.len_utf8() {
5741                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
5742                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
5743                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5744                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5745                        assert_eq!(
5746                            left_offset,
5747                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
5748                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5749                            offset,
5750                            buffer_id,
5751                            buffer_offset,
5752                        );
5753                        assert_eq!(
5754                            right_offset,
5755                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
5756                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5757                            offset,
5758                            buffer_id,
5759                            buffer_offset,
5760                        );
5761
5762                        let left_point = snapshot.clip_point(point, Bias::Left);
5763                        let right_point = snapshot.clip_point(point, Bias::Right);
5764                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5765                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5766                        assert_eq!(
5767                            left_point,
5768                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
5769                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5770                            point,
5771                            buffer_id,
5772                            buffer_point,
5773                        );
5774                        assert_eq!(
5775                            right_point,
5776                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
5777                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5778                            point,
5779                            buffer_id,
5780                            buffer_point,
5781                        );
5782
5783                        assert_eq!(
5784                            snapshot.point_to_offset(left_point),
5785                            left_offset,
5786                            "point_to_offset({:?})",
5787                            left_point,
5788                        );
5789                        assert_eq!(
5790                            snapshot.offset_to_point(left_offset),
5791                            left_point,
5792                            "offset_to_point({:?})",
5793                            left_offset,
5794                        );
5795
5796                        offset += 1;
5797                        buffer_offset += 1;
5798                        if ch == '\n' {
5799                            point += Point::new(1, 0);
5800                            buffer_point += Point::new(1, 0);
5801                        } else {
5802                            point += Point::new(0, 1);
5803                            buffer_point += Point::new(0, 1);
5804                        }
5805                    }
5806
5807                    for _ in 0..ch.len_utf16() {
5808                        let left_point_utf16 =
5809                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5810                        let right_point_utf16 =
5811                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5812                        let buffer_left_point_utf16 =
5813                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5814                        let buffer_right_point_utf16 =
5815                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5816                        assert_eq!(
5817                            left_point_utf16,
5818                            excerpt_start.lines_utf16()
5819                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
5820                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5821                            point_utf16,
5822                            buffer_id,
5823                            buffer_point_utf16,
5824                        );
5825                        assert_eq!(
5826                            right_point_utf16,
5827                            excerpt_start.lines_utf16()
5828                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
5829                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5830                            point_utf16,
5831                            buffer_id,
5832                            buffer_point_utf16,
5833                        );
5834
5835                        if ch == '\n' {
5836                            point_utf16 += PointUtf16::new(1, 0);
5837                            buffer_point_utf16 += PointUtf16::new(1, 0);
5838                        } else {
5839                            point_utf16 += PointUtf16::new(0, 1);
5840                            buffer_point_utf16 += PointUtf16::new(0, 1);
5841                        }
5842                    }
5843                }
5844            }
5845
5846            for (row, line) in expected_text.split('\n').enumerate() {
5847                assert_eq!(
5848                    snapshot.line_len(MultiBufferRow(row as u32)),
5849                    line.len() as u32,
5850                    "line_len({}).",
5851                    row
5852                );
5853            }
5854
5855            let text_rope = Rope::from(expected_text.as_str());
5856            for _ in 0..10 {
5857                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5858                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5859
5860                let text_for_range = snapshot
5861                    .text_for_range(start_ix..end_ix)
5862                    .collect::<String>();
5863                assert_eq!(
5864                    text_for_range,
5865                    &expected_text[start_ix..end_ix],
5866                    "incorrect text for range {:?}",
5867                    start_ix..end_ix
5868                );
5869
5870                let excerpted_buffer_ranges = multibuffer
5871                    .read(cx)
5872                    .range_to_buffer_ranges(start_ix..end_ix, cx);
5873                let excerpted_buffers_text = excerpted_buffer_ranges
5874                    .iter()
5875                    .map(|(buffer, buffer_range, _)| {
5876                        buffer
5877                            .read(cx)
5878                            .text_for_range(buffer_range.clone())
5879                            .collect::<String>()
5880                    })
5881                    .collect::<Vec<_>>()
5882                    .join("\n");
5883                assert_eq!(excerpted_buffers_text, text_for_range);
5884                if !expected_excerpts.is_empty() {
5885                    assert!(!excerpted_buffer_ranges.is_empty());
5886                }
5887
5888                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5889                assert_eq!(
5890                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5891                    expected_summary,
5892                    "incorrect summary for range {:?}",
5893                    start_ix..end_ix
5894                );
5895            }
5896
5897            // Anchor resolution
5898            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5899            assert_eq!(anchors.len(), summaries.len());
5900            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5901                assert!(resolved_offset <= snapshot.len());
5902                assert_eq!(
5903                    snapshot.summary_for_anchor::<usize>(anchor),
5904                    resolved_offset
5905                );
5906            }
5907
5908            for _ in 0..10 {
5909                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5910                assert_eq!(
5911                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
5912                    expected_text[..end_ix].chars().rev().collect::<String>(),
5913                );
5914            }
5915
5916            for _ in 0..10 {
5917                let end_ix = rng.gen_range(0..=text_rope.len());
5918                let start_ix = rng.gen_range(0..=end_ix);
5919                assert_eq!(
5920                    snapshot
5921                        .bytes_in_range(start_ix..end_ix)
5922                        .flatten()
5923                        .copied()
5924                        .collect::<Vec<_>>(),
5925                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5926                    "bytes_in_range({:?})",
5927                    start_ix..end_ix,
5928                );
5929            }
5930        }
5931
5932        let snapshot = multibuffer.read(cx).snapshot(cx);
5933        for (old_snapshot, subscription) in old_versions {
5934            let edits = subscription.consume().into_inner();
5935
5936            log::info!(
5937                "applying subscription edits to old text: {:?}: {:?}",
5938                old_snapshot.text(),
5939                edits,
5940            );
5941
5942            let mut text = old_snapshot.text();
5943            for edit in edits {
5944                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5945                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5946            }
5947            assert_eq!(text.to_string(), snapshot.text());
5948        }
5949    }
5950
5951    #[gpui::test]
5952    fn test_history(cx: &mut AppContext) {
5953        let test_settings = SettingsStore::test(cx);
5954        cx.set_global(test_settings);
5955
5956        let buffer_1 = cx.new_model(|cx| Buffer::local("1234", cx));
5957        let buffer_2 = cx.new_model(|cx| Buffer::local("5678", cx));
5958        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5959        let group_interval = multibuffer.read(cx).history.group_interval;
5960        multibuffer.update(cx, |multibuffer, cx| {
5961            multibuffer.push_excerpts(
5962                buffer_1.clone(),
5963                [ExcerptRange {
5964                    context: 0..buffer_1.read(cx).len(),
5965                    primary: None,
5966                }],
5967                cx,
5968            );
5969            multibuffer.push_excerpts(
5970                buffer_2.clone(),
5971                [ExcerptRange {
5972                    context: 0..buffer_2.read(cx).len(),
5973                    primary: None,
5974                }],
5975                cx,
5976            );
5977        });
5978
5979        let mut now = Instant::now();
5980
5981        multibuffer.update(cx, |multibuffer, cx| {
5982            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5983            multibuffer.edit(
5984                [
5985                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5986                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5987                ],
5988                None,
5989                cx,
5990            );
5991            multibuffer.edit(
5992                [
5993                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5994                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5995                ],
5996                None,
5997                cx,
5998            );
5999            multibuffer.end_transaction_at(now, cx);
6000            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6001
6002            // Edit buffer 1 through the multibuffer
6003            now += 2 * group_interval;
6004            multibuffer.start_transaction_at(now, cx);
6005            multibuffer.edit([(2..2, "C")], None, cx);
6006            multibuffer.end_transaction_at(now, cx);
6007            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
6008
6009            // Edit buffer 1 independently
6010            buffer_1.update(cx, |buffer_1, cx| {
6011                buffer_1.start_transaction_at(now);
6012                buffer_1.edit([(3..3, "D")], None, cx);
6013                buffer_1.end_transaction_at(now, cx);
6014
6015                now += 2 * group_interval;
6016                buffer_1.start_transaction_at(now);
6017                buffer_1.edit([(4..4, "E")], None, cx);
6018                buffer_1.end_transaction_at(now, cx);
6019            });
6020            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6021
6022            // An undo in the multibuffer undoes the multibuffer transaction
6023            // and also any individual buffer edits that have occurred since
6024            // that transaction.
6025            multibuffer.undo(cx);
6026            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6027
6028            multibuffer.undo(cx);
6029            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6030
6031            multibuffer.redo(cx);
6032            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6033
6034            multibuffer.redo(cx);
6035            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
6036
6037            // Undo buffer 2 independently.
6038            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
6039            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
6040
6041            // An undo in the multibuffer undoes the components of the
6042            // the last multibuffer transaction that are not already undone.
6043            multibuffer.undo(cx);
6044            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
6045
6046            multibuffer.undo(cx);
6047            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6048
6049            multibuffer.redo(cx);
6050            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
6051
6052            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
6053            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6054
6055            // Redo stack gets cleared after an edit.
6056            now += 2 * group_interval;
6057            multibuffer.start_transaction_at(now, cx);
6058            multibuffer.edit([(0..0, "X")], None, cx);
6059            multibuffer.end_transaction_at(now, cx);
6060            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6061            multibuffer.redo(cx);
6062            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6063            multibuffer.undo(cx);
6064            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
6065            multibuffer.undo(cx);
6066            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6067
6068            // Transactions can be grouped manually.
6069            multibuffer.redo(cx);
6070            multibuffer.redo(cx);
6071            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6072            multibuffer.group_until_transaction(transaction_1, cx);
6073            multibuffer.undo(cx);
6074            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
6075            multibuffer.redo(cx);
6076            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
6077        });
6078    }
6079}