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                    .filter_map(move |mut runnable| {
3186                        // Re-base onto the excerpts coordinates in the multibuffer
3187                        //
3188                        // The node matching our runnables query might partially overlap with
3189                        // the provided range. If the run indicator is outside of excerpt bounds, do not actually show it.
3190                        if runnable.run_range.start < excerpt_buffer_start {
3191                            return None;
3192                        }
3193                        if language::ToPoint::to_point(&runnable.run_range.end, &excerpt.buffer).row
3194                            > excerpt.max_buffer_row
3195                        {
3196                            return None;
3197                        }
3198                        runnable.run_range.start =
3199                            excerpt_offset + runnable.run_range.start - excerpt_buffer_start;
3200                        runnable.run_range.end =
3201                            excerpt_offset + runnable.run_range.end - excerpt_buffer_start;
3202                        Some(runnable)
3203                    })
3204                    .skip_while(move |runnable| runnable.run_range.end < range.start)
3205                    .take_while(move |runnable| runnable.run_range.start < range.end)
3206            })
3207    }
3208
3209    pub fn diagnostics_update_count(&self) -> usize {
3210        self.diagnostics_update_count
3211    }
3212
3213    pub fn git_diff_update_count(&self) -> usize {
3214        self.git_diff_update_count
3215    }
3216
3217    pub fn trailing_excerpt_update_count(&self) -> usize {
3218        self.trailing_excerpt_update_count
3219    }
3220
3221    pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
3222        self.point_to_buffer_offset(point)
3223            .and_then(|(buffer, _)| buffer.file())
3224    }
3225
3226    pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
3227        self.point_to_buffer_offset(point)
3228            .and_then(|(buffer, offset)| buffer.language_at(offset))
3229    }
3230
3231    pub fn settings_at<'a, T: ToOffset>(
3232        &'a self,
3233        point: T,
3234        cx: &'a AppContext,
3235    ) -> &'a LanguageSettings {
3236        let mut language = None;
3237        let mut file = None;
3238        if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
3239            language = buffer.language_at(offset);
3240            file = buffer.file();
3241        }
3242        language_settings(language, file, cx)
3243    }
3244
3245    pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
3246        self.point_to_buffer_offset(point)
3247            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
3248    }
3249
3250    pub fn language_indent_size_at<T: ToOffset>(
3251        &self,
3252        position: T,
3253        cx: &AppContext,
3254    ) -> Option<IndentSize> {
3255        let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
3256        Some(buffer_snapshot.language_indent_size_at(offset, cx))
3257    }
3258
3259    pub fn is_dirty(&self) -> bool {
3260        self.is_dirty
3261    }
3262
3263    pub fn has_conflict(&self) -> bool {
3264        self.has_conflict
3265    }
3266
3267    pub fn has_diagnostics(&self) -> bool {
3268        self.excerpts
3269            .iter()
3270            .any(|excerpt| excerpt.buffer.has_diagnostics())
3271    }
3272
3273    pub fn diagnostic_group<'a, O>(
3274        &'a self,
3275        group_id: usize,
3276    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3277    where
3278        O: text::FromAnchor + 'a,
3279    {
3280        self.as_singleton()
3281            .into_iter()
3282            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
3283    }
3284
3285    pub fn diagnostics_in_range<'a, T, O>(
3286        &'a self,
3287        range: Range<T>,
3288        reversed: bool,
3289    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3290    where
3291        T: 'a + ToOffset,
3292        O: 'a + text::FromAnchor + Ord,
3293    {
3294        self.as_singleton()
3295            .into_iter()
3296            .flat_map(move |(_, _, buffer)| {
3297                buffer.diagnostics_in_range(
3298                    range.start.to_offset(self)..range.end.to_offset(self),
3299                    reversed,
3300                )
3301            })
3302    }
3303
3304    pub fn has_git_diffs(&self) -> bool {
3305        for excerpt in self.excerpts.iter() {
3306            if excerpt.buffer.has_git_diff() {
3307                return true;
3308            }
3309        }
3310        false
3311    }
3312
3313    pub fn git_diff_hunks_in_range_rev(
3314        &self,
3315        row_range: Range<u32>,
3316    ) -> impl Iterator<Item = DiffHunk<u32>> + '_ {
3317        let mut cursor = self.excerpts.cursor::<Point>();
3318
3319        cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
3320        if cursor.item().is_none() {
3321            cursor.prev(&());
3322        }
3323
3324        std::iter::from_fn(move || {
3325            let excerpt = cursor.item()?;
3326            let multibuffer_start = *cursor.start();
3327            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3328            if multibuffer_start.row >= row_range.end {
3329                return None;
3330            }
3331
3332            let mut buffer_start = excerpt.range.context.start;
3333            let mut buffer_end = excerpt.range.context.end;
3334            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3335            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3336
3337            if row_range.start > multibuffer_start.row {
3338                let buffer_start_point =
3339                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3340                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3341            }
3342
3343            if row_range.end < multibuffer_end.row {
3344                let buffer_end_point =
3345                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3346                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3347            }
3348
3349            let buffer_hunks = excerpt
3350                .buffer
3351                .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
3352                .map(move |hunk| {
3353                    let start = multibuffer_start.row
3354                        + hunk
3355                            .associated_range
3356                            .start
3357                            .saturating_sub(excerpt_start_point.row);
3358                    let end = multibuffer_start.row
3359                        + hunk
3360                            .associated_range
3361                            .end
3362                            .min(excerpt_end_point.row + 1)
3363                            .saturating_sub(excerpt_start_point.row);
3364
3365                    DiffHunk {
3366                        associated_range: start..end,
3367                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3368                        buffer_range: hunk.buffer_range.clone(),
3369                        buffer_id: hunk.buffer_id,
3370                    }
3371                });
3372
3373            cursor.prev(&());
3374
3375            Some(buffer_hunks)
3376        })
3377        .flatten()
3378    }
3379
3380    pub fn git_diff_hunks_in_range(
3381        &self,
3382        row_range: Range<u32>,
3383    ) -> impl Iterator<Item = DiffHunk<u32>> + '_ {
3384        let mut cursor = self.excerpts.cursor::<Point>();
3385
3386        cursor.seek(&Point::new(row_range.start, 0), Bias::Left, &());
3387
3388        std::iter::from_fn(move || {
3389            let excerpt = cursor.item()?;
3390            let multibuffer_start = *cursor.start();
3391            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3392            let mut buffer_start = excerpt.range.context.start;
3393            let mut buffer_end = excerpt.range.context.end;
3394
3395            let excerpt_rows = match multibuffer_start.row.cmp(&row_range.end) {
3396                cmp::Ordering::Less => {
3397                    let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3398                    let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3399
3400                    if row_range.start > multibuffer_start.row {
3401                        let buffer_start_point = excerpt_start_point
3402                            + Point::new(row_range.start - multibuffer_start.row, 0);
3403                        buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3404                    }
3405
3406                    if row_range.end < multibuffer_end.row {
3407                        let buffer_end_point = excerpt_start_point
3408                            + Point::new(row_range.end - multibuffer_start.row, 0);
3409                        buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3410                    }
3411                    excerpt_start_point.row..excerpt_end_point.row
3412                }
3413                cmp::Ordering::Equal if row_range.end == 0 => {
3414                    buffer_end = buffer_start;
3415                    0..0
3416                }
3417                cmp::Ordering::Greater | cmp::Ordering::Equal => return None,
3418            };
3419
3420            let buffer_hunks = excerpt
3421                .buffer
3422                .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3423                .map(move |hunk| {
3424                    let buffer_range = if excerpt_rows.start == 0 && excerpt_rows.end == 0 {
3425                        0..1
3426                    } else {
3427                        let start = multibuffer_start.row
3428                            + hunk
3429                                .associated_range
3430                                .start
3431                                .saturating_sub(excerpt_rows.start);
3432                        let end = multibuffer_start.row
3433                            + hunk
3434                                .associated_range
3435                                .end
3436                                .min(excerpt_rows.end + 1)
3437                                .saturating_sub(excerpt_rows.start);
3438                        start..end
3439                    };
3440                    DiffHunk {
3441                        associated_range: buffer_range,
3442                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3443                        buffer_range: hunk.buffer_range.clone(),
3444                        buffer_id: hunk.buffer_id,
3445                    }
3446                });
3447
3448            cursor.next(&());
3449
3450            Some(buffer_hunks)
3451        })
3452        .flatten()
3453    }
3454
3455    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3456        let range = range.start.to_offset(self)..range.end.to_offset(self);
3457        let excerpt = self.excerpt_containing(range.clone())?;
3458
3459        let ancestor_buffer_range = excerpt
3460            .buffer()
3461            .range_for_syntax_ancestor(excerpt.map_range_to_buffer(range))?;
3462
3463        Some(excerpt.map_range_from_buffer(ancestor_buffer_range))
3464    }
3465
3466    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3467        let (excerpt_id, _, buffer) = self.as_singleton()?;
3468        let outline = buffer.outline(theme)?;
3469        Some(Outline::new(
3470            outline
3471                .items
3472                .into_iter()
3473                .flat_map(|item| {
3474                    Some(OutlineItem {
3475                        depth: item.depth,
3476                        range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
3477                            ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
3478                        text: item.text,
3479                        highlight_ranges: item.highlight_ranges,
3480                        name_ranges: item.name_ranges,
3481                    })
3482                })
3483                .collect(),
3484        ))
3485    }
3486
3487    pub fn symbols_containing<T: ToOffset>(
3488        &self,
3489        offset: T,
3490        theme: Option<&SyntaxTheme>,
3491    ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3492        let anchor = self.anchor_before(offset);
3493        let excerpt_id = anchor.excerpt_id;
3494        let excerpt = self.excerpt(excerpt_id)?;
3495        Some((
3496            excerpt.buffer_id,
3497            excerpt
3498                .buffer
3499                .symbols_containing(anchor.text_anchor, theme)
3500                .into_iter()
3501                .flatten()
3502                .flat_map(|item| {
3503                    Some(OutlineItem {
3504                        depth: item.depth,
3505                        range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3506                            ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3507                        text: item.text,
3508                        highlight_ranges: item.highlight_ranges,
3509                        name_ranges: item.name_ranges,
3510                    })
3511                })
3512                .collect(),
3513        ))
3514    }
3515
3516    fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3517        if id == ExcerptId::min() {
3518            Locator::min_ref()
3519        } else if id == ExcerptId::max() {
3520            Locator::max_ref()
3521        } else {
3522            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3523            cursor.seek(&id, Bias::Left, &());
3524            if let Some(entry) = cursor.item() {
3525                if entry.id == id {
3526                    return &entry.locator;
3527                }
3528            }
3529            panic!("invalid excerpt id {:?}", id)
3530        }
3531    }
3532
3533    // Returns the locators referenced by the given excerpt ids, sorted by locator.
3534    fn excerpt_locators_for_ids(
3535        &self,
3536        ids: impl IntoIterator<Item = ExcerptId>,
3537    ) -> SmallVec<[Locator; 1]> {
3538        let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
3539        sorted_ids.sort_unstable();
3540        let mut locators = SmallVec::new();
3541
3542        while sorted_ids.last() == Some(&ExcerptId::max()) {
3543            sorted_ids.pop();
3544            locators.push(Locator::max());
3545        }
3546
3547        let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
3548        if sorted_ids.peek() == Some(&ExcerptId::min()) {
3549            sorted_ids.next();
3550            locators.push(Locator::min());
3551        }
3552
3553        let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3554        for id in sorted_ids {
3555            if cursor.seek_forward(&id, Bias::Left, &()) {
3556                locators.push(cursor.item().unwrap().locator.clone());
3557            } else {
3558                panic!("invalid excerpt id {:?}", id);
3559            }
3560        }
3561
3562        locators.sort_unstable();
3563        locators
3564    }
3565
3566    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3567        Some(self.excerpt(excerpt_id)?.buffer_id)
3568    }
3569
3570    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3571        Some(&self.excerpt(excerpt_id)?.buffer)
3572    }
3573
3574    fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3575        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3576        let locator = self.excerpt_locator_for_id(excerpt_id);
3577        cursor.seek(&Some(locator), Bias::Left, &());
3578        if let Some(excerpt) = cursor.item() {
3579            if excerpt.id == excerpt_id {
3580                return Some(excerpt);
3581            }
3582        }
3583        None
3584    }
3585
3586    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3587    pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3588        let range = range.start.to_offset(self)..range.end.to_offset(self);
3589
3590        let mut cursor = self.excerpts.cursor::<usize>();
3591        cursor.seek(&range.start, Bias::Right, &());
3592        let start_excerpt = cursor.item()?;
3593
3594        if range.start == range.end {
3595            return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3596        }
3597
3598        cursor.seek(&range.end, Bias::Right, &());
3599        let end_excerpt = cursor.item()?;
3600
3601        if start_excerpt.id == end_excerpt.id {
3602            Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3603        } else {
3604            None
3605        }
3606    }
3607
3608    pub fn remote_selections_in_range<'a>(
3609        &'a self,
3610        range: &'a Range<Anchor>,
3611    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3612        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3613        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3614        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3615        cursor.seek(start_locator, Bias::Left, &());
3616        cursor
3617            .take_while(move |excerpt| excerpt.locator <= *end_locator)
3618            .flat_map(move |excerpt| {
3619                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3620                if excerpt.id == range.start.excerpt_id {
3621                    query_range.start = range.start.text_anchor;
3622                }
3623                if excerpt.id == range.end.excerpt_id {
3624                    query_range.end = range.end.text_anchor;
3625                }
3626
3627                excerpt
3628                    .buffer
3629                    .remote_selections_in_range(query_range)
3630                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3631                        selections.map(move |selection| {
3632                            let mut start = Anchor {
3633                                buffer_id: Some(excerpt.buffer_id),
3634                                excerpt_id: excerpt.id,
3635                                text_anchor: selection.start,
3636                            };
3637                            let mut end = Anchor {
3638                                buffer_id: Some(excerpt.buffer_id),
3639                                excerpt_id: excerpt.id,
3640                                text_anchor: selection.end,
3641                            };
3642                            if range.start.cmp(&start, self).is_gt() {
3643                                start = range.start;
3644                            }
3645                            if range.end.cmp(&end, self).is_lt() {
3646                                end = range.end;
3647                            }
3648
3649                            (
3650                                replica_id,
3651                                line_mode,
3652                                cursor_shape,
3653                                Selection {
3654                                    id: selection.id,
3655                                    start,
3656                                    end,
3657                                    reversed: selection.reversed,
3658                                    goal: selection.goal,
3659                                },
3660                            )
3661                        })
3662                    })
3663            })
3664    }
3665
3666    pub fn show_headers(&self) -> bool {
3667        self.show_headers
3668    }
3669}
3670
3671#[cfg(any(test, feature = "test-support"))]
3672impl MultiBufferSnapshot {
3673    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3674        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3675        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3676        start..end
3677    }
3678}
3679
3680impl History {
3681    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3682        self.transaction_depth += 1;
3683        if self.transaction_depth == 1 {
3684            let id = self.next_transaction_id.tick();
3685            self.undo_stack.push(Transaction {
3686                id,
3687                buffer_transactions: Default::default(),
3688                first_edit_at: now,
3689                last_edit_at: now,
3690                suppress_grouping: false,
3691            });
3692            Some(id)
3693        } else {
3694            None
3695        }
3696    }
3697
3698    fn end_transaction(
3699        &mut self,
3700        now: Instant,
3701        buffer_transactions: HashMap<BufferId, TransactionId>,
3702    ) -> bool {
3703        assert_ne!(self.transaction_depth, 0);
3704        self.transaction_depth -= 1;
3705        if self.transaction_depth == 0 {
3706            if buffer_transactions.is_empty() {
3707                self.undo_stack.pop();
3708                false
3709            } else {
3710                self.redo_stack.clear();
3711                let transaction = self.undo_stack.last_mut().unwrap();
3712                transaction.last_edit_at = now;
3713                for (buffer_id, transaction_id) in buffer_transactions {
3714                    transaction
3715                        .buffer_transactions
3716                        .entry(buffer_id)
3717                        .or_insert(transaction_id);
3718                }
3719                true
3720            }
3721        } else {
3722            false
3723        }
3724    }
3725
3726    fn push_transaction<'a, T>(
3727        &mut self,
3728        buffer_transactions: T,
3729        now: Instant,
3730        cx: &mut ModelContext<MultiBuffer>,
3731    ) where
3732        T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
3733    {
3734        assert_eq!(self.transaction_depth, 0);
3735        let transaction = Transaction {
3736            id: self.next_transaction_id.tick(),
3737            buffer_transactions: buffer_transactions
3738                .into_iter()
3739                .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3740                .collect(),
3741            first_edit_at: now,
3742            last_edit_at: now,
3743            suppress_grouping: false,
3744        };
3745        if !transaction.buffer_transactions.is_empty() {
3746            self.undo_stack.push(transaction);
3747            self.redo_stack.clear();
3748        }
3749    }
3750
3751    fn finalize_last_transaction(&mut self) {
3752        if let Some(transaction) = self.undo_stack.last_mut() {
3753            transaction.suppress_grouping = true;
3754        }
3755    }
3756
3757    fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
3758        if let Some(ix) = self
3759            .undo_stack
3760            .iter()
3761            .rposition(|transaction| transaction.id == transaction_id)
3762        {
3763            Some(self.undo_stack.remove(ix))
3764        } else if let Some(ix) = self
3765            .redo_stack
3766            .iter()
3767            .rposition(|transaction| transaction.id == transaction_id)
3768        {
3769            Some(self.redo_stack.remove(ix))
3770        } else {
3771            None
3772        }
3773    }
3774
3775    fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
3776        self.undo_stack
3777            .iter_mut()
3778            .find(|transaction| transaction.id == transaction_id)
3779            .or_else(|| {
3780                self.redo_stack
3781                    .iter_mut()
3782                    .find(|transaction| transaction.id == transaction_id)
3783            })
3784    }
3785
3786    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3787        assert_eq!(self.transaction_depth, 0);
3788        if let Some(transaction) = self.undo_stack.pop() {
3789            self.redo_stack.push(transaction);
3790            self.redo_stack.last_mut()
3791        } else {
3792            None
3793        }
3794    }
3795
3796    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3797        assert_eq!(self.transaction_depth, 0);
3798        if let Some(transaction) = self.redo_stack.pop() {
3799            self.undo_stack.push(transaction);
3800            self.undo_stack.last_mut()
3801        } else {
3802            None
3803        }
3804    }
3805
3806    fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
3807        let ix = self
3808            .undo_stack
3809            .iter()
3810            .rposition(|transaction| transaction.id == transaction_id)?;
3811        let transaction = self.undo_stack.remove(ix);
3812        self.redo_stack.push(transaction);
3813        self.redo_stack.last()
3814    }
3815
3816    fn group(&mut self) -> Option<TransactionId> {
3817        let mut count = 0;
3818        let mut transactions = self.undo_stack.iter();
3819        if let Some(mut transaction) = transactions.next_back() {
3820            while let Some(prev_transaction) = transactions.next_back() {
3821                if !prev_transaction.suppress_grouping
3822                    && transaction.first_edit_at - prev_transaction.last_edit_at
3823                        <= self.group_interval
3824                {
3825                    transaction = prev_transaction;
3826                    count += 1;
3827                } else {
3828                    break;
3829                }
3830            }
3831        }
3832        self.group_trailing(count)
3833    }
3834
3835    fn group_until(&mut self, transaction_id: TransactionId) {
3836        let mut count = 0;
3837        for transaction in self.undo_stack.iter().rev() {
3838            if transaction.id == transaction_id {
3839                self.group_trailing(count);
3840                break;
3841            } else if transaction.suppress_grouping {
3842                break;
3843            } else {
3844                count += 1;
3845            }
3846        }
3847    }
3848
3849    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3850        let new_len = self.undo_stack.len() - n;
3851        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3852        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3853            if let Some(transaction) = transactions_to_merge.last() {
3854                last_transaction.last_edit_at = transaction.last_edit_at;
3855            }
3856            for to_merge in transactions_to_merge {
3857                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3858                    last_transaction
3859                        .buffer_transactions
3860                        .entry(*buffer_id)
3861                        .or_insert(*transaction_id);
3862                }
3863            }
3864        }
3865
3866        self.undo_stack.truncate(new_len);
3867        self.undo_stack.last().map(|t| t.id)
3868    }
3869}
3870
3871impl Excerpt {
3872    fn new(
3873        id: ExcerptId,
3874        locator: Locator,
3875        buffer_id: BufferId,
3876        buffer: BufferSnapshot,
3877        range: ExcerptRange<text::Anchor>,
3878        has_trailing_newline: bool,
3879    ) -> Self {
3880        Excerpt {
3881            id,
3882            locator,
3883            max_buffer_row: range.context.end.to_point(&buffer).row,
3884            text_summary: buffer
3885                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3886            buffer_id,
3887            buffer,
3888            range,
3889            has_trailing_newline,
3890        }
3891    }
3892
3893    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3894        let content_start = self.range.context.start.to_offset(&self.buffer);
3895        let chunks_start = content_start + range.start;
3896        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3897
3898        let footer_height = if self.has_trailing_newline
3899            && range.start <= self.text_summary.len
3900            && range.end > self.text_summary.len
3901        {
3902            1
3903        } else {
3904            0
3905        };
3906
3907        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3908
3909        ExcerptChunks {
3910            content_chunks,
3911            footer_height,
3912        }
3913    }
3914
3915    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3916        let content_start = self.range.context.start.to_offset(&self.buffer);
3917        let bytes_start = content_start + range.start;
3918        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3919        let footer_height = if self.has_trailing_newline
3920            && range.start <= self.text_summary.len
3921            && range.end > self.text_summary.len
3922        {
3923            1
3924        } else {
3925            0
3926        };
3927        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3928
3929        ExcerptBytes {
3930            content_bytes,
3931            padding_height: footer_height,
3932            reversed: false,
3933        }
3934    }
3935
3936    fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3937        let content_start = self.range.context.start.to_offset(&self.buffer);
3938        let bytes_start = content_start + range.start;
3939        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3940        let footer_height = if self.has_trailing_newline
3941            && range.start <= self.text_summary.len
3942            && range.end > self.text_summary.len
3943        {
3944            1
3945        } else {
3946            0
3947        };
3948        let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3949
3950        ExcerptBytes {
3951            content_bytes,
3952            padding_height: footer_height,
3953            reversed: true,
3954        }
3955    }
3956
3957    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3958        if text_anchor
3959            .cmp(&self.range.context.start, &self.buffer)
3960            .is_lt()
3961        {
3962            self.range.context.start
3963        } else if text_anchor
3964            .cmp(&self.range.context.end, &self.buffer)
3965            .is_gt()
3966        {
3967            self.range.context.end
3968        } else {
3969            text_anchor
3970        }
3971    }
3972
3973    fn contains(&self, anchor: &Anchor) -> bool {
3974        Some(self.buffer_id) == anchor.buffer_id
3975            && self
3976                .range
3977                .context
3978                .start
3979                .cmp(&anchor.text_anchor, &self.buffer)
3980                .is_le()
3981            && self
3982                .range
3983                .context
3984                .end
3985                .cmp(&anchor.text_anchor, &self.buffer)
3986                .is_ge()
3987    }
3988
3989    /// The [`Excerpt`]'s start offset in its [`Buffer`]
3990    fn buffer_start_offset(&self) -> usize {
3991        self.range.context.start.to_offset(&self.buffer)
3992    }
3993
3994    /// The [`Excerpt`]'s end offset in its [`Buffer`]
3995    fn buffer_end_offset(&self) -> usize {
3996        self.buffer_start_offset() + self.text_summary.len
3997    }
3998}
3999
4000impl<'a> MultiBufferExcerpt<'a> {
4001    fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
4002        MultiBufferExcerpt {
4003            excerpt,
4004            excerpt_offset,
4005        }
4006    }
4007
4008    pub fn buffer(&self) -> &'a BufferSnapshot {
4009        &self.excerpt.buffer
4010    }
4011
4012    /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
4013    pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
4014        self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
4015    }
4016
4017    /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
4018    pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
4019        self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
4020    }
4021
4022    /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
4023    pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
4024        let mut buffer_offset_in_excerpt =
4025            buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
4026        buffer_offset_in_excerpt =
4027            cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
4028
4029        self.excerpt_offset + buffer_offset_in_excerpt
4030    }
4031
4032    /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
4033    pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
4034        self.map_offset_from_buffer(buffer_range.start)
4035            ..self.map_offset_from_buffer(buffer_range.end)
4036    }
4037
4038    /// Returns true if the entirety of the given range is in the buffer's excerpt
4039    pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
4040        range.start >= self.excerpt.buffer_start_offset()
4041            && range.end <= self.excerpt.buffer_end_offset()
4042    }
4043}
4044
4045impl ExcerptId {
4046    pub fn min() -> Self {
4047        Self(0)
4048    }
4049
4050    pub fn max() -> Self {
4051        Self(usize::MAX)
4052    }
4053
4054    pub fn to_proto(&self) -> u64 {
4055        self.0 as _
4056    }
4057
4058    pub fn from_proto(proto: u64) -> Self {
4059        Self(proto as _)
4060    }
4061
4062    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
4063        let a = snapshot.excerpt_locator_for_id(*self);
4064        let b = snapshot.excerpt_locator_for_id(*other);
4065        a.cmp(b).then_with(|| self.0.cmp(&other.0))
4066    }
4067}
4068
4069impl Into<usize> for ExcerptId {
4070    fn into(self) -> usize {
4071        self.0
4072    }
4073}
4074
4075impl fmt::Debug for Excerpt {
4076    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4077        f.debug_struct("Excerpt")
4078            .field("id", &self.id)
4079            .field("locator", &self.locator)
4080            .field("buffer_id", &self.buffer_id)
4081            .field("range", &self.range)
4082            .field("text_summary", &self.text_summary)
4083            .field("has_trailing_newline", &self.has_trailing_newline)
4084            .finish()
4085    }
4086}
4087
4088impl sum_tree::Item for Excerpt {
4089    type Summary = ExcerptSummary;
4090
4091    fn summary(&self) -> Self::Summary {
4092        let mut text = self.text_summary.clone();
4093        if self.has_trailing_newline {
4094            text += TextSummary::from("\n");
4095        }
4096        ExcerptSummary {
4097            excerpt_id: self.id,
4098            excerpt_locator: self.locator.clone(),
4099            max_buffer_row: self.max_buffer_row,
4100            text,
4101        }
4102    }
4103}
4104
4105impl sum_tree::Item for ExcerptIdMapping {
4106    type Summary = ExcerptId;
4107
4108    fn summary(&self) -> Self::Summary {
4109        self.id
4110    }
4111}
4112
4113impl sum_tree::KeyedItem for ExcerptIdMapping {
4114    type Key = ExcerptId;
4115
4116    fn key(&self) -> Self::Key {
4117        self.id
4118    }
4119}
4120
4121impl sum_tree::Summary for ExcerptId {
4122    type Context = ();
4123
4124    fn add_summary(&mut self, other: &Self, _: &()) {
4125        *self = *other;
4126    }
4127}
4128
4129impl sum_tree::Summary for ExcerptSummary {
4130    type Context = ();
4131
4132    fn add_summary(&mut self, summary: &Self, _: &()) {
4133        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
4134        self.excerpt_locator = summary.excerpt_locator.clone();
4135        self.text.add_summary(&summary.text, &());
4136        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
4137    }
4138}
4139
4140impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
4141    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4142        *self += &summary.text;
4143    }
4144}
4145
4146impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
4147    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4148        *self += summary.text.len;
4149    }
4150}
4151
4152impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
4153    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4154        Ord::cmp(self, &cursor_location.text.len)
4155    }
4156}
4157
4158impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
4159    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
4160        Ord::cmp(&Some(self), cursor_location)
4161    }
4162}
4163
4164impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
4165    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4166        Ord::cmp(self, &cursor_location.excerpt_locator)
4167    }
4168}
4169
4170impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
4171    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4172        *self += summary.text.len_utf16;
4173    }
4174}
4175
4176impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
4177    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4178        *self += summary.text.lines;
4179    }
4180}
4181
4182impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
4183    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4184        *self += summary.text.lines_utf16()
4185    }
4186}
4187
4188impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
4189    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4190        *self = Some(&summary.excerpt_locator);
4191    }
4192}
4193
4194impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
4195    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4196        *self = Some(summary.excerpt_id);
4197    }
4198}
4199
4200impl<'a> MultiBufferRows<'a> {
4201    pub fn seek(&mut self, row: u32) {
4202        self.buffer_row_range = 0..0;
4203
4204        self.excerpts
4205            .seek_forward(&Point::new(row, 0), Bias::Right, &());
4206        if self.excerpts.item().is_none() {
4207            self.excerpts.prev(&());
4208
4209            if self.excerpts.item().is_none() && row == 0 {
4210                self.buffer_row_range = 0..1;
4211                return;
4212            }
4213        }
4214
4215        if let Some(excerpt) = self.excerpts.item() {
4216            let overshoot = row - self.excerpts.start().row;
4217            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4218            self.buffer_row_range.start = excerpt_start + overshoot;
4219            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4220        }
4221    }
4222}
4223
4224impl<'a> Iterator for MultiBufferRows<'a> {
4225    type Item = Option<u32>;
4226
4227    fn next(&mut self) -> Option<Self::Item> {
4228        loop {
4229            if !self.buffer_row_range.is_empty() {
4230                let row = Some(self.buffer_row_range.start);
4231                self.buffer_row_range.start += 1;
4232                return Some(row);
4233            }
4234            self.excerpts.item()?;
4235            self.excerpts.next(&());
4236            let excerpt = self.excerpts.item()?;
4237            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4238            self.buffer_row_range.end =
4239                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4240        }
4241    }
4242}
4243
4244impl<'a> MultiBufferChunks<'a> {
4245    pub fn offset(&self) -> usize {
4246        self.range.start
4247    }
4248
4249    pub fn seek(&mut self, offset: usize) {
4250        self.range.start = offset;
4251        self.excerpts.seek(&offset, Bias::Right, &());
4252        if let Some(excerpt) = self.excerpts.item() {
4253            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4254                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
4255                self.language_aware,
4256            ));
4257        } else {
4258            self.excerpt_chunks = None;
4259        }
4260    }
4261}
4262
4263impl<'a> Iterator for MultiBufferChunks<'a> {
4264    type Item = Chunk<'a>;
4265
4266    fn next(&mut self) -> Option<Self::Item> {
4267        if self.range.is_empty() {
4268            None
4269        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4270            self.range.start += chunk.text.len();
4271            Some(chunk)
4272        } else {
4273            self.excerpts.next(&());
4274            let excerpt = self.excerpts.item()?;
4275            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4276                0..self.range.end - self.excerpts.start(),
4277                self.language_aware,
4278            ));
4279            self.next()
4280        }
4281    }
4282}
4283
4284impl<'a> MultiBufferBytes<'a> {
4285    fn consume(&mut self, len: usize) {
4286        self.range.start += len;
4287        self.chunk = &self.chunk[len..];
4288
4289        if !self.range.is_empty() && self.chunk.is_empty() {
4290            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4291                self.chunk = chunk;
4292            } else {
4293                self.excerpts.next(&());
4294                if let Some(excerpt) = self.excerpts.item() {
4295                    let mut excerpt_bytes =
4296                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4297                    self.chunk = excerpt_bytes.next().unwrap();
4298                    self.excerpt_bytes = Some(excerpt_bytes);
4299                }
4300            }
4301        }
4302    }
4303}
4304
4305impl<'a> Iterator for MultiBufferBytes<'a> {
4306    type Item = &'a [u8];
4307
4308    fn next(&mut self) -> Option<Self::Item> {
4309        let chunk = self.chunk;
4310        if chunk.is_empty() {
4311            None
4312        } else {
4313            self.consume(chunk.len());
4314            Some(chunk)
4315        }
4316    }
4317}
4318
4319impl<'a> io::Read for MultiBufferBytes<'a> {
4320    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4321        let len = cmp::min(buf.len(), self.chunk.len());
4322        buf[..len].copy_from_slice(&self.chunk[..len]);
4323        if len > 0 {
4324            self.consume(len);
4325        }
4326        Ok(len)
4327    }
4328}
4329
4330impl<'a> ReversedMultiBufferBytes<'a> {
4331    fn consume(&mut self, len: usize) {
4332        self.range.end -= len;
4333        self.chunk = &self.chunk[..self.chunk.len() - len];
4334
4335        if !self.range.is_empty() && self.chunk.is_empty() {
4336            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4337                self.chunk = chunk;
4338            } else {
4339                self.excerpts.prev(&());
4340                if let Some(excerpt) = self.excerpts.item() {
4341                    let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
4342                        self.range.start.saturating_sub(*self.excerpts.start())..usize::MAX,
4343                    );
4344                    self.chunk = excerpt_bytes.next().unwrap();
4345                    self.excerpt_bytes = Some(excerpt_bytes);
4346                }
4347            }
4348        } else {
4349        }
4350    }
4351}
4352
4353impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4354    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4355        let len = cmp::min(buf.len(), self.chunk.len());
4356        buf[..len].copy_from_slice(&self.chunk[..len]);
4357        buf[..len].reverse();
4358        if len > 0 {
4359            self.consume(len);
4360        }
4361        Ok(len)
4362    }
4363}
4364impl<'a> Iterator for ExcerptBytes<'a> {
4365    type Item = &'a [u8];
4366
4367    fn next(&mut self) -> Option<Self::Item> {
4368        if self.reversed && self.padding_height > 0 {
4369            let result = &NEWLINES[..self.padding_height];
4370            self.padding_height = 0;
4371            return Some(result);
4372        }
4373
4374        if let Some(chunk) = self.content_bytes.next() {
4375            if !chunk.is_empty() {
4376                return Some(chunk);
4377            }
4378        }
4379
4380        if self.padding_height > 0 {
4381            let result = &NEWLINES[..self.padding_height];
4382            self.padding_height = 0;
4383            return Some(result);
4384        }
4385
4386        None
4387    }
4388}
4389
4390impl<'a> Iterator for ExcerptChunks<'a> {
4391    type Item = Chunk<'a>;
4392
4393    fn next(&mut self) -> Option<Self::Item> {
4394        if let Some(chunk) = self.content_chunks.next() {
4395            return Some(chunk);
4396        }
4397
4398        if self.footer_height > 0 {
4399            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4400            self.footer_height = 0;
4401            return Some(Chunk {
4402                text,
4403                ..Default::default()
4404            });
4405        }
4406
4407        None
4408    }
4409}
4410
4411impl ToOffset for Point {
4412    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4413        snapshot.point_to_offset(*self)
4414    }
4415}
4416
4417impl ToOffset for usize {
4418    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4419        assert!(*self <= snapshot.len(), "offset is out of range");
4420        *self
4421    }
4422}
4423
4424impl ToOffset for OffsetUtf16 {
4425    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4426        snapshot.offset_utf16_to_offset(*self)
4427    }
4428}
4429
4430impl ToOffset for PointUtf16 {
4431    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4432        snapshot.point_utf16_to_offset(*self)
4433    }
4434}
4435
4436impl ToOffsetUtf16 for OffsetUtf16 {
4437    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4438        *self
4439    }
4440}
4441
4442impl ToOffsetUtf16 for usize {
4443    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4444        snapshot.offset_to_offset_utf16(*self)
4445    }
4446}
4447
4448impl ToPoint for usize {
4449    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
4450        snapshot.offset_to_point(*self)
4451    }
4452}
4453
4454impl ToPoint for Point {
4455    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
4456        *self
4457    }
4458}
4459
4460impl ToPointUtf16 for usize {
4461    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4462        snapshot.offset_to_point_utf16(*self)
4463    }
4464}
4465
4466impl ToPointUtf16 for Point {
4467    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4468        snapshot.point_to_point_utf16(*self)
4469    }
4470}
4471
4472impl ToPointUtf16 for PointUtf16 {
4473    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
4474        *self
4475    }
4476}
4477
4478fn build_excerpt_ranges<T>(
4479    buffer: &BufferSnapshot,
4480    ranges: &[Range<T>],
4481    context_line_count: u32,
4482) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
4483where
4484    T: text::ToPoint,
4485{
4486    let max_point = buffer.max_point();
4487    let mut range_counts = Vec::new();
4488    let mut excerpt_ranges = Vec::new();
4489    let mut range_iter = ranges
4490        .iter()
4491        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
4492        .peekable();
4493    while let Some(range) = range_iter.next() {
4494        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
4495        // These + 1s ensure that we select the whole next line
4496        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
4497
4498        let mut ranges_in_excerpt = 1;
4499
4500        while let Some(next_range) = range_iter.peek() {
4501            if next_range.start.row <= excerpt_end.row + context_line_count {
4502                excerpt_end =
4503                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
4504                ranges_in_excerpt += 1;
4505                range_iter.next();
4506            } else {
4507                break;
4508            }
4509        }
4510
4511        excerpt_ranges.push(ExcerptRange {
4512            context: excerpt_start..excerpt_end,
4513            primary: Some(range),
4514        });
4515        range_counts.push(ranges_in_excerpt);
4516    }
4517
4518    (excerpt_ranges, range_counts)
4519}
4520
4521#[cfg(test)]
4522mod tests {
4523    use super::*;
4524    use futures::StreamExt;
4525    use gpui::{AppContext, Context, TestAppContext};
4526    use language::{Buffer, Rope};
4527    use parking_lot::RwLock;
4528    use rand::prelude::*;
4529    use settings::SettingsStore;
4530    use std::env;
4531    use util::test::sample_text;
4532
4533    #[ctor::ctor]
4534    fn init_logger() {
4535        if std::env::var("RUST_LOG").is_ok() {
4536            env_logger::init();
4537        }
4538    }
4539
4540    #[gpui::test]
4541    fn test_singleton(cx: &mut AppContext) {
4542        let buffer = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4543        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4544
4545        let snapshot = multibuffer.read(cx).snapshot(cx);
4546        assert_eq!(snapshot.text(), buffer.read(cx).text());
4547
4548        assert_eq!(
4549            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4550            (0..buffer.read(cx).row_count())
4551                .map(Some)
4552                .collect::<Vec<_>>()
4553        );
4554
4555        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4556        let snapshot = multibuffer.read(cx).snapshot(cx);
4557
4558        assert_eq!(snapshot.text(), buffer.read(cx).text());
4559        assert_eq!(
4560            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4561            (0..buffer.read(cx).row_count())
4562                .map(Some)
4563                .collect::<Vec<_>>()
4564        );
4565    }
4566
4567    #[gpui::test]
4568    fn test_remote(cx: &mut AppContext) {
4569        let host_buffer = cx.new_model(|cx| Buffer::local("a", cx));
4570        let guest_buffer = cx.new_model(|cx| {
4571            let state = host_buffer.read(cx).to_proto();
4572            let ops = cx
4573                .background_executor()
4574                .block(host_buffer.read(cx).serialize_ops(None, cx));
4575            let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
4576            buffer
4577                .apply_ops(
4578                    ops.into_iter()
4579                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
4580                    cx,
4581                )
4582                .unwrap();
4583            buffer
4584        });
4585        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4586        let snapshot = multibuffer.read(cx).snapshot(cx);
4587        assert_eq!(snapshot.text(), "a");
4588
4589        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4590        let snapshot = multibuffer.read(cx).snapshot(cx);
4591        assert_eq!(snapshot.text(), "ab");
4592
4593        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4594        let snapshot = multibuffer.read(cx).snapshot(cx);
4595        assert_eq!(snapshot.text(), "abc");
4596    }
4597
4598    #[gpui::test]
4599    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4600        let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4601        let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
4602        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4603
4604        let events = Arc::new(RwLock::new(Vec::<Event>::new()));
4605        multibuffer.update(cx, |_, cx| {
4606            let events = events.clone();
4607            cx.subscribe(&multibuffer, move |_, _, event, _| {
4608                if let Event::Edited { .. } = event {
4609                    events.write().push(event.clone())
4610                }
4611            })
4612            .detach();
4613        });
4614
4615        let subscription = multibuffer.update(cx, |multibuffer, cx| {
4616            let subscription = multibuffer.subscribe();
4617            multibuffer.push_excerpts(
4618                buffer_1.clone(),
4619                [ExcerptRange {
4620                    context: Point::new(1, 2)..Point::new(2, 5),
4621                    primary: None,
4622                }],
4623                cx,
4624            );
4625            assert_eq!(
4626                subscription.consume().into_inner(),
4627                [Edit {
4628                    old: 0..0,
4629                    new: 0..10
4630                }]
4631            );
4632
4633            multibuffer.push_excerpts(
4634                buffer_1.clone(),
4635                [ExcerptRange {
4636                    context: Point::new(3, 3)..Point::new(4, 4),
4637                    primary: None,
4638                }],
4639                cx,
4640            );
4641            multibuffer.push_excerpts(
4642                buffer_2.clone(),
4643                [ExcerptRange {
4644                    context: Point::new(3, 1)..Point::new(3, 3),
4645                    primary: None,
4646                }],
4647                cx,
4648            );
4649            assert_eq!(
4650                subscription.consume().into_inner(),
4651                [Edit {
4652                    old: 10..10,
4653                    new: 10..22
4654                }]
4655            );
4656
4657            subscription
4658        });
4659
4660        // Adding excerpts emits an edited event.
4661        assert_eq!(
4662            events.read().as_slice(),
4663            &[
4664                Event::Edited {
4665                    singleton_buffer_edited: false
4666                },
4667                Event::Edited {
4668                    singleton_buffer_edited: false
4669                },
4670                Event::Edited {
4671                    singleton_buffer_edited: false
4672                }
4673            ]
4674        );
4675
4676        let snapshot = multibuffer.read(cx).snapshot(cx);
4677        assert_eq!(
4678            snapshot.text(),
4679            concat!(
4680                "bbbb\n",  // Preserve newlines
4681                "ccccc\n", //
4682                "ddd\n",   //
4683                "eeee\n",  //
4684                "jj"       //
4685            )
4686        );
4687        assert_eq!(
4688            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4689            [Some(1), Some(2), Some(3), Some(4), Some(3)]
4690        );
4691        assert_eq!(
4692            snapshot.buffer_rows(2).collect::<Vec<_>>(),
4693            [Some(3), Some(4), Some(3)]
4694        );
4695        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4696        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4697
4698        assert_eq!(
4699            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4700            &[
4701                (0, "bbbb\nccccc".to_string(), true),
4702                (2, "ddd\neeee".to_string(), false),
4703                (4, "jj".to_string(), true),
4704            ]
4705        );
4706        assert_eq!(
4707            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4708            &[(0, "bbbb\nccccc".to_string(), true)]
4709        );
4710        assert_eq!(
4711            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4712            &[]
4713        );
4714        assert_eq!(
4715            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4716            &[]
4717        );
4718        assert_eq!(
4719            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4720            &[(2, "ddd\neeee".to_string(), false)]
4721        );
4722        assert_eq!(
4723            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4724            &[(2, "ddd\neeee".to_string(), false)]
4725        );
4726        assert_eq!(
4727            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4728            &[(2, "ddd\neeee".to_string(), false)]
4729        );
4730        assert_eq!(
4731            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4732            &[(4, "jj".to_string(), true)]
4733        );
4734        assert_eq!(
4735            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4736            &[]
4737        );
4738
4739        buffer_1.update(cx, |buffer, cx| {
4740            let text = "\n";
4741            buffer.edit(
4742                [
4743                    (Point::new(0, 0)..Point::new(0, 0), text),
4744                    (Point::new(2, 1)..Point::new(2, 3), text),
4745                ],
4746                None,
4747                cx,
4748            );
4749        });
4750
4751        let snapshot = multibuffer.read(cx).snapshot(cx);
4752        assert_eq!(
4753            snapshot.text(),
4754            concat!(
4755                "bbbb\n", // Preserve newlines
4756                "c\n",    //
4757                "cc\n",   //
4758                "ddd\n",  //
4759                "eeee\n", //
4760                "jj"      //
4761            )
4762        );
4763
4764        assert_eq!(
4765            subscription.consume().into_inner(),
4766            [Edit {
4767                old: 6..8,
4768                new: 6..7
4769            }]
4770        );
4771
4772        let snapshot = multibuffer.read(cx).snapshot(cx);
4773        assert_eq!(
4774            snapshot.clip_point(Point::new(0, 5), Bias::Left),
4775            Point::new(0, 4)
4776        );
4777        assert_eq!(
4778            snapshot.clip_point(Point::new(0, 5), Bias::Right),
4779            Point::new(0, 4)
4780        );
4781        assert_eq!(
4782            snapshot.clip_point(Point::new(5, 1), Bias::Right),
4783            Point::new(5, 1)
4784        );
4785        assert_eq!(
4786            snapshot.clip_point(Point::new(5, 2), Bias::Right),
4787            Point::new(5, 2)
4788        );
4789        assert_eq!(
4790            snapshot.clip_point(Point::new(5, 3), Bias::Right),
4791            Point::new(5, 2)
4792        );
4793
4794        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4795            let (buffer_2_excerpt_id, _) =
4796                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4797            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4798            multibuffer.snapshot(cx)
4799        });
4800
4801        assert_eq!(
4802            snapshot.text(),
4803            concat!(
4804                "bbbb\n", // Preserve newlines
4805                "c\n",    //
4806                "cc\n",   //
4807                "ddd\n",  //
4808                "eeee",   //
4809            )
4810        );
4811
4812        fn boundaries_in_range(
4813            range: Range<Point>,
4814            snapshot: &MultiBufferSnapshot,
4815        ) -> Vec<(u32, String, bool)> {
4816            snapshot
4817                .excerpt_boundaries_in_range(range)
4818                .map(|boundary| {
4819                    (
4820                        boundary.row,
4821                        boundary
4822                            .buffer
4823                            .text_for_range(boundary.range.context)
4824                            .collect::<String>(),
4825                        boundary.starts_new_buffer,
4826                    )
4827                })
4828                .collect::<Vec<_>>()
4829        }
4830    }
4831
4832    #[gpui::test]
4833    fn test_excerpt_events(cx: &mut AppContext) {
4834        let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
4835        let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
4836
4837        let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4838        let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4839        let follower_edit_event_count = Arc::new(RwLock::new(0));
4840
4841        follower_multibuffer.update(cx, |_, cx| {
4842            let follower_edit_event_count = follower_edit_event_count.clone();
4843            cx.subscribe(
4844                &leader_multibuffer,
4845                move |follower, _, event, cx| match event.clone() {
4846                    Event::ExcerptsAdded {
4847                        buffer,
4848                        predecessor,
4849                        excerpts,
4850                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4851                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4852                    Event::Edited { .. } => {
4853                        *follower_edit_event_count.write() += 1;
4854                    }
4855                    _ => {}
4856                },
4857            )
4858            .detach();
4859        });
4860
4861        leader_multibuffer.update(cx, |leader, cx| {
4862            leader.push_excerpts(
4863                buffer_1.clone(),
4864                [
4865                    ExcerptRange {
4866                        context: 0..8,
4867                        primary: None,
4868                    },
4869                    ExcerptRange {
4870                        context: 12..16,
4871                        primary: None,
4872                    },
4873                ],
4874                cx,
4875            );
4876            leader.insert_excerpts_after(
4877                leader.excerpt_ids()[0],
4878                buffer_2.clone(),
4879                [
4880                    ExcerptRange {
4881                        context: 0..5,
4882                        primary: None,
4883                    },
4884                    ExcerptRange {
4885                        context: 10..15,
4886                        primary: None,
4887                    },
4888                ],
4889                cx,
4890            )
4891        });
4892        assert_eq!(
4893            leader_multibuffer.read(cx).snapshot(cx).text(),
4894            follower_multibuffer.read(cx).snapshot(cx).text(),
4895        );
4896        assert_eq!(*follower_edit_event_count.read(), 2);
4897
4898        leader_multibuffer.update(cx, |leader, cx| {
4899            let excerpt_ids = leader.excerpt_ids();
4900            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4901        });
4902        assert_eq!(
4903            leader_multibuffer.read(cx).snapshot(cx).text(),
4904            follower_multibuffer.read(cx).snapshot(cx).text(),
4905        );
4906        assert_eq!(*follower_edit_event_count.read(), 3);
4907
4908        // Removing an empty set of excerpts is a noop.
4909        leader_multibuffer.update(cx, |leader, cx| {
4910            leader.remove_excerpts([], cx);
4911        });
4912        assert_eq!(
4913            leader_multibuffer.read(cx).snapshot(cx).text(),
4914            follower_multibuffer.read(cx).snapshot(cx).text(),
4915        );
4916        assert_eq!(*follower_edit_event_count.read(), 3);
4917
4918        // Adding an empty set of excerpts is a noop.
4919        leader_multibuffer.update(cx, |leader, cx| {
4920            leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4921        });
4922        assert_eq!(
4923            leader_multibuffer.read(cx).snapshot(cx).text(),
4924            follower_multibuffer.read(cx).snapshot(cx).text(),
4925        );
4926        assert_eq!(*follower_edit_event_count.read(), 3);
4927
4928        leader_multibuffer.update(cx, |leader, cx| {
4929            leader.clear(cx);
4930        });
4931        assert_eq!(
4932            leader_multibuffer.read(cx).snapshot(cx).text(),
4933            follower_multibuffer.read(cx).snapshot(cx).text(),
4934        );
4935        assert_eq!(*follower_edit_event_count.read(), 4);
4936    }
4937
4938    #[gpui::test]
4939    fn test_expand_excerpts(cx: &mut AppContext) {
4940        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
4941        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4942
4943        multibuffer.update(cx, |multibuffer, cx| {
4944            multibuffer.push_excerpts_with_context_lines(
4945                buffer.clone(),
4946                vec![
4947                    // Note that in this test, this first excerpt
4948                    // does not contain a new line
4949                    Point::new(3, 2)..Point::new(3, 3),
4950                    Point::new(7, 1)..Point::new(7, 3),
4951                    Point::new(15, 0)..Point::new(15, 0),
4952                ],
4953                1,
4954                cx,
4955            )
4956        });
4957
4958        multibuffer.update(cx, |multibuffer, cx| {
4959            multibuffer.expand_excerpts(multibuffer.excerpt_ids(), 1, cx)
4960        });
4961
4962        let snapshot = multibuffer.read(cx).snapshot(cx);
4963
4964        // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
4965        // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
4966        // that are tracking excerpt ids.
4967        assert_eq!(
4968            snapshot.text(),
4969            concat!(
4970                "bbb\n", // Preserve newlines
4971                "ccc\n", //
4972                "ddd\n", //
4973                "eee\n", //
4974                "fff\n", // <- Same as below
4975                "\n",    // Excerpt boundary
4976                "fff\n", // <- Same as above
4977                "ggg\n", //
4978                "hhh\n", //
4979                "iii\n", //
4980                "jjj\n", //
4981                "\n",    //
4982                "nnn\n", //
4983                "ooo\n", //
4984                "ppp\n", //
4985                "qqq\n", //
4986                "rrr\n", //
4987            )
4988        );
4989    }
4990
4991    #[gpui::test]
4992    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4993        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
4994        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4995        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4996            multibuffer.push_excerpts_with_context_lines(
4997                buffer.clone(),
4998                vec![
4999                    // Note that in this test, this first excerpt
5000                    // does contain a new line
5001                    Point::new(3, 2)..Point::new(4, 2),
5002                    Point::new(7, 1)..Point::new(7, 3),
5003                    Point::new(15, 0)..Point::new(15, 0),
5004                ],
5005                2,
5006                cx,
5007            )
5008        });
5009
5010        let snapshot = multibuffer.read(cx).snapshot(cx);
5011        assert_eq!(
5012            snapshot.text(),
5013            concat!(
5014                "bbb\n", // Preserve newlines
5015                "ccc\n", //
5016                "ddd\n", //
5017                "eee\n", //
5018                "fff\n", //
5019                "ggg\n", //
5020                "hhh\n", //
5021                "iii\n", //
5022                "jjj\n", //
5023                "\n",    //
5024                "nnn\n", //
5025                "ooo\n", //
5026                "ppp\n", //
5027                "qqq\n", //
5028                "rrr\n", //
5029            )
5030        );
5031
5032        assert_eq!(
5033            anchor_ranges
5034                .iter()
5035                .map(|range| range.to_point(&snapshot))
5036                .collect::<Vec<_>>(),
5037            vec![
5038                Point::new(2, 2)..Point::new(3, 2),
5039                Point::new(6, 1)..Point::new(6, 3),
5040                Point::new(12, 0)..Point::new(12, 0)
5041            ]
5042        );
5043    }
5044
5045    #[gpui::test]
5046    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
5047        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5048        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5049        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5050            let snapshot = buffer.read(cx);
5051            let ranges = vec![
5052                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
5053                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
5054                snapshot.anchor_before(Point::new(15, 0))
5055                    ..snapshot.anchor_before(Point::new(15, 0)),
5056            ];
5057            multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
5058        });
5059
5060        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
5061
5062        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
5063        assert_eq!(
5064            snapshot.text(),
5065            concat!(
5066                "bbb\n", //
5067                "ccc\n", //
5068                "ddd\n", //
5069                "eee\n", //
5070                "fff\n", //
5071                "ggg\n", //
5072                "hhh\n", //
5073                "iii\n", //
5074                "jjj\n", //
5075                "\n",    //
5076                "nnn\n", //
5077                "ooo\n", //
5078                "ppp\n", //
5079                "qqq\n", //
5080                "rrr\n", //
5081            )
5082        );
5083
5084        assert_eq!(
5085            anchor_ranges
5086                .iter()
5087                .map(|range| range.to_point(&snapshot))
5088                .collect::<Vec<_>>(),
5089            vec![
5090                Point::new(2, 2)..Point::new(3, 2),
5091                Point::new(6, 1)..Point::new(6, 3),
5092                Point::new(12, 0)..Point::new(12, 0)
5093            ]
5094        );
5095    }
5096
5097    #[gpui::test]
5098    fn test_empty_multibuffer(cx: &mut AppContext) {
5099        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5100
5101        let snapshot = multibuffer.read(cx).snapshot(cx);
5102        assert_eq!(snapshot.text(), "");
5103        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
5104        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
5105    }
5106
5107    #[gpui::test]
5108    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
5109        let buffer = cx.new_model(|cx| Buffer::local("abcd", cx));
5110        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5111        let old_snapshot = multibuffer.read(cx).snapshot(cx);
5112        buffer.update(cx, |buffer, cx| {
5113            buffer.edit([(0..0, "X")], None, cx);
5114            buffer.edit([(5..5, "Y")], None, cx);
5115        });
5116        let new_snapshot = multibuffer.read(cx).snapshot(cx);
5117
5118        assert_eq!(old_snapshot.text(), "abcd");
5119        assert_eq!(new_snapshot.text(), "XabcdY");
5120
5121        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5122        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5123        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
5124        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
5125    }
5126
5127    #[gpui::test]
5128    fn test_multibuffer_anchors(cx: &mut AppContext) {
5129        let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5130        let buffer_2 = cx.new_model(|cx| Buffer::local("efghi", cx));
5131        let multibuffer = cx.new_model(|cx| {
5132            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
5133            multibuffer.push_excerpts(
5134                buffer_1.clone(),
5135                [ExcerptRange {
5136                    context: 0..4,
5137                    primary: None,
5138                }],
5139                cx,
5140            );
5141            multibuffer.push_excerpts(
5142                buffer_2.clone(),
5143                [ExcerptRange {
5144                    context: 0..5,
5145                    primary: None,
5146                }],
5147                cx,
5148            );
5149            multibuffer
5150        });
5151        let old_snapshot = multibuffer.read(cx).snapshot(cx);
5152
5153        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
5154        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
5155        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5156        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5157        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5158        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5159
5160        buffer_1.update(cx, |buffer, cx| {
5161            buffer.edit([(0..0, "W")], None, cx);
5162            buffer.edit([(5..5, "X")], None, cx);
5163        });
5164        buffer_2.update(cx, |buffer, cx| {
5165            buffer.edit([(0..0, "Y")], None, cx);
5166            buffer.edit([(6..6, "Z")], None, cx);
5167        });
5168        let new_snapshot = multibuffer.read(cx).snapshot(cx);
5169
5170        assert_eq!(old_snapshot.text(), "abcd\nefghi");
5171        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
5172
5173        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5174        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5175        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
5176        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
5177        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
5178        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
5179        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
5180        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
5181        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
5182        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
5183    }
5184
5185    #[gpui::test]
5186    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
5187        let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5188        let buffer_2 = cx.new_model(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
5189        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5190
5191        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
5192        // Add an excerpt from buffer 1 that spans this new insertion.
5193        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
5194        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
5195            multibuffer
5196                .push_excerpts(
5197                    buffer_1.clone(),
5198                    [ExcerptRange {
5199                        context: 0..7,
5200                        primary: None,
5201                    }],
5202                    cx,
5203                )
5204                .pop()
5205                .unwrap()
5206        });
5207
5208        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
5209        assert_eq!(snapshot_1.text(), "abcd123");
5210
5211        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
5212        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
5213            multibuffer.remove_excerpts([excerpt_id_1], cx);
5214            let mut ids = multibuffer
5215                .push_excerpts(
5216                    buffer_2.clone(),
5217                    [
5218                        ExcerptRange {
5219                            context: 0..4,
5220                            primary: None,
5221                        },
5222                        ExcerptRange {
5223                            context: 6..10,
5224                            primary: None,
5225                        },
5226                        ExcerptRange {
5227                            context: 12..16,
5228                            primary: None,
5229                        },
5230                    ],
5231                    cx,
5232                )
5233                .into_iter();
5234            (ids.next().unwrap(), ids.next().unwrap())
5235        });
5236        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
5237        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
5238
5239        // The old excerpt id doesn't get reused.
5240        assert_ne!(excerpt_id_2, excerpt_id_1);
5241
5242        // Resolve some anchors from the previous snapshot in the new snapshot.
5243        // The current excerpts are from a different buffer, so we don't attempt to
5244        // resolve the old text anchor in the new buffer.
5245        assert_eq!(
5246            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
5247            0
5248        );
5249        assert_eq!(
5250            snapshot_2.summaries_for_anchors::<usize, _>(&[
5251                snapshot_1.anchor_before(2),
5252                snapshot_1.anchor_after(3)
5253            ]),
5254            vec![0, 0]
5255        );
5256
5257        // Refresh anchors from the old snapshot. The return value indicates that both
5258        // anchors lost their original excerpt.
5259        let refresh =
5260            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5261        assert_eq!(
5262            refresh,
5263            &[
5264                (0, snapshot_2.anchor_before(0), false),
5265                (1, snapshot_2.anchor_after(0), false),
5266            ]
5267        );
5268
5269        // Replace the middle excerpt with a smaller excerpt in buffer 2,
5270        // that intersects the old excerpt.
5271        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5272            multibuffer.remove_excerpts([excerpt_id_3], cx);
5273            multibuffer
5274                .insert_excerpts_after(
5275                    excerpt_id_2,
5276                    buffer_2.clone(),
5277                    [ExcerptRange {
5278                        context: 5..8,
5279                        primary: None,
5280                    }],
5281                    cx,
5282                )
5283                .pop()
5284                .unwrap()
5285        });
5286
5287        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5288        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5289        assert_ne!(excerpt_id_5, excerpt_id_3);
5290
5291        // Resolve some anchors from the previous snapshot in the new snapshot.
5292        // The third anchor can't be resolved, since its excerpt has been removed,
5293        // so it resolves to the same position as its predecessor.
5294        let anchors = [
5295            snapshot_2.anchor_before(0),
5296            snapshot_2.anchor_after(2),
5297            snapshot_2.anchor_after(6),
5298            snapshot_2.anchor_after(14),
5299        ];
5300        assert_eq!(
5301            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5302            &[0, 2, 9, 13]
5303        );
5304
5305        let new_anchors = snapshot_3.refresh_anchors(&anchors);
5306        assert_eq!(
5307            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5308            &[(0, true), (1, true), (2, true), (3, true)]
5309        );
5310        assert_eq!(
5311            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5312            &[0, 2, 7, 13]
5313        );
5314    }
5315
5316    #[gpui::test(iterations = 100)]
5317    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5318        let operations = env::var("OPERATIONS")
5319            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5320            .unwrap_or(10);
5321
5322        let mut buffers: Vec<Model<Buffer>> = Vec::new();
5323        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5324        let mut excerpt_ids = Vec::<ExcerptId>::new();
5325        let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5326        let mut anchors = Vec::new();
5327        let mut old_versions = Vec::new();
5328
5329        for _ in 0..operations {
5330            match rng.gen_range(0..100) {
5331                0..=14 if !buffers.is_empty() => {
5332                    let buffer = buffers.choose(&mut rng).unwrap();
5333                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5334                }
5335                15..=19 if !expected_excerpts.is_empty() => {
5336                    multibuffer.update(cx, |multibuffer, cx| {
5337                        let ids = multibuffer.excerpt_ids();
5338                        let mut excerpts = HashSet::default();
5339                        for _ in 0..rng.gen_range(0..ids.len()) {
5340                            excerpts.extend(ids.choose(&mut rng).copied());
5341                        }
5342
5343                        let line_count = rng.gen_range(0..5);
5344
5345                        let excerpt_ixs = excerpts
5346                            .iter()
5347                            .map(|id| excerpt_ids.iter().position(|i| i == id).unwrap())
5348                            .collect::<Vec<_>>();
5349                        log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
5350                        multibuffer.expand_excerpts(excerpts.iter().cloned(), line_count, cx);
5351
5352                        if line_count > 0 {
5353                            for id in excerpts {
5354                                let excerpt_ix = excerpt_ids.iter().position(|&i| i == id).unwrap();
5355                                let (buffer, range) = &mut expected_excerpts[excerpt_ix];
5356                                let snapshot = buffer.read(cx).snapshot();
5357                                let mut point_range = range.to_point(&snapshot);
5358                                point_range.start =
5359                                    Point::new(point_range.start.row.saturating_sub(line_count), 0);
5360                                point_range.end = snapshot.clip_point(
5361                                    Point::new(point_range.end.row + line_count, 0),
5362                                    Bias::Left,
5363                                );
5364                                *range = snapshot.anchor_before(point_range.start)
5365                                    ..snapshot.anchor_after(point_range.end);
5366                            }
5367                        }
5368                    });
5369                }
5370                20..=29 if !expected_excerpts.is_empty() => {
5371                    let mut ids_to_remove = vec![];
5372                    for _ in 0..rng.gen_range(1..=3) {
5373                        if expected_excerpts.is_empty() {
5374                            break;
5375                        }
5376
5377                        let ix = rng.gen_range(0..expected_excerpts.len());
5378                        ids_to_remove.push(excerpt_ids.remove(ix));
5379                        let (buffer, range) = expected_excerpts.remove(ix);
5380                        let buffer = buffer.read(cx);
5381                        log::info!(
5382                            "Removing excerpt {}: {:?}",
5383                            ix,
5384                            buffer
5385                                .text_for_range(range.to_offset(buffer))
5386                                .collect::<String>(),
5387                        );
5388                    }
5389                    let snapshot = multibuffer.read(cx).read(cx);
5390                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
5391                    drop(snapshot);
5392                    multibuffer.update(cx, |multibuffer, cx| {
5393                        multibuffer.remove_excerpts(ids_to_remove, cx)
5394                    });
5395                }
5396                30..=39 if !expected_excerpts.is_empty() => {
5397                    let multibuffer = multibuffer.read(cx).read(cx);
5398                    let offset =
5399                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
5400                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
5401                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
5402                    anchors.push(multibuffer.anchor_at(offset, bias));
5403                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
5404                }
5405                40..=44 if !anchors.is_empty() => {
5406                    let multibuffer = multibuffer.read(cx).read(cx);
5407                    let prev_len = anchors.len();
5408                    anchors = multibuffer
5409                        .refresh_anchors(&anchors)
5410                        .into_iter()
5411                        .map(|a| a.1)
5412                        .collect();
5413
5414                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
5415                    // overshoot its boundaries.
5416                    assert_eq!(anchors.len(), prev_len);
5417                    for anchor in &anchors {
5418                        if anchor.excerpt_id == ExcerptId::min()
5419                            || anchor.excerpt_id == ExcerptId::max()
5420                        {
5421                            continue;
5422                        }
5423
5424                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
5425                        assert_eq!(excerpt.id, anchor.excerpt_id);
5426                        assert!(excerpt.contains(anchor));
5427                    }
5428                }
5429                _ => {
5430                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
5431                        let base_text = util::RandomCharIter::new(&mut rng)
5432                            .take(25)
5433                            .collect::<String>();
5434
5435                        buffers.push(cx.new_model(|cx| Buffer::local(base_text, cx)));
5436                        buffers.last().unwrap()
5437                    } else {
5438                        buffers.choose(&mut rng).unwrap()
5439                    };
5440
5441                    let buffer = buffer_handle.read(cx);
5442                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
5443                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5444                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
5445                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
5446                    let prev_excerpt_id = excerpt_ids
5447                        .get(prev_excerpt_ix)
5448                        .cloned()
5449                        .unwrap_or_else(ExcerptId::max);
5450                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
5451
5452                    log::info!(
5453                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
5454                        excerpt_ix,
5455                        expected_excerpts.len(),
5456                        buffer_handle.read(cx).remote_id(),
5457                        buffer.text(),
5458                        start_ix..end_ix,
5459                        &buffer.text()[start_ix..end_ix]
5460                    );
5461
5462                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
5463                        multibuffer
5464                            .insert_excerpts_after(
5465                                prev_excerpt_id,
5466                                buffer_handle.clone(),
5467                                [ExcerptRange {
5468                                    context: start_ix..end_ix,
5469                                    primary: None,
5470                                }],
5471                                cx,
5472                            )
5473                            .pop()
5474                            .unwrap()
5475                    });
5476
5477                    excerpt_ids.insert(excerpt_ix, excerpt_id);
5478                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5479                }
5480            }
5481
5482            if rng.gen_bool(0.3) {
5483                multibuffer.update(cx, |multibuffer, cx| {
5484                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5485                })
5486            }
5487
5488            let snapshot = multibuffer.read(cx).snapshot(cx);
5489
5490            let mut excerpt_starts = Vec::new();
5491            let mut expected_text = String::new();
5492            let mut expected_buffer_rows = Vec::new();
5493            for (buffer, range) in &expected_excerpts {
5494                let buffer = buffer.read(cx);
5495                let buffer_range = range.to_offset(buffer);
5496
5497                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5498                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5499                expected_text.push('\n');
5500
5501                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5502                    ..=buffer.offset_to_point(buffer_range.end).row;
5503                for row in buffer_row_range {
5504                    expected_buffer_rows.push(Some(row));
5505                }
5506            }
5507            // Remove final trailing newline.
5508            if !expected_excerpts.is_empty() {
5509                expected_text.pop();
5510            }
5511
5512            // Always report one buffer row
5513            if expected_buffer_rows.is_empty() {
5514                expected_buffer_rows.push(Some(0));
5515            }
5516
5517            assert_eq!(snapshot.text(), expected_text);
5518            log::info!("MultiBuffer text: {:?}", expected_text);
5519
5520            assert_eq!(
5521                snapshot.buffer_rows(0).collect::<Vec<_>>(),
5522                expected_buffer_rows,
5523            );
5524
5525            for _ in 0..5 {
5526                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5527                assert_eq!(
5528                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
5529                    &expected_buffer_rows[start_row..],
5530                    "buffer_rows({})",
5531                    start_row
5532                );
5533            }
5534
5535            assert_eq!(
5536                snapshot.max_buffer_row(),
5537                expected_buffer_rows.into_iter().flatten().max().unwrap()
5538            );
5539
5540            let mut excerpt_starts = excerpt_starts.into_iter();
5541            for (buffer, range) in &expected_excerpts {
5542                let buffer = buffer.read(cx);
5543                let buffer_id = buffer.remote_id();
5544                let buffer_range = range.to_offset(buffer);
5545                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5546                let buffer_start_point_utf16 =
5547                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5548
5549                let excerpt_start = excerpt_starts.next().unwrap();
5550                let mut offset = excerpt_start.len;
5551                let mut buffer_offset = buffer_range.start;
5552                let mut point = excerpt_start.lines;
5553                let mut buffer_point = buffer_start_point;
5554                let mut point_utf16 = excerpt_start.lines_utf16();
5555                let mut buffer_point_utf16 = buffer_start_point_utf16;
5556                for ch in buffer
5557                    .snapshot()
5558                    .chunks(buffer_range.clone(), false)
5559                    .flat_map(|c| c.text.chars())
5560                {
5561                    for _ in 0..ch.len_utf8() {
5562                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
5563                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
5564                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5565                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5566                        assert_eq!(
5567                            left_offset,
5568                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
5569                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5570                            offset,
5571                            buffer_id,
5572                            buffer_offset,
5573                        );
5574                        assert_eq!(
5575                            right_offset,
5576                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
5577                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5578                            offset,
5579                            buffer_id,
5580                            buffer_offset,
5581                        );
5582
5583                        let left_point = snapshot.clip_point(point, Bias::Left);
5584                        let right_point = snapshot.clip_point(point, Bias::Right);
5585                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5586                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5587                        assert_eq!(
5588                            left_point,
5589                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
5590                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5591                            point,
5592                            buffer_id,
5593                            buffer_point,
5594                        );
5595                        assert_eq!(
5596                            right_point,
5597                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
5598                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5599                            point,
5600                            buffer_id,
5601                            buffer_point,
5602                        );
5603
5604                        assert_eq!(
5605                            snapshot.point_to_offset(left_point),
5606                            left_offset,
5607                            "point_to_offset({:?})",
5608                            left_point,
5609                        );
5610                        assert_eq!(
5611                            snapshot.offset_to_point(left_offset),
5612                            left_point,
5613                            "offset_to_point({:?})",
5614                            left_offset,
5615                        );
5616
5617                        offset += 1;
5618                        buffer_offset += 1;
5619                        if ch == '\n' {
5620                            point += Point::new(1, 0);
5621                            buffer_point += Point::new(1, 0);
5622                        } else {
5623                            point += Point::new(0, 1);
5624                            buffer_point += Point::new(0, 1);
5625                        }
5626                    }
5627
5628                    for _ in 0..ch.len_utf16() {
5629                        let left_point_utf16 =
5630                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5631                        let right_point_utf16 =
5632                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5633                        let buffer_left_point_utf16 =
5634                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5635                        let buffer_right_point_utf16 =
5636                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5637                        assert_eq!(
5638                            left_point_utf16,
5639                            excerpt_start.lines_utf16()
5640                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
5641                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5642                            point_utf16,
5643                            buffer_id,
5644                            buffer_point_utf16,
5645                        );
5646                        assert_eq!(
5647                            right_point_utf16,
5648                            excerpt_start.lines_utf16()
5649                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
5650                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5651                            point_utf16,
5652                            buffer_id,
5653                            buffer_point_utf16,
5654                        );
5655
5656                        if ch == '\n' {
5657                            point_utf16 += PointUtf16::new(1, 0);
5658                            buffer_point_utf16 += PointUtf16::new(1, 0);
5659                        } else {
5660                            point_utf16 += PointUtf16::new(0, 1);
5661                            buffer_point_utf16 += PointUtf16::new(0, 1);
5662                        }
5663                    }
5664                }
5665            }
5666
5667            for (row, line) in expected_text.split('\n').enumerate() {
5668                assert_eq!(
5669                    snapshot.line_len(row as u32),
5670                    line.len() as u32,
5671                    "line_len({}).",
5672                    row
5673                );
5674            }
5675
5676            let text_rope = Rope::from(expected_text.as_str());
5677            for _ in 0..10 {
5678                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5679                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5680
5681                let text_for_range = snapshot
5682                    .text_for_range(start_ix..end_ix)
5683                    .collect::<String>();
5684                assert_eq!(
5685                    text_for_range,
5686                    &expected_text[start_ix..end_ix],
5687                    "incorrect text for range {:?}",
5688                    start_ix..end_ix
5689                );
5690
5691                let excerpted_buffer_ranges = multibuffer
5692                    .read(cx)
5693                    .range_to_buffer_ranges(start_ix..end_ix, cx);
5694                let excerpted_buffers_text = excerpted_buffer_ranges
5695                    .iter()
5696                    .map(|(buffer, buffer_range, _)| {
5697                        buffer
5698                            .read(cx)
5699                            .text_for_range(buffer_range.clone())
5700                            .collect::<String>()
5701                    })
5702                    .collect::<Vec<_>>()
5703                    .join("\n");
5704                assert_eq!(excerpted_buffers_text, text_for_range);
5705                if !expected_excerpts.is_empty() {
5706                    assert!(!excerpted_buffer_ranges.is_empty());
5707                }
5708
5709                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5710                assert_eq!(
5711                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5712                    expected_summary,
5713                    "incorrect summary for range {:?}",
5714                    start_ix..end_ix
5715                );
5716            }
5717
5718            // Anchor resolution
5719            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5720            assert_eq!(anchors.len(), summaries.len());
5721            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5722                assert!(resolved_offset <= snapshot.len());
5723                assert_eq!(
5724                    snapshot.summary_for_anchor::<usize>(anchor),
5725                    resolved_offset
5726                );
5727            }
5728
5729            for _ in 0..10 {
5730                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5731                assert_eq!(
5732                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
5733                    expected_text[..end_ix].chars().rev().collect::<String>(),
5734                );
5735            }
5736
5737            for _ in 0..10 {
5738                let end_ix = rng.gen_range(0..=text_rope.len());
5739                let start_ix = rng.gen_range(0..=end_ix);
5740                assert_eq!(
5741                    snapshot
5742                        .bytes_in_range(start_ix..end_ix)
5743                        .flatten()
5744                        .copied()
5745                        .collect::<Vec<_>>(),
5746                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5747                    "bytes_in_range({:?})",
5748                    start_ix..end_ix,
5749                );
5750            }
5751        }
5752
5753        let snapshot = multibuffer.read(cx).snapshot(cx);
5754        for (old_snapshot, subscription) in old_versions {
5755            let edits = subscription.consume().into_inner();
5756
5757            log::info!(
5758                "applying subscription edits to old text: {:?}: {:?}",
5759                old_snapshot.text(),
5760                edits,
5761            );
5762
5763            let mut text = old_snapshot.text();
5764            for edit in edits {
5765                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5766                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5767            }
5768            assert_eq!(text.to_string(), snapshot.text());
5769        }
5770    }
5771
5772    #[gpui::test]
5773    fn test_history(cx: &mut AppContext) {
5774        let test_settings = SettingsStore::test(cx);
5775        cx.set_global(test_settings);
5776
5777        let buffer_1 = cx.new_model(|cx| Buffer::local("1234", cx));
5778        let buffer_2 = cx.new_model(|cx| Buffer::local("5678", cx));
5779        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5780        let group_interval = multibuffer.read(cx).history.group_interval;
5781        multibuffer.update(cx, |multibuffer, cx| {
5782            multibuffer.push_excerpts(
5783                buffer_1.clone(),
5784                [ExcerptRange {
5785                    context: 0..buffer_1.read(cx).len(),
5786                    primary: None,
5787                }],
5788                cx,
5789            );
5790            multibuffer.push_excerpts(
5791                buffer_2.clone(),
5792                [ExcerptRange {
5793                    context: 0..buffer_2.read(cx).len(),
5794                    primary: None,
5795                }],
5796                cx,
5797            );
5798        });
5799
5800        let mut now = Instant::now();
5801
5802        multibuffer.update(cx, |multibuffer, cx| {
5803            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5804            multibuffer.edit(
5805                [
5806                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5807                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5808                ],
5809                None,
5810                cx,
5811            );
5812            multibuffer.edit(
5813                [
5814                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5815                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5816                ],
5817                None,
5818                cx,
5819            );
5820            multibuffer.end_transaction_at(now, cx);
5821            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5822
5823            // Edit buffer 1 through the multibuffer
5824            now += 2 * group_interval;
5825            multibuffer.start_transaction_at(now, cx);
5826            multibuffer.edit([(2..2, "C")], None, cx);
5827            multibuffer.end_transaction_at(now, cx);
5828            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5829
5830            // Edit buffer 1 independently
5831            buffer_1.update(cx, |buffer_1, cx| {
5832                buffer_1.start_transaction_at(now);
5833                buffer_1.edit([(3..3, "D")], None, cx);
5834                buffer_1.end_transaction_at(now, cx);
5835
5836                now += 2 * group_interval;
5837                buffer_1.start_transaction_at(now);
5838                buffer_1.edit([(4..4, "E")], None, cx);
5839                buffer_1.end_transaction_at(now, cx);
5840            });
5841            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5842
5843            // An undo in the multibuffer undoes the multibuffer transaction
5844            // and also any individual buffer edits that have occurred since
5845            // that transaction.
5846            multibuffer.undo(cx);
5847            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5848
5849            multibuffer.undo(cx);
5850            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5851
5852            multibuffer.redo(cx);
5853            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5854
5855            multibuffer.redo(cx);
5856            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5857
5858            // Undo buffer 2 independently.
5859            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5860            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5861
5862            // An undo in the multibuffer undoes the components of the
5863            // the last multibuffer transaction that are not already undone.
5864            multibuffer.undo(cx);
5865            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5866
5867            multibuffer.undo(cx);
5868            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5869
5870            multibuffer.redo(cx);
5871            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5872
5873            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5874            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5875
5876            // Redo stack gets cleared after an edit.
5877            now += 2 * group_interval;
5878            multibuffer.start_transaction_at(now, cx);
5879            multibuffer.edit([(0..0, "X")], None, cx);
5880            multibuffer.end_transaction_at(now, cx);
5881            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5882            multibuffer.redo(cx);
5883            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5884            multibuffer.undo(cx);
5885            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5886            multibuffer.undo(cx);
5887            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5888
5889            // Transactions can be grouped manually.
5890            multibuffer.redo(cx);
5891            multibuffer.redo(cx);
5892            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5893            multibuffer.group_until_transaction(transaction_1, cx);
5894            multibuffer.undo(cx);
5895            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5896            multibuffer.redo(cx);
5897            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5898        });
5899    }
5900}