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