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(&self, position: Anchor, text: &str, cx: &AppContext) -> bool {
1526        let mut chars = text.chars();
1527        let char = if let Some(char) = chars.next() {
1528            char
1529        } else {
1530            return false;
1531        };
1532        if chars.next().is_some() {
1533            return false;
1534        }
1535
1536        let snapshot = self.snapshot(cx);
1537        let position = position.to_offset(&snapshot);
1538        let scope = snapshot.language_scope_at(position);
1539        if char_kind(&scope, char) == CharKind::Word {
1540            return true;
1541        }
1542
1543        let anchor = snapshot.anchor_before(position);
1544        anchor
1545            .buffer_id
1546            .and_then(|buffer_id| {
1547                let buffer = self.buffers.borrow().get(&buffer_id)?.buffer.clone();
1548                Some(
1549                    buffer
1550                        .read(cx)
1551                        .completion_triggers()
1552                        .iter()
1553                        .any(|string| string == text),
1554                )
1555            })
1556            .unwrap_or(false)
1557    }
1558
1559    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1560        self.point_to_buffer_offset(point, cx)
1561            .and_then(|(buffer, offset, _)| buffer.read(cx).language_at(offset))
1562    }
1563
1564    pub fn settings_at<'a, T: ToOffset>(
1565        &self,
1566        point: T,
1567        cx: &'a AppContext,
1568    ) -> &'a LanguageSettings {
1569        let mut language = None;
1570        let mut file = None;
1571        if let Some((buffer, offset, _)) = self.point_to_buffer_offset(point, cx) {
1572            let buffer = buffer.read(cx);
1573            language = buffer.language_at(offset);
1574            file = buffer.file();
1575        }
1576        language_settings(language.as_ref(), file, cx)
1577    }
1578
1579    pub fn for_each_buffer(&self, mut f: impl FnMut(&Model<Buffer>)) {
1580        self.buffers
1581            .borrow()
1582            .values()
1583            .for_each(|state| f(&state.buffer))
1584    }
1585
1586    pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1587        if let Some(title) = self.title.as_ref() {
1588            return title.into();
1589        }
1590
1591        if let Some(buffer) = self.as_singleton() {
1592            if let Some(file) = buffer.read(cx).file() {
1593                return file.file_name(cx).to_string_lossy();
1594            }
1595        }
1596
1597        "untitled".into()
1598    }
1599
1600    #[cfg(any(test, feature = "test-support"))]
1601    pub fn is_parsing(&self, cx: &AppContext) -> bool {
1602        self.as_singleton().unwrap().read(cx).is_parsing()
1603    }
1604
1605    pub fn expand_excerpts(
1606        &mut self,
1607        ids: impl IntoIterator<Item = ExcerptId>,
1608        line_count: u32,
1609        cx: &mut ModelContext<Self>,
1610    ) {
1611        if line_count == 0 {
1612            return;
1613        }
1614        self.sync(cx);
1615
1616        let snapshot = self.snapshot(cx);
1617        let locators = snapshot.excerpt_locators_for_ids(ids);
1618        let mut new_excerpts = SumTree::new();
1619        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1620        let mut edits = Vec::<Edit<usize>>::new();
1621
1622        for locator in &locators {
1623            let prefix = cursor.slice(&Some(locator), Bias::Left, &());
1624            new_excerpts.append(prefix, &());
1625
1626            let mut excerpt = cursor.item().unwrap().clone();
1627            let old_text_len = excerpt.text_summary.len;
1628
1629            let start_row = excerpt
1630                .range
1631                .context
1632                .start
1633                .to_point(&excerpt.buffer)
1634                .row
1635                .saturating_sub(line_count);
1636            let start_point = Point::new(start_row, 0);
1637            excerpt.range.context.start = excerpt.buffer.anchor_before(start_point);
1638
1639            let end_point = excerpt.buffer.clip_point(
1640                excerpt.range.context.end.to_point(&excerpt.buffer) + Point::new(line_count, 0),
1641                Bias::Left,
1642            );
1643            excerpt.range.context.end = excerpt.buffer.anchor_after(end_point);
1644            excerpt.max_buffer_row = end_point.row;
1645
1646            excerpt.text_summary = excerpt
1647                .buffer
1648                .text_summary_for_range(start_point..end_point);
1649
1650            let new_start_offset = new_excerpts.summary().text.len;
1651            let old_start_offset = cursor.start().1;
1652            let edit = Edit {
1653                old: old_start_offset..old_start_offset + old_text_len,
1654                new: new_start_offset..new_start_offset + excerpt.text_summary.len,
1655            };
1656
1657            if let Some(last_edit) = edits.last_mut() {
1658                if last_edit.old.end == edit.old.start {
1659                    last_edit.old.end = edit.old.end;
1660                    last_edit.new.end = edit.new.end;
1661                } else {
1662                    edits.push(edit);
1663                }
1664            } else {
1665                edits.push(edit);
1666            }
1667
1668            new_excerpts.push(excerpt, &());
1669
1670            cursor.next(&());
1671        }
1672
1673        new_excerpts.append(cursor.suffix(&()), &());
1674
1675        drop(cursor);
1676        self.snapshot.borrow_mut().excerpts = new_excerpts;
1677
1678        self.subscriptions.publish_mut(edits);
1679        cx.emit(Event::Edited {
1680            singleton_buffer_edited: false,
1681        });
1682        cx.notify();
1683    }
1684
1685    fn sync(&self, cx: &AppContext) {
1686        let mut snapshot = self.snapshot.borrow_mut();
1687        let mut excerpts_to_edit = Vec::new();
1688        let mut reparsed = false;
1689        let mut diagnostics_updated = false;
1690        let mut git_diff_updated = false;
1691        let mut is_dirty = false;
1692        let mut has_conflict = false;
1693        let mut edited = false;
1694        let mut buffers = self.buffers.borrow_mut();
1695        for buffer_state in buffers.values_mut() {
1696            let buffer = buffer_state.buffer.read(cx);
1697            let version = buffer.version();
1698            let parse_count = buffer.parse_count();
1699            let selections_update_count = buffer.selections_update_count();
1700            let diagnostics_update_count = buffer.diagnostics_update_count();
1701            let file_update_count = buffer.file_update_count();
1702            let git_diff_update_count = buffer.git_diff_update_count();
1703
1704            let buffer_edited = version.changed_since(&buffer_state.last_version);
1705            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1706            let buffer_selections_updated =
1707                selections_update_count > buffer_state.last_selections_update_count;
1708            let buffer_diagnostics_updated =
1709                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1710            let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1711            let buffer_git_diff_updated =
1712                git_diff_update_count > buffer_state.last_git_diff_update_count;
1713            if buffer_edited
1714                || buffer_reparsed
1715                || buffer_selections_updated
1716                || buffer_diagnostics_updated
1717                || buffer_file_updated
1718                || buffer_git_diff_updated
1719            {
1720                buffer_state.last_version = version;
1721                buffer_state.last_parse_count = parse_count;
1722                buffer_state.last_selections_update_count = selections_update_count;
1723                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1724                buffer_state.last_file_update_count = file_update_count;
1725                buffer_state.last_git_diff_update_count = git_diff_update_count;
1726                excerpts_to_edit.extend(
1727                    buffer_state
1728                        .excerpts
1729                        .iter()
1730                        .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1731                );
1732            }
1733
1734            edited |= buffer_edited;
1735            reparsed |= buffer_reparsed;
1736            diagnostics_updated |= buffer_diagnostics_updated;
1737            git_diff_updated |= buffer_git_diff_updated;
1738            is_dirty |= buffer.is_dirty();
1739            has_conflict |= buffer.has_conflict();
1740        }
1741        if edited {
1742            snapshot.edit_count += 1;
1743        }
1744        if reparsed {
1745            snapshot.parse_count += 1;
1746        }
1747        if diagnostics_updated {
1748            snapshot.diagnostics_update_count += 1;
1749        }
1750        if git_diff_updated {
1751            snapshot.git_diff_update_count += 1;
1752        }
1753        snapshot.is_dirty = is_dirty;
1754        snapshot.has_conflict = has_conflict;
1755
1756        excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1757
1758        let mut edits = Vec::new();
1759        let mut new_excerpts = SumTree::new();
1760        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1761
1762        for (locator, buffer, buffer_edited) in excerpts_to_edit {
1763            new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1764            let old_excerpt = cursor.item().unwrap();
1765            let buffer = buffer.read(cx);
1766            let buffer_id = buffer.remote_id();
1767
1768            let mut new_excerpt;
1769            if buffer_edited {
1770                edits.extend(
1771                    buffer
1772                        .edits_since_in_range::<usize>(
1773                            old_excerpt.buffer.version(),
1774                            old_excerpt.range.context.clone(),
1775                        )
1776                        .map(|mut edit| {
1777                            let excerpt_old_start = cursor.start().1;
1778                            let excerpt_new_start = new_excerpts.summary().text.len;
1779                            edit.old.start += excerpt_old_start;
1780                            edit.old.end += excerpt_old_start;
1781                            edit.new.start += excerpt_new_start;
1782                            edit.new.end += excerpt_new_start;
1783                            edit
1784                        }),
1785                );
1786
1787                new_excerpt = Excerpt::new(
1788                    old_excerpt.id,
1789                    locator.clone(),
1790                    buffer_id,
1791                    buffer.snapshot(),
1792                    old_excerpt.range.clone(),
1793                    old_excerpt.has_trailing_newline,
1794                );
1795            } else {
1796                new_excerpt = old_excerpt.clone();
1797                new_excerpt.buffer = buffer.snapshot();
1798            }
1799
1800            new_excerpts.push(new_excerpt, &());
1801            cursor.next(&());
1802        }
1803        new_excerpts.append(cursor.suffix(&()), &());
1804
1805        drop(cursor);
1806        snapshot.excerpts = new_excerpts;
1807
1808        self.subscriptions.publish(edits);
1809    }
1810}
1811
1812#[cfg(any(test, feature = "test-support"))]
1813impl MultiBuffer {
1814    pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> Model<Self> {
1815        let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1816        cx.new_model(|cx| Self::singleton(buffer, cx))
1817    }
1818
1819    pub fn build_multi<const COUNT: usize>(
1820        excerpts: [(&str, Vec<Range<Point>>); COUNT],
1821        cx: &mut gpui::AppContext,
1822    ) -> Model<Self> {
1823        let multi = cx.new_model(|_| Self::new(0, Capability::ReadWrite));
1824        for (text, ranges) in excerpts {
1825            let buffer = cx.new_model(|cx| Buffer::local(text, cx));
1826            let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
1827                context: range,
1828                primary: None,
1829            });
1830            multi.update(cx, |multi, cx| {
1831                multi.push_excerpts(buffer, excerpt_ranges, cx)
1832            });
1833        }
1834
1835        multi
1836    }
1837
1838    pub fn build_from_buffer(buffer: Model<Buffer>, cx: &mut gpui::AppContext) -> Model<Self> {
1839        cx.new_model(|cx| Self::singleton(buffer, cx))
1840    }
1841
1842    pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> Model<Self> {
1843        cx.new_model(|cx| {
1844            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
1845            let mutation_count = rng.gen_range(1..=5);
1846            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1847            multibuffer
1848        })
1849    }
1850
1851    pub fn randomly_edit(
1852        &mut self,
1853        rng: &mut impl rand::Rng,
1854        edit_count: usize,
1855        cx: &mut ModelContext<Self>,
1856    ) {
1857        use util::RandomCharIter;
1858
1859        let snapshot = self.read(cx);
1860        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1861        let mut last_end = None;
1862        for _ in 0..edit_count {
1863            if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1864                break;
1865            }
1866
1867            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1868            let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1869            let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1870            last_end = Some(end);
1871
1872            let mut range = start..end;
1873            if rng.gen_bool(0.2) {
1874                mem::swap(&mut range.start, &mut range.end);
1875            }
1876
1877            let new_text_len = rng.gen_range(0..10);
1878            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1879
1880            edits.push((range, new_text.into()));
1881        }
1882        log::info!("mutating multi-buffer with {:?}", edits);
1883        drop(snapshot);
1884
1885        self.edit(edits, None, cx);
1886    }
1887
1888    pub fn randomly_edit_excerpts(
1889        &mut self,
1890        rng: &mut impl rand::Rng,
1891        mutation_count: usize,
1892        cx: &mut ModelContext<Self>,
1893    ) {
1894        use rand::prelude::*;
1895        use std::env;
1896        use util::RandomCharIter;
1897
1898        let max_excerpts = env::var("MAX_EXCERPTS")
1899            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1900            .unwrap_or(5);
1901
1902        let mut buffers = Vec::new();
1903        for _ in 0..mutation_count {
1904            if rng.gen_bool(0.05) {
1905                log::info!("Clearing multi-buffer");
1906                self.clear(cx);
1907                continue;
1908            } else if rng.gen_bool(0.1) && !self.excerpt_ids().is_empty() {
1909                let ids = self.excerpt_ids();
1910                let mut excerpts = HashSet::default();
1911                for _ in 0..rng.gen_range(0..ids.len()) {
1912                    excerpts.extend(ids.choose(rng).copied());
1913                }
1914
1915                let line_count = rng.gen_range(0..5);
1916
1917                log::info!("Expanding excerpts {excerpts:?} by {line_count} lines");
1918
1919                self.expand_excerpts(excerpts.iter().cloned(), line_count, cx);
1920                continue;
1921            }
1922
1923            let excerpt_ids = self.excerpt_ids();
1924            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1925                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1926                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1927                    buffers.push(cx.new_model(|cx| Buffer::local(text, cx)));
1928                    let buffer = buffers.last().unwrap().read(cx);
1929                    log::info!(
1930                        "Creating new buffer {} with text: {:?}",
1931                        buffer.remote_id(),
1932                        buffer.text()
1933                    );
1934                    buffers.last().unwrap().clone()
1935                } else {
1936                    self.buffers
1937                        .borrow()
1938                        .values()
1939                        .choose(rng)
1940                        .unwrap()
1941                        .buffer
1942                        .clone()
1943                };
1944
1945                let buffer = buffer_handle.read(cx);
1946                let buffer_text = buffer.text();
1947                let ranges = (0..rng.gen_range(0..5))
1948                    .map(|_| {
1949                        let end_ix =
1950                            buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1951                        let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1952                        ExcerptRange {
1953                            context: start_ix..end_ix,
1954                            primary: None,
1955                        }
1956                    })
1957                    .collect::<Vec<_>>();
1958                log::info!(
1959                    "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1960                    buffer_handle.read(cx).remote_id(),
1961                    ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1962                    ranges
1963                        .iter()
1964                        .map(|r| &buffer_text[r.context.clone()])
1965                        .collect::<Vec<_>>()
1966                );
1967
1968                let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1969                log::info!("Inserted with ids: {:?}", excerpt_id);
1970            } else {
1971                let remove_count = rng.gen_range(1..=excerpt_ids.len());
1972                let mut excerpts_to_remove = excerpt_ids
1973                    .choose_multiple(rng, remove_count)
1974                    .cloned()
1975                    .collect::<Vec<_>>();
1976                let snapshot = self.snapshot.borrow();
1977                excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
1978                drop(snapshot);
1979                log::info!("Removing excerpts {:?}", excerpts_to_remove);
1980                self.remove_excerpts(excerpts_to_remove, cx);
1981            }
1982        }
1983    }
1984
1985    pub fn randomly_mutate(
1986        &mut self,
1987        rng: &mut impl rand::Rng,
1988        mutation_count: usize,
1989        cx: &mut ModelContext<Self>,
1990    ) {
1991        use rand::prelude::*;
1992
1993        if rng.gen_bool(0.7) || self.singleton {
1994            let buffer = self
1995                .buffers
1996                .borrow()
1997                .values()
1998                .choose(rng)
1999                .map(|state| state.buffer.clone());
2000
2001            if let Some(buffer) = buffer {
2002                buffer.update(cx, |buffer, cx| {
2003                    if rng.gen() {
2004                        buffer.randomly_edit(rng, mutation_count, cx);
2005                    } else {
2006                        buffer.randomly_undo_redo(rng, cx);
2007                    }
2008                });
2009            } else {
2010                self.randomly_edit(rng, mutation_count, cx);
2011            }
2012        } else {
2013            self.randomly_edit_excerpts(rng, mutation_count, cx);
2014        }
2015
2016        self.check_invariants(cx);
2017    }
2018
2019    fn check_invariants(&self, cx: &mut ModelContext<Self>) {
2020        let snapshot = self.read(cx);
2021        let excerpts = snapshot.excerpts.items(&());
2022        let excerpt_ids = snapshot.excerpt_ids.items(&());
2023
2024        for (ix, excerpt) in excerpts.iter().enumerate() {
2025            if ix == 0 {
2026                if excerpt.locator <= Locator::min() {
2027                    panic!("invalid first excerpt locator {:?}", excerpt.locator);
2028                }
2029            } else {
2030                if excerpt.locator <= excerpts[ix - 1].locator {
2031                    panic!("excerpts are out-of-order: {:?}", excerpts);
2032                }
2033            }
2034        }
2035
2036        for (ix, entry) in excerpt_ids.iter().enumerate() {
2037            if ix == 0 {
2038                if entry.id.cmp(&ExcerptId::min(), &snapshot).is_le() {
2039                    panic!("invalid first excerpt id {:?}", entry.id);
2040                }
2041            } else {
2042                if entry.id <= excerpt_ids[ix - 1].id {
2043                    panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
2044                }
2045            }
2046        }
2047    }
2048}
2049
2050impl EventEmitter<Event> for MultiBuffer {}
2051
2052impl MultiBufferSnapshot {
2053    pub fn text(&self) -> String {
2054        self.chunks(0..self.len(), false)
2055            .map(|chunk| chunk.text)
2056            .collect()
2057    }
2058
2059    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
2060        let mut offset = position.to_offset(self);
2061        let mut cursor = self.excerpts.cursor::<usize>();
2062        cursor.seek(&offset, Bias::Left, &());
2063        let mut excerpt_chunks = cursor.item().map(|excerpt| {
2064            let end_before_footer = cursor.start() + excerpt.text_summary.len;
2065            let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2066            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
2067            excerpt.buffer.reversed_chunks_in_range(start..end)
2068        });
2069        iter::from_fn(move || {
2070            if offset == *cursor.start() {
2071                cursor.prev(&());
2072                let excerpt = cursor.item()?;
2073                excerpt_chunks = Some(
2074                    excerpt
2075                        .buffer
2076                        .reversed_chunks_in_range(excerpt.range.context.clone()),
2077                );
2078            }
2079
2080            let excerpt = cursor.item().unwrap();
2081            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
2082                offset -= 1;
2083                Some("\n")
2084            } else {
2085                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
2086                offset -= chunk.len();
2087                Some(chunk)
2088            }
2089        })
2090        .flat_map(|c| c.chars().rev())
2091    }
2092
2093    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
2094        let offset = position.to_offset(self);
2095        self.text_for_range(offset..self.len())
2096            .flat_map(|chunk| chunk.chars())
2097    }
2098
2099    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
2100        self.chunks(range, false).map(|chunk| chunk.text)
2101    }
2102
2103    pub fn is_line_blank(&self, row: u32) -> bool {
2104        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
2105            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
2106    }
2107
2108    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
2109    where
2110        T: ToOffset,
2111    {
2112        let position = position.to_offset(self);
2113        position == self.clip_offset(position, Bias::Left)
2114            && self
2115                .bytes_in_range(position..self.len())
2116                .flatten()
2117                .copied()
2118                .take(needle.len())
2119                .eq(needle.bytes())
2120    }
2121
2122    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2123        let mut start = start.to_offset(self);
2124        let mut end = start;
2125        let mut next_chars = self.chars_at(start).peekable();
2126        let mut prev_chars = self.reversed_chars_at(start).peekable();
2127
2128        let scope = self.language_scope_at(start);
2129        let kind = |c| char_kind(&scope, c);
2130        let word_kind = cmp::max(
2131            prev_chars.peek().copied().map(kind),
2132            next_chars.peek().copied().map(kind),
2133        );
2134
2135        for ch in prev_chars {
2136            if Some(kind(ch)) == word_kind && ch != '\n' {
2137                start -= ch.len_utf8();
2138            } else {
2139                break;
2140            }
2141        }
2142
2143        for ch in next_chars {
2144            if Some(kind(ch)) == word_kind && ch != '\n' {
2145                end += ch.len_utf8();
2146            } else {
2147                break;
2148            }
2149        }
2150
2151        (start..end, word_kind)
2152    }
2153
2154    pub fn as_singleton(&self) -> Option<(&ExcerptId, BufferId, &BufferSnapshot)> {
2155        if self.singleton {
2156            self.excerpts
2157                .iter()
2158                .next()
2159                .map(|e| (&e.id, e.buffer_id, &e.buffer))
2160        } else {
2161            None
2162        }
2163    }
2164
2165    pub fn len(&self) -> usize {
2166        self.excerpts.summary().text.len
2167    }
2168
2169    pub fn is_empty(&self) -> bool {
2170        self.excerpts.summary().text.len == 0
2171    }
2172
2173    pub fn max_buffer_row(&self) -> u32 {
2174        self.excerpts.summary().max_buffer_row
2175    }
2176
2177    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
2178        if let Some((_, _, buffer)) = self.as_singleton() {
2179            return buffer.clip_offset(offset, bias);
2180        }
2181
2182        let mut cursor = self.excerpts.cursor::<usize>();
2183        cursor.seek(&offset, Bias::Right, &());
2184        let overshoot = if let Some(excerpt) = cursor.item() {
2185            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2186            let buffer_offset = excerpt
2187                .buffer
2188                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
2189            buffer_offset.saturating_sub(excerpt_start)
2190        } else {
2191            0
2192        };
2193        cursor.start() + overshoot
2194    }
2195
2196    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
2197        if let Some((_, _, buffer)) = self.as_singleton() {
2198            return buffer.clip_point(point, bias);
2199        }
2200
2201        let mut cursor = self.excerpts.cursor::<Point>();
2202        cursor.seek(&point, Bias::Right, &());
2203        let overshoot = if let Some(excerpt) = cursor.item() {
2204            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2205            let buffer_point = excerpt
2206                .buffer
2207                .clip_point(excerpt_start + (point - cursor.start()), bias);
2208            buffer_point.saturating_sub(excerpt_start)
2209        } else {
2210            Point::zero()
2211        };
2212        *cursor.start() + overshoot
2213    }
2214
2215    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
2216        if let Some((_, _, buffer)) = self.as_singleton() {
2217            return buffer.clip_offset_utf16(offset, bias);
2218        }
2219
2220        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
2221        cursor.seek(&offset, Bias::Right, &());
2222        let overshoot = if let Some(excerpt) = cursor.item() {
2223            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2224            let buffer_offset = excerpt
2225                .buffer
2226                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
2227            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
2228        } else {
2229            OffsetUtf16(0)
2230        };
2231        *cursor.start() + overshoot
2232    }
2233
2234    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
2235        if let Some((_, _, buffer)) = self.as_singleton() {
2236            return buffer.clip_point_utf16(point, bias);
2237        }
2238
2239        let mut cursor = self.excerpts.cursor::<PointUtf16>();
2240        cursor.seek(&point.0, Bias::Right, &());
2241        let overshoot = if let Some(excerpt) = cursor.item() {
2242            let excerpt_start = excerpt
2243                .buffer
2244                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2245            let buffer_point = excerpt
2246                .buffer
2247                .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
2248            buffer_point.saturating_sub(excerpt_start)
2249        } else {
2250            PointUtf16::zero()
2251        };
2252        *cursor.start() + overshoot
2253    }
2254
2255    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
2256        let range = range.start.to_offset(self)..range.end.to_offset(self);
2257        let mut excerpts = self.excerpts.cursor::<usize>();
2258        excerpts.seek(&range.start, Bias::Right, &());
2259
2260        let mut chunk = &[][..];
2261        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2262            let mut excerpt_bytes = excerpt
2263                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
2264            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2265            Some(excerpt_bytes)
2266        } else {
2267            None
2268        };
2269        MultiBufferBytes {
2270            range,
2271            excerpts,
2272            excerpt_bytes,
2273            chunk,
2274        }
2275    }
2276
2277    pub fn reversed_bytes_in_range<T: ToOffset>(
2278        &self,
2279        range: Range<T>,
2280    ) -> ReversedMultiBufferBytes {
2281        let range = range.start.to_offset(self)..range.end.to_offset(self);
2282        let mut excerpts = self.excerpts.cursor::<usize>();
2283        excerpts.seek(&range.end, Bias::Left, &());
2284
2285        let mut chunk = &[][..];
2286        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2287            let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
2288                range.start.saturating_sub(*excerpts.start())..range.end - *excerpts.start(),
2289            );
2290            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2291            Some(excerpt_bytes)
2292        } else {
2293            None
2294        };
2295
2296        ReversedMultiBufferBytes {
2297            range,
2298            excerpts,
2299            excerpt_bytes,
2300            chunk,
2301        }
2302    }
2303
2304    pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
2305        let mut result = MultiBufferRows {
2306            buffer_row_range: 0..0,
2307            excerpts: self.excerpts.cursor(),
2308        };
2309        result.seek(start_row);
2310        result
2311    }
2312
2313    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
2314        let range = range.start.to_offset(self)..range.end.to_offset(self);
2315        let mut chunks = MultiBufferChunks {
2316            range: range.clone(),
2317            excerpts: self.excerpts.cursor(),
2318            excerpt_chunks: None,
2319            language_aware,
2320        };
2321        chunks.seek(range.start);
2322        chunks
2323    }
2324
2325    pub fn offset_to_point(&self, offset: usize) -> Point {
2326        if let Some((_, _, buffer)) = self.as_singleton() {
2327            return buffer.offset_to_point(offset);
2328        }
2329
2330        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2331        cursor.seek(&offset, Bias::Right, &());
2332        if let Some(excerpt) = cursor.item() {
2333            let (start_offset, start_point) = cursor.start();
2334            let overshoot = offset - start_offset;
2335            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2336            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2337            let buffer_point = excerpt
2338                .buffer
2339                .offset_to_point(excerpt_start_offset + overshoot);
2340            *start_point + (buffer_point - excerpt_start_point)
2341        } else {
2342            self.excerpts.summary().text.lines
2343        }
2344    }
2345
2346    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
2347        if let Some((_, _, buffer)) = self.as_singleton() {
2348            return buffer.offset_to_point_utf16(offset);
2349        }
2350
2351        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
2352        cursor.seek(&offset, Bias::Right, &());
2353        if let Some(excerpt) = cursor.item() {
2354            let (start_offset, start_point) = cursor.start();
2355            let overshoot = offset - start_offset;
2356            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2357            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2358            let buffer_point = excerpt
2359                .buffer
2360                .offset_to_point_utf16(excerpt_start_offset + overshoot);
2361            *start_point + (buffer_point - excerpt_start_point)
2362        } else {
2363            self.excerpts.summary().text.lines_utf16()
2364        }
2365    }
2366
2367    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
2368        if let Some((_, _, buffer)) = self.as_singleton() {
2369            return buffer.point_to_point_utf16(point);
2370        }
2371
2372        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
2373        cursor.seek(&point, Bias::Right, &());
2374        if let Some(excerpt) = cursor.item() {
2375            let (start_offset, start_point) = cursor.start();
2376            let overshoot = point - start_offset;
2377            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2378            let excerpt_start_point_utf16 =
2379                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2380            let buffer_point = excerpt
2381                .buffer
2382                .point_to_point_utf16(excerpt_start_point + overshoot);
2383            *start_point + (buffer_point - excerpt_start_point_utf16)
2384        } else {
2385            self.excerpts.summary().text.lines_utf16()
2386        }
2387    }
2388
2389    pub fn point_to_offset(&self, point: Point) -> usize {
2390        if let Some((_, _, buffer)) = self.as_singleton() {
2391            return buffer.point_to_offset(point);
2392        }
2393
2394        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2395        cursor.seek(&point, Bias::Right, &());
2396        if let Some(excerpt) = cursor.item() {
2397            let (start_point, start_offset) = cursor.start();
2398            let overshoot = point - start_point;
2399            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2400            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2401            let buffer_offset = excerpt
2402                .buffer
2403                .point_to_offset(excerpt_start_point + overshoot);
2404            *start_offset + buffer_offset - excerpt_start_offset
2405        } else {
2406            self.excerpts.summary().text.len
2407        }
2408    }
2409
2410    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2411        if let Some((_, _, buffer)) = self.as_singleton() {
2412            return buffer.offset_utf16_to_offset(offset_utf16);
2413        }
2414
2415        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2416        cursor.seek(&offset_utf16, Bias::Right, &());
2417        if let Some(excerpt) = cursor.item() {
2418            let (start_offset_utf16, start_offset) = cursor.start();
2419            let overshoot = offset_utf16 - start_offset_utf16;
2420            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2421            let excerpt_start_offset_utf16 =
2422                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2423            let buffer_offset = excerpt
2424                .buffer
2425                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2426            *start_offset + (buffer_offset - excerpt_start_offset)
2427        } else {
2428            self.excerpts.summary().text.len
2429        }
2430    }
2431
2432    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2433        if let Some((_, _, buffer)) = self.as_singleton() {
2434            return buffer.offset_to_offset_utf16(offset);
2435        }
2436
2437        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2438        cursor.seek(&offset, Bias::Right, &());
2439        if let Some(excerpt) = cursor.item() {
2440            let (start_offset, start_offset_utf16) = cursor.start();
2441            let overshoot = offset - start_offset;
2442            let excerpt_start_offset_utf16 =
2443                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2444            let excerpt_start_offset = excerpt
2445                .buffer
2446                .offset_utf16_to_offset(excerpt_start_offset_utf16);
2447            let buffer_offset_utf16 = excerpt
2448                .buffer
2449                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2450            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2451        } else {
2452            self.excerpts.summary().text.len_utf16
2453        }
2454    }
2455
2456    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2457        if let Some((_, _, buffer)) = self.as_singleton() {
2458            return buffer.point_utf16_to_offset(point);
2459        }
2460
2461        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2462        cursor.seek(&point, Bias::Right, &());
2463        if let Some(excerpt) = cursor.item() {
2464            let (start_point, start_offset) = cursor.start();
2465            let overshoot = point - start_point;
2466            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2467            let excerpt_start_point = excerpt
2468                .buffer
2469                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2470            let buffer_offset = excerpt
2471                .buffer
2472                .point_utf16_to_offset(excerpt_start_point + overshoot);
2473            *start_offset + (buffer_offset - excerpt_start_offset)
2474        } else {
2475            self.excerpts.summary().text.len
2476        }
2477    }
2478
2479    pub fn point_to_buffer_offset<T: ToOffset>(
2480        &self,
2481        point: T,
2482    ) -> Option<(&BufferSnapshot, usize)> {
2483        let offset = point.to_offset(self);
2484        let mut cursor = self.excerpts.cursor::<usize>();
2485        cursor.seek(&offset, Bias::Right, &());
2486        if cursor.item().is_none() {
2487            cursor.prev(&());
2488        }
2489
2490        cursor.item().map(|excerpt| {
2491            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2492            let buffer_point = excerpt_start + offset - *cursor.start();
2493            (&excerpt.buffer, buffer_point)
2494        })
2495    }
2496
2497    pub fn suggested_indents(
2498        &self,
2499        rows: impl IntoIterator<Item = u32>,
2500        cx: &AppContext,
2501    ) -> BTreeMap<u32, IndentSize> {
2502        let mut result = BTreeMap::new();
2503
2504        let mut rows_for_excerpt = Vec::new();
2505        let mut cursor = self.excerpts.cursor::<Point>();
2506        let mut rows = rows.into_iter().peekable();
2507        let mut prev_row = u32::MAX;
2508        let mut prev_language_indent_size = IndentSize::default();
2509
2510        while let Some(row) = rows.next() {
2511            cursor.seek(&Point::new(row, 0), Bias::Right, &());
2512            let excerpt = match cursor.item() {
2513                Some(excerpt) => excerpt,
2514                _ => continue,
2515            };
2516
2517            // Retrieve the language and indent size once for each disjoint region being indented.
2518            let single_indent_size = if row.saturating_sub(1) == prev_row {
2519                prev_language_indent_size
2520            } else {
2521                excerpt
2522                    .buffer
2523                    .language_indent_size_at(Point::new(row, 0), cx)
2524            };
2525            prev_language_indent_size = single_indent_size;
2526            prev_row = row;
2527
2528            let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2529            let start_multibuffer_row = cursor.start().row;
2530
2531            rows_for_excerpt.push(row);
2532            while let Some(next_row) = rows.peek().copied() {
2533                if cursor.end(&()).row > next_row {
2534                    rows_for_excerpt.push(next_row);
2535                    rows.next();
2536                } else {
2537                    break;
2538                }
2539            }
2540
2541            let buffer_rows = rows_for_excerpt
2542                .drain(..)
2543                .map(|row| start_buffer_row + row - start_multibuffer_row);
2544            let buffer_indents = excerpt
2545                .buffer
2546                .suggested_indents(buffer_rows, single_indent_size);
2547            let multibuffer_indents = buffer_indents
2548                .into_iter()
2549                .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2550            result.extend(multibuffer_indents);
2551        }
2552
2553        result
2554    }
2555
2556    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2557        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2558            let mut size = buffer.indent_size_for_line(range.start.row);
2559            size.len = size
2560                .len
2561                .min(range.end.column)
2562                .saturating_sub(range.start.column);
2563            size
2564        } else {
2565            IndentSize::spaces(0)
2566        }
2567    }
2568
2569    pub fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2570        while row > 0 {
2571            row -= 1;
2572            if !self.is_line_blank(row) {
2573                return Some(row);
2574            }
2575        }
2576        None
2577    }
2578
2579    pub fn line_len(&self, row: u32) -> u32 {
2580        if let Some((_, range)) = self.buffer_line_for_row(row) {
2581            range.end.column - range.start.column
2582        } else {
2583            0
2584        }
2585    }
2586
2587    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2588        let mut cursor = self.excerpts.cursor::<Point>();
2589        let point = Point::new(row, 0);
2590        cursor.seek(&point, Bias::Right, &());
2591        if cursor.item().is_none() && *cursor.start() == point {
2592            cursor.prev(&());
2593        }
2594        if let Some(excerpt) = cursor.item() {
2595            let overshoot = row - cursor.start().row;
2596            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2597            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2598            let buffer_row = excerpt_start.row + overshoot;
2599            let line_start = Point::new(buffer_row, 0);
2600            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2601            return Some((
2602                &excerpt.buffer,
2603                line_start.max(excerpt_start)..line_end.min(excerpt_end),
2604            ));
2605        }
2606        None
2607    }
2608
2609    pub fn max_point(&self) -> Point {
2610        self.text_summary().lines
2611    }
2612
2613    pub fn text_summary(&self) -> TextSummary {
2614        self.excerpts.summary().text.clone()
2615    }
2616
2617    pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2618    where
2619        D: TextDimension,
2620        O: ToOffset,
2621    {
2622        let mut summary = D::default();
2623        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2624        let mut cursor = self.excerpts.cursor::<usize>();
2625        cursor.seek(&range.start, Bias::Right, &());
2626        if let Some(excerpt) = cursor.item() {
2627            let mut end_before_newline = cursor.end(&());
2628            if excerpt.has_trailing_newline {
2629                end_before_newline -= 1;
2630            }
2631
2632            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2633            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2634            let end_in_excerpt =
2635                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2636            summary.add_assign(
2637                &excerpt
2638                    .buffer
2639                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2640            );
2641
2642            if range.end > end_before_newline {
2643                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2644            }
2645
2646            cursor.next(&());
2647        }
2648
2649        if range.end > *cursor.start() {
2650            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2651                &range.end,
2652                Bias::Right,
2653                &(),
2654            )));
2655            if let Some(excerpt) = cursor.item() {
2656                range.end = cmp::max(*cursor.start(), range.end);
2657
2658                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2659                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2660                summary.add_assign(
2661                    &excerpt
2662                        .buffer
2663                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2664                );
2665            }
2666        }
2667
2668        summary
2669    }
2670
2671    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2672    where
2673        D: TextDimension + Ord + Sub<D, Output = D>,
2674    {
2675        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2676        let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2677
2678        cursor.seek(locator, Bias::Left, &());
2679        if cursor.item().is_none() {
2680            cursor.next(&());
2681        }
2682
2683        let mut position = D::from_text_summary(&cursor.start().text);
2684        if let Some(excerpt) = cursor.item() {
2685            if excerpt.id == anchor.excerpt_id {
2686                let excerpt_buffer_start =
2687                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2688                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2689                let buffer_position = cmp::min(
2690                    excerpt_buffer_end,
2691                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2692                );
2693                if buffer_position > excerpt_buffer_start {
2694                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2695                }
2696            }
2697        }
2698        position
2699    }
2700
2701    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2702    where
2703        D: TextDimension + Ord + Sub<D, Output = D>,
2704        I: 'a + IntoIterator<Item = &'a Anchor>,
2705    {
2706        if let Some((_, _, buffer)) = self.as_singleton() {
2707            return buffer
2708                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2709                .collect();
2710        }
2711
2712        let mut anchors = anchors.into_iter().peekable();
2713        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2714        let mut summaries = Vec::new();
2715        while let Some(anchor) = anchors.peek() {
2716            let excerpt_id = anchor.excerpt_id;
2717            let excerpt_anchors = iter::from_fn(|| {
2718                let anchor = anchors.peek()?;
2719                if anchor.excerpt_id == excerpt_id {
2720                    Some(&anchors.next().unwrap().text_anchor)
2721                } else {
2722                    None
2723                }
2724            });
2725
2726            let locator = self.excerpt_locator_for_id(excerpt_id);
2727            cursor.seek_forward(locator, Bias::Left, &());
2728            if cursor.item().is_none() {
2729                cursor.next(&());
2730            }
2731
2732            let position = D::from_text_summary(&cursor.start().text);
2733            if let Some(excerpt) = cursor.item() {
2734                if excerpt.id == excerpt_id {
2735                    let excerpt_buffer_start =
2736                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2737                    let excerpt_buffer_end =
2738                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2739                    summaries.extend(
2740                        excerpt
2741                            .buffer
2742                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2743                            .map(move |summary| {
2744                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2745                                let mut position = position.clone();
2746                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2747                                if summary > excerpt_buffer_start {
2748                                    position.add_assign(&(summary - excerpt_buffer_start));
2749                                }
2750                                position
2751                            }),
2752                    );
2753                    continue;
2754                }
2755            }
2756
2757            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2758        }
2759
2760        summaries
2761    }
2762
2763    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2764    where
2765        I: 'a + IntoIterator<Item = &'a Anchor>,
2766    {
2767        let mut anchors = anchors.into_iter().enumerate().peekable();
2768        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2769        cursor.next(&());
2770
2771        let mut result = Vec::new();
2772
2773        while let Some((_, anchor)) = anchors.peek() {
2774            let old_excerpt_id = anchor.excerpt_id;
2775
2776            // Find the location where this anchor's excerpt should be.
2777            let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2778            cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2779
2780            if cursor.item().is_none() {
2781                cursor.next(&());
2782            }
2783
2784            let next_excerpt = cursor.item();
2785            let prev_excerpt = cursor.prev_item();
2786
2787            // Process all of the anchors for this excerpt.
2788            while let Some((_, anchor)) = anchors.peek() {
2789                if anchor.excerpt_id != old_excerpt_id {
2790                    break;
2791                }
2792                let (anchor_ix, anchor) = anchors.next().unwrap();
2793                let mut anchor = *anchor;
2794
2795                // Leave min and max anchors unchanged if invalid or
2796                // if the old excerpt still exists at this location
2797                let mut kept_position = next_excerpt
2798                    .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2799                    || old_excerpt_id == ExcerptId::max()
2800                    || old_excerpt_id == ExcerptId::min();
2801
2802                // If the old excerpt no longer exists at this location, then attempt to
2803                // find an equivalent position for this anchor in an adjacent excerpt.
2804                if !kept_position {
2805                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2806                        if excerpt.contains(&anchor) {
2807                            anchor.excerpt_id = excerpt.id;
2808                            kept_position = true;
2809                            break;
2810                        }
2811                    }
2812                }
2813
2814                // If there's no adjacent excerpt that contains the anchor's position,
2815                // then report that the anchor has lost its position.
2816                if !kept_position {
2817                    anchor = if let Some(excerpt) = next_excerpt {
2818                        let mut text_anchor = excerpt
2819                            .range
2820                            .context
2821                            .start
2822                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2823                        if text_anchor
2824                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2825                            .is_gt()
2826                        {
2827                            text_anchor = excerpt.range.context.end;
2828                        }
2829                        Anchor {
2830                            buffer_id: Some(excerpt.buffer_id),
2831                            excerpt_id: excerpt.id,
2832                            text_anchor,
2833                        }
2834                    } else if let Some(excerpt) = prev_excerpt {
2835                        let mut text_anchor = excerpt
2836                            .range
2837                            .context
2838                            .end
2839                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2840                        if text_anchor
2841                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2842                            .is_lt()
2843                        {
2844                            text_anchor = excerpt.range.context.start;
2845                        }
2846                        Anchor {
2847                            buffer_id: Some(excerpt.buffer_id),
2848                            excerpt_id: excerpt.id,
2849                            text_anchor,
2850                        }
2851                    } else if anchor.text_anchor.bias == Bias::Left {
2852                        Anchor::min()
2853                    } else {
2854                        Anchor::max()
2855                    };
2856                }
2857
2858                result.push((anchor_ix, anchor, kept_position));
2859            }
2860        }
2861        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2862        result
2863    }
2864
2865    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2866        self.anchor_at(position, Bias::Left)
2867    }
2868
2869    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2870        self.anchor_at(position, Bias::Right)
2871    }
2872
2873    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2874        let offset = position.to_offset(self);
2875        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2876            return Anchor {
2877                buffer_id: Some(buffer_id),
2878                excerpt_id: *excerpt_id,
2879                text_anchor: buffer.anchor_at(offset, bias),
2880            };
2881        }
2882
2883        let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2884        cursor.seek(&offset, Bias::Right, &());
2885        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2886            cursor.prev(&());
2887        }
2888        if let Some(excerpt) = cursor.item() {
2889            let mut overshoot = offset.saturating_sub(cursor.start().0);
2890            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2891                overshoot -= 1;
2892                bias = Bias::Right;
2893            }
2894
2895            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2896            let text_anchor =
2897                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2898            Anchor {
2899                buffer_id: Some(excerpt.buffer_id),
2900                excerpt_id: excerpt.id,
2901                text_anchor,
2902            }
2903        } else if offset == 0 && bias == Bias::Left {
2904            Anchor::min()
2905        } else {
2906            Anchor::max()
2907        }
2908    }
2909
2910    /// Returns an anchor for the given excerpt and text anchor,
2911    /// returns None if the excerpt_id is no longer valid.
2912    pub fn anchor_in_excerpt(
2913        &self,
2914        excerpt_id: ExcerptId,
2915        text_anchor: text::Anchor,
2916    ) -> Option<Anchor> {
2917        let locator = self.excerpt_locator_for_id(excerpt_id);
2918        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2919        cursor.seek(locator, Bias::Left, &());
2920        if let Some(excerpt) = cursor.item() {
2921            if excerpt.id == excerpt_id {
2922                let text_anchor = excerpt.clip_anchor(text_anchor);
2923                drop(cursor);
2924                return Some(Anchor {
2925                    buffer_id: Some(excerpt.buffer_id),
2926                    excerpt_id,
2927                    text_anchor,
2928                });
2929            }
2930        }
2931        None
2932    }
2933
2934    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2935        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2936            true
2937        } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2938            excerpt.buffer.can_resolve(&anchor.text_anchor)
2939        } else {
2940            false
2941        }
2942    }
2943
2944    pub fn excerpts(
2945        &self,
2946    ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2947        self.excerpts
2948            .iter()
2949            .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2950    }
2951
2952    fn excerpts_for_range<T: ToOffset>(
2953        &self,
2954        range: Range<T>,
2955    ) -> impl Iterator<Item = (&Excerpt, usize)> + '_ {
2956        let range = range.start.to_offset(self)..range.end.to_offset(self);
2957
2958        let mut cursor = self.excerpts.cursor::<usize>();
2959        cursor.seek(&range.start, Bias::Right, &());
2960        cursor.prev(&());
2961
2962        iter::from_fn(move || {
2963            cursor.next(&());
2964            if cursor.start() < &range.end {
2965                cursor.item().map(|item| (item, *cursor.start()))
2966            } else {
2967                None
2968            }
2969        })
2970    }
2971
2972    pub fn excerpt_boundaries_in_range<R, T>(
2973        &self,
2974        range: R,
2975    ) -> impl Iterator<Item = ExcerptBoundary> + '_
2976    where
2977        R: RangeBounds<T>,
2978        T: ToOffset,
2979    {
2980        let start_offset;
2981        let start = match range.start_bound() {
2982            Bound::Included(start) => {
2983                start_offset = start.to_offset(self);
2984                Bound::Included(start_offset)
2985            }
2986            Bound::Excluded(start) => {
2987                start_offset = start.to_offset(self);
2988                Bound::Excluded(start_offset)
2989            }
2990            Bound::Unbounded => {
2991                start_offset = 0;
2992                Bound::Unbounded
2993            }
2994        };
2995        let end = match range.end_bound() {
2996            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2997            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2998            Bound::Unbounded => Bound::Unbounded,
2999        };
3000        let bounds = (start, end);
3001
3002        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
3003        cursor.seek(&start_offset, Bias::Right, &());
3004        if cursor.item().is_none() {
3005            cursor.prev(&());
3006        }
3007        if !bounds.contains(&cursor.start().0) {
3008            cursor.next(&());
3009        }
3010
3011        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
3012        std::iter::from_fn(move || {
3013            if self.singleton {
3014                None
3015            } else if bounds.contains(&cursor.start().0) {
3016                let excerpt = cursor.item()?;
3017                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
3018                let boundary = ExcerptBoundary {
3019                    id: excerpt.id,
3020                    row: cursor.start().1.row,
3021                    buffer: excerpt.buffer.clone(),
3022                    range: excerpt.range.clone(),
3023                    starts_new_buffer,
3024                };
3025
3026                prev_buffer_id = Some(excerpt.buffer_id);
3027                cursor.next(&());
3028                Some(boundary)
3029            } else {
3030                None
3031            }
3032        })
3033    }
3034
3035    pub fn edit_count(&self) -> usize {
3036        self.edit_count
3037    }
3038
3039    pub fn parse_count(&self) -> usize {
3040        self.parse_count
3041    }
3042
3043    /// Returns the smallest enclosing bracket ranges containing the given range or
3044    /// None if no brackets contain range or the range is not contained in a single
3045    /// excerpt
3046    ///
3047    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
3048    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
3049        &self,
3050        range: Range<T>,
3051        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
3052    ) -> Option<(Range<usize>, Range<usize>)> {
3053        let range = range.start.to_offset(self)..range.end.to_offset(self);
3054        let excerpt = self.excerpt_containing(range.clone())?;
3055
3056        // Filter to ranges contained in the excerpt
3057        let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
3058            excerpt.contains_buffer_range(open.start..close.end)
3059                && range_filter.map_or(true, |filter| {
3060                    filter(
3061                        excerpt.map_range_from_buffer(open),
3062                        excerpt.map_range_from_buffer(close),
3063                    )
3064                })
3065        };
3066
3067        let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
3068            excerpt.map_range_to_buffer(range),
3069            Some(&range_filter),
3070        )?;
3071
3072        Some((
3073            excerpt.map_range_from_buffer(open),
3074            excerpt.map_range_from_buffer(close),
3075        ))
3076    }
3077
3078    /// Returns enclosing bracket ranges containing the given range or returns None if the range is
3079    /// not contained in a single excerpt
3080    pub fn enclosing_bracket_ranges<T: ToOffset>(
3081        &self,
3082        range: Range<T>,
3083    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3084        let range = range.start.to_offset(self)..range.end.to_offset(self);
3085        let excerpt = self.excerpt_containing(range.clone())?;
3086
3087        Some(
3088            excerpt
3089                .buffer()
3090                .enclosing_bracket_ranges(excerpt.map_range_to_buffer(range))
3091                .filter_map(move |(open, close)| {
3092                    if excerpt.contains_buffer_range(open.start..close.end) {
3093                        Some((
3094                            excerpt.map_range_from_buffer(open),
3095                            excerpt.map_range_from_buffer(close),
3096                        ))
3097                    } else {
3098                        None
3099                    }
3100                }),
3101        )
3102    }
3103
3104    /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
3105    /// not contained in a single excerpt
3106    pub fn bracket_ranges<T: ToOffset>(
3107        &self,
3108        range: Range<T>,
3109    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
3110        let range = range.start.to_offset(self)..range.end.to_offset(self);
3111        let excerpt = self.excerpt_containing(range.clone())?;
3112
3113        Some(
3114            excerpt
3115                .buffer()
3116                .bracket_ranges(excerpt.map_range_to_buffer(range))
3117                .filter_map(move |(start_bracket_range, close_bracket_range)| {
3118                    let buffer_range = start_bracket_range.start..close_bracket_range.end;
3119                    if excerpt.contains_buffer_range(buffer_range) {
3120                        Some((
3121                            excerpt.map_range_from_buffer(start_bracket_range),
3122                            excerpt.map_range_from_buffer(close_bracket_range),
3123                        ))
3124                    } else {
3125                        None
3126                    }
3127                }),
3128        )
3129    }
3130
3131    pub fn redacted_ranges<'a, T: ToOffset>(
3132        &'a self,
3133        range: Range<T>,
3134        redaction_enabled: impl Fn(Option<&Arc<dyn File>>) -> bool + 'a,
3135    ) -> impl Iterator<Item = Range<usize>> + 'a {
3136        let range = range.start.to_offset(self)..range.end.to_offset(self);
3137        self.excerpts_for_range(range.clone())
3138            .filter_map(move |(excerpt, excerpt_offset)| {
3139                redaction_enabled(excerpt.buffer.file()).then(move || {
3140                    let excerpt_buffer_start =
3141                        excerpt.range.context.start.to_offset(&excerpt.buffer);
3142
3143                    excerpt
3144                        .buffer
3145                        .redacted_ranges(excerpt.range.context.clone())
3146                        .map(move |mut redacted_range| {
3147                            // Re-base onto the excerpts coordinates in the multibuffer
3148                            redacted_range.start =
3149                                excerpt_offset + (redacted_range.start - excerpt_buffer_start);
3150                            redacted_range.end =
3151                                excerpt_offset + (redacted_range.end - excerpt_buffer_start);
3152
3153                            redacted_range
3154                        })
3155                        .skip_while(move |redacted_range| redacted_range.end < range.start)
3156                        .take_while(move |redacted_range| redacted_range.start < range.end)
3157                })
3158            })
3159            .flatten()
3160    }
3161
3162    pub fn diagnostics_update_count(&self) -> usize {
3163        self.diagnostics_update_count
3164    }
3165
3166    pub fn git_diff_update_count(&self) -> usize {
3167        self.git_diff_update_count
3168    }
3169
3170    pub fn trailing_excerpt_update_count(&self) -> usize {
3171        self.trailing_excerpt_update_count
3172    }
3173
3174    pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
3175        self.point_to_buffer_offset(point)
3176            .and_then(|(buffer, _)| buffer.file())
3177    }
3178
3179    pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
3180        self.point_to_buffer_offset(point)
3181            .and_then(|(buffer, offset)| buffer.language_at(offset))
3182    }
3183
3184    pub fn settings_at<'a, T: ToOffset>(
3185        &'a self,
3186        point: T,
3187        cx: &'a AppContext,
3188    ) -> &'a LanguageSettings {
3189        let mut language = None;
3190        let mut file = None;
3191        if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
3192            language = buffer.language_at(offset);
3193            file = buffer.file();
3194        }
3195        language_settings(language, file, cx)
3196    }
3197
3198    pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
3199        self.point_to_buffer_offset(point)
3200            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
3201    }
3202
3203    pub fn language_indent_size_at<T: ToOffset>(
3204        &self,
3205        position: T,
3206        cx: &AppContext,
3207    ) -> Option<IndentSize> {
3208        let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
3209        Some(buffer_snapshot.language_indent_size_at(offset, cx))
3210    }
3211
3212    pub fn is_dirty(&self) -> bool {
3213        self.is_dirty
3214    }
3215
3216    pub fn has_conflict(&self) -> bool {
3217        self.has_conflict
3218    }
3219
3220    pub fn has_diagnostics(&self) -> bool {
3221        self.excerpts
3222            .iter()
3223            .any(|excerpt| excerpt.buffer.has_diagnostics())
3224    }
3225
3226    pub fn diagnostic_group<'a, O>(
3227        &'a self,
3228        group_id: usize,
3229    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3230    where
3231        O: text::FromAnchor + 'a,
3232    {
3233        self.as_singleton()
3234            .into_iter()
3235            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
3236    }
3237
3238    pub fn diagnostics_in_range<'a, T, O>(
3239        &'a self,
3240        range: Range<T>,
3241        reversed: bool,
3242    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3243    where
3244        T: 'a + ToOffset,
3245        O: 'a + text::FromAnchor + Ord,
3246    {
3247        self.as_singleton()
3248            .into_iter()
3249            .flat_map(move |(_, _, buffer)| {
3250                buffer.diagnostics_in_range(
3251                    range.start.to_offset(self)..range.end.to_offset(self),
3252                    reversed,
3253                )
3254            })
3255    }
3256
3257    pub fn has_git_diffs(&self) -> bool {
3258        for excerpt in self.excerpts.iter() {
3259            if excerpt.buffer.has_git_diff() {
3260                return true;
3261            }
3262        }
3263        false
3264    }
3265
3266    pub fn git_diff_hunks_in_range_rev(
3267        &self,
3268        row_range: Range<u32>,
3269    ) -> impl Iterator<Item = DiffHunk<u32>> + '_ {
3270        let mut cursor = self.excerpts.cursor::<Point>();
3271
3272        cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
3273        if cursor.item().is_none() {
3274            cursor.prev(&());
3275        }
3276
3277        std::iter::from_fn(move || {
3278            let excerpt = cursor.item()?;
3279            let multibuffer_start = *cursor.start();
3280            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3281            if multibuffer_start.row >= row_range.end {
3282                return None;
3283            }
3284
3285            let mut buffer_start = excerpt.range.context.start;
3286            let mut buffer_end = excerpt.range.context.end;
3287            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3288            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3289
3290            if row_range.start > multibuffer_start.row {
3291                let buffer_start_point =
3292                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3293                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3294            }
3295
3296            if row_range.end < multibuffer_end.row {
3297                let buffer_end_point =
3298                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3299                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3300            }
3301
3302            let buffer_hunks = excerpt
3303                .buffer
3304                .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
3305                .map(move |hunk| {
3306                    let start = multibuffer_start.row
3307                        + hunk
3308                            .associated_range
3309                            .start
3310                            .saturating_sub(excerpt_start_point.row);
3311                    let end = multibuffer_start.row
3312                        + hunk
3313                            .associated_range
3314                            .end
3315                            .min(excerpt_end_point.row + 1)
3316                            .saturating_sub(excerpt_start_point.row);
3317
3318                    DiffHunk {
3319                        associated_range: start..end,
3320                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3321                        buffer_range: hunk.buffer_range.clone(),
3322                        buffer_id: hunk.buffer_id,
3323                    }
3324                });
3325
3326            cursor.prev(&());
3327
3328            Some(buffer_hunks)
3329        })
3330        .flatten()
3331    }
3332
3333    pub fn git_diff_hunks_in_range(
3334        &self,
3335        row_range: Range<u32>,
3336    ) -> impl Iterator<Item = DiffHunk<u32>> + '_ {
3337        let mut cursor = self.excerpts.cursor::<Point>();
3338
3339        cursor.seek(&Point::new(row_range.start, 0), Bias::Left, &());
3340
3341        std::iter::from_fn(move || {
3342            let excerpt = cursor.item()?;
3343            let multibuffer_start = *cursor.start();
3344            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3345            let mut buffer_start = excerpt.range.context.start;
3346            let mut buffer_end = excerpt.range.context.end;
3347
3348            let excerpt_rows = match multibuffer_start.row.cmp(&row_range.end) {
3349                cmp::Ordering::Less => {
3350                    let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3351                    let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3352
3353                    if row_range.start > multibuffer_start.row {
3354                        let buffer_start_point = excerpt_start_point
3355                            + Point::new(row_range.start - multibuffer_start.row, 0);
3356                        buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3357                    }
3358
3359                    if row_range.end < multibuffer_end.row {
3360                        let buffer_end_point = excerpt_start_point
3361                            + Point::new(row_range.end - multibuffer_start.row, 0);
3362                        buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3363                    }
3364                    excerpt_start_point.row..excerpt_end_point.row
3365                }
3366                cmp::Ordering::Equal if row_range.end == 0 => {
3367                    buffer_end = buffer_start;
3368                    0..0
3369                }
3370                cmp::Ordering::Greater | cmp::Ordering::Equal => return None,
3371            };
3372
3373            let buffer_hunks = excerpt
3374                .buffer
3375                .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3376                .map(move |hunk| {
3377                    let buffer_range = if excerpt_rows.start == 0 && excerpt_rows.end == 0 {
3378                        0..1
3379                    } else {
3380                        let start = multibuffer_start.row
3381                            + hunk
3382                                .associated_range
3383                                .start
3384                                .saturating_sub(excerpt_rows.start);
3385                        let end = multibuffer_start.row
3386                            + hunk
3387                                .associated_range
3388                                .end
3389                                .min(excerpt_rows.end + 1)
3390                                .saturating_sub(excerpt_rows.start);
3391                        start..end
3392                    };
3393                    DiffHunk {
3394                        associated_range: buffer_range,
3395                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3396                        buffer_range: hunk.buffer_range.clone(),
3397                        buffer_id: hunk.buffer_id,
3398                    }
3399                });
3400
3401            cursor.next(&());
3402
3403            Some(buffer_hunks)
3404        })
3405        .flatten()
3406    }
3407
3408    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3409        let range = range.start.to_offset(self)..range.end.to_offset(self);
3410        let excerpt = self.excerpt_containing(range.clone())?;
3411
3412        let ancestor_buffer_range = excerpt
3413            .buffer()
3414            .range_for_syntax_ancestor(excerpt.map_range_to_buffer(range))?;
3415
3416        Some(excerpt.map_range_from_buffer(ancestor_buffer_range))
3417    }
3418
3419    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3420        let (excerpt_id, _, buffer) = self.as_singleton()?;
3421        let outline = buffer.outline(theme)?;
3422        Some(Outline::new(
3423            outline
3424                .items
3425                .into_iter()
3426                .flat_map(|item| {
3427                    Some(OutlineItem {
3428                        depth: item.depth,
3429                        range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
3430                            ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
3431                        text: item.text,
3432                        highlight_ranges: item.highlight_ranges,
3433                        name_ranges: item.name_ranges,
3434                    })
3435                })
3436                .collect(),
3437        ))
3438    }
3439
3440    pub fn symbols_containing<T: ToOffset>(
3441        &self,
3442        offset: T,
3443        theme: Option<&SyntaxTheme>,
3444    ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3445        let anchor = self.anchor_before(offset);
3446        let excerpt_id = anchor.excerpt_id;
3447        let excerpt = self.excerpt(excerpt_id)?;
3448        Some((
3449            excerpt.buffer_id,
3450            excerpt
3451                .buffer
3452                .symbols_containing(anchor.text_anchor, theme)
3453                .into_iter()
3454                .flatten()
3455                .flat_map(|item| {
3456                    Some(OutlineItem {
3457                        depth: item.depth,
3458                        range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3459                            ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3460                        text: item.text,
3461                        highlight_ranges: item.highlight_ranges,
3462                        name_ranges: item.name_ranges,
3463                    })
3464                })
3465                .collect(),
3466        ))
3467    }
3468
3469    fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3470        if id == ExcerptId::min() {
3471            Locator::min_ref()
3472        } else if id == ExcerptId::max() {
3473            Locator::max_ref()
3474        } else {
3475            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3476            cursor.seek(&id, Bias::Left, &());
3477            if let Some(entry) = cursor.item() {
3478                if entry.id == id {
3479                    return &entry.locator;
3480                }
3481            }
3482            panic!("invalid excerpt id {:?}", id)
3483        }
3484    }
3485
3486    // Returns the locators referenced by the given excerpt ids, sorted by locator.
3487    fn excerpt_locators_for_ids(
3488        &self,
3489        ids: impl IntoIterator<Item = ExcerptId>,
3490    ) -> SmallVec<[Locator; 1]> {
3491        let mut sorted_ids = ids.into_iter().collect::<SmallVec<[_; 1]>>();
3492        sorted_ids.sort_unstable();
3493        let mut locators = SmallVec::new();
3494
3495        while sorted_ids.last() == Some(&ExcerptId::max()) {
3496            sorted_ids.pop();
3497            locators.push(Locator::max());
3498        }
3499
3500        let mut sorted_ids = sorted_ids.into_iter().dedup().peekable();
3501        if sorted_ids.peek() == Some(&ExcerptId::min()) {
3502            sorted_ids.next();
3503            locators.push(Locator::min());
3504        }
3505
3506        let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3507        for id in sorted_ids {
3508            if cursor.seek_forward(&id, Bias::Left, &()) {
3509                locators.push(cursor.item().unwrap().locator.clone());
3510            } else {
3511                panic!("invalid excerpt id {:?}", id);
3512            }
3513        }
3514
3515        locators.sort_unstable();
3516        locators
3517    }
3518
3519    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3520        Some(self.excerpt(excerpt_id)?.buffer_id)
3521    }
3522
3523    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3524        Some(&self.excerpt(excerpt_id)?.buffer)
3525    }
3526
3527    fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3528        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3529        let locator = self.excerpt_locator_for_id(excerpt_id);
3530        cursor.seek(&Some(locator), Bias::Left, &());
3531        if let Some(excerpt) = cursor.item() {
3532            if excerpt.id == excerpt_id {
3533                return Some(excerpt);
3534            }
3535        }
3536        None
3537    }
3538
3539    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3540    pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3541        let range = range.start.to_offset(self)..range.end.to_offset(self);
3542
3543        let mut cursor = self.excerpts.cursor::<usize>();
3544        cursor.seek(&range.start, Bias::Right, &());
3545        let start_excerpt = cursor.item()?;
3546
3547        if range.start == range.end {
3548            return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3549        }
3550
3551        cursor.seek(&range.end, Bias::Right, &());
3552        let end_excerpt = cursor.item()?;
3553
3554        if start_excerpt.id == end_excerpt.id {
3555            Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3556        } else {
3557            None
3558        }
3559    }
3560
3561    pub fn remote_selections_in_range<'a>(
3562        &'a self,
3563        range: &'a Range<Anchor>,
3564    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3565        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3566        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3567        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3568        cursor.seek(start_locator, Bias::Left, &());
3569        cursor
3570            .take_while(move |excerpt| excerpt.locator <= *end_locator)
3571            .flat_map(move |excerpt| {
3572                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3573                if excerpt.id == range.start.excerpt_id {
3574                    query_range.start = range.start.text_anchor;
3575                }
3576                if excerpt.id == range.end.excerpt_id {
3577                    query_range.end = range.end.text_anchor;
3578                }
3579
3580                excerpt
3581                    .buffer
3582                    .remote_selections_in_range(query_range)
3583                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3584                        selections.map(move |selection| {
3585                            let mut start = Anchor {
3586                                buffer_id: Some(excerpt.buffer_id),
3587                                excerpt_id: excerpt.id,
3588                                text_anchor: selection.start,
3589                            };
3590                            let mut end = Anchor {
3591                                buffer_id: Some(excerpt.buffer_id),
3592                                excerpt_id: excerpt.id,
3593                                text_anchor: selection.end,
3594                            };
3595                            if range.start.cmp(&start, self).is_gt() {
3596                                start = range.start;
3597                            }
3598                            if range.end.cmp(&end, self).is_lt() {
3599                                end = range.end;
3600                            }
3601
3602                            (
3603                                replica_id,
3604                                line_mode,
3605                                cursor_shape,
3606                                Selection {
3607                                    id: selection.id,
3608                                    start,
3609                                    end,
3610                                    reversed: selection.reversed,
3611                                    goal: selection.goal,
3612                                },
3613                            )
3614                        })
3615                    })
3616            })
3617    }
3618
3619    pub fn show_headers(&self) -> bool {
3620        self.show_headers
3621    }
3622}
3623
3624#[cfg(any(test, feature = "test-support"))]
3625impl MultiBufferSnapshot {
3626    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3627        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3628        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3629        start..end
3630    }
3631}
3632
3633impl History {
3634    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3635        self.transaction_depth += 1;
3636        if self.transaction_depth == 1 {
3637            let id = self.next_transaction_id.tick();
3638            self.undo_stack.push(Transaction {
3639                id,
3640                buffer_transactions: Default::default(),
3641                first_edit_at: now,
3642                last_edit_at: now,
3643                suppress_grouping: false,
3644            });
3645            Some(id)
3646        } else {
3647            None
3648        }
3649    }
3650
3651    fn end_transaction(
3652        &mut self,
3653        now: Instant,
3654        buffer_transactions: HashMap<BufferId, TransactionId>,
3655    ) -> bool {
3656        assert_ne!(self.transaction_depth, 0);
3657        self.transaction_depth -= 1;
3658        if self.transaction_depth == 0 {
3659            if buffer_transactions.is_empty() {
3660                self.undo_stack.pop();
3661                false
3662            } else {
3663                self.redo_stack.clear();
3664                let transaction = self.undo_stack.last_mut().unwrap();
3665                transaction.last_edit_at = now;
3666                for (buffer_id, transaction_id) in buffer_transactions {
3667                    transaction
3668                        .buffer_transactions
3669                        .entry(buffer_id)
3670                        .or_insert(transaction_id);
3671                }
3672                true
3673            }
3674        } else {
3675            false
3676        }
3677    }
3678
3679    fn push_transaction<'a, T>(
3680        &mut self,
3681        buffer_transactions: T,
3682        now: Instant,
3683        cx: &mut ModelContext<MultiBuffer>,
3684    ) where
3685        T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
3686    {
3687        assert_eq!(self.transaction_depth, 0);
3688        let transaction = Transaction {
3689            id: self.next_transaction_id.tick(),
3690            buffer_transactions: buffer_transactions
3691                .into_iter()
3692                .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3693                .collect(),
3694            first_edit_at: now,
3695            last_edit_at: now,
3696            suppress_grouping: false,
3697        };
3698        if !transaction.buffer_transactions.is_empty() {
3699            self.undo_stack.push(transaction);
3700            self.redo_stack.clear();
3701        }
3702    }
3703
3704    fn finalize_last_transaction(&mut self) {
3705        if let Some(transaction) = self.undo_stack.last_mut() {
3706            transaction.suppress_grouping = true;
3707        }
3708    }
3709
3710    fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
3711        if let Some(ix) = self
3712            .undo_stack
3713            .iter()
3714            .rposition(|transaction| transaction.id == transaction_id)
3715        {
3716            Some(self.undo_stack.remove(ix))
3717        } else if let Some(ix) = self
3718            .redo_stack
3719            .iter()
3720            .rposition(|transaction| transaction.id == transaction_id)
3721        {
3722            Some(self.redo_stack.remove(ix))
3723        } else {
3724            None
3725        }
3726    }
3727
3728    fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
3729        self.undo_stack
3730            .iter_mut()
3731            .find(|transaction| transaction.id == transaction_id)
3732            .or_else(|| {
3733                self.redo_stack
3734                    .iter_mut()
3735                    .find(|transaction| transaction.id == transaction_id)
3736            })
3737    }
3738
3739    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3740        assert_eq!(self.transaction_depth, 0);
3741        if let Some(transaction) = self.undo_stack.pop() {
3742            self.redo_stack.push(transaction);
3743            self.redo_stack.last_mut()
3744        } else {
3745            None
3746        }
3747    }
3748
3749    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3750        assert_eq!(self.transaction_depth, 0);
3751        if let Some(transaction) = self.redo_stack.pop() {
3752            self.undo_stack.push(transaction);
3753            self.undo_stack.last_mut()
3754        } else {
3755            None
3756        }
3757    }
3758
3759    fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
3760        let ix = self
3761            .undo_stack
3762            .iter()
3763            .rposition(|transaction| transaction.id == transaction_id)?;
3764        let transaction = self.undo_stack.remove(ix);
3765        self.redo_stack.push(transaction);
3766        self.redo_stack.last()
3767    }
3768
3769    fn group(&mut self) -> Option<TransactionId> {
3770        let mut count = 0;
3771        let mut transactions = self.undo_stack.iter();
3772        if let Some(mut transaction) = transactions.next_back() {
3773            while let Some(prev_transaction) = transactions.next_back() {
3774                if !prev_transaction.suppress_grouping
3775                    && transaction.first_edit_at - prev_transaction.last_edit_at
3776                        <= self.group_interval
3777                {
3778                    transaction = prev_transaction;
3779                    count += 1;
3780                } else {
3781                    break;
3782                }
3783            }
3784        }
3785        self.group_trailing(count)
3786    }
3787
3788    fn group_until(&mut self, transaction_id: TransactionId) {
3789        let mut count = 0;
3790        for transaction in self.undo_stack.iter().rev() {
3791            if transaction.id == transaction_id {
3792                self.group_trailing(count);
3793                break;
3794            } else if transaction.suppress_grouping {
3795                break;
3796            } else {
3797                count += 1;
3798            }
3799        }
3800    }
3801
3802    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3803        let new_len = self.undo_stack.len() - n;
3804        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3805        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3806            if let Some(transaction) = transactions_to_merge.last() {
3807                last_transaction.last_edit_at = transaction.last_edit_at;
3808            }
3809            for to_merge in transactions_to_merge {
3810                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3811                    last_transaction
3812                        .buffer_transactions
3813                        .entry(*buffer_id)
3814                        .or_insert(*transaction_id);
3815                }
3816            }
3817        }
3818
3819        self.undo_stack.truncate(new_len);
3820        self.undo_stack.last().map(|t| t.id)
3821    }
3822}
3823
3824impl Excerpt {
3825    fn new(
3826        id: ExcerptId,
3827        locator: Locator,
3828        buffer_id: BufferId,
3829        buffer: BufferSnapshot,
3830        range: ExcerptRange<text::Anchor>,
3831        has_trailing_newline: bool,
3832    ) -> Self {
3833        Excerpt {
3834            id,
3835            locator,
3836            max_buffer_row: range.context.end.to_point(&buffer).row,
3837            text_summary: buffer
3838                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3839            buffer_id,
3840            buffer,
3841            range,
3842            has_trailing_newline,
3843        }
3844    }
3845
3846    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3847        let content_start = self.range.context.start.to_offset(&self.buffer);
3848        let chunks_start = content_start + range.start;
3849        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3850
3851        let footer_height = if self.has_trailing_newline
3852            && range.start <= self.text_summary.len
3853            && range.end > self.text_summary.len
3854        {
3855            1
3856        } else {
3857            0
3858        };
3859
3860        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3861
3862        ExcerptChunks {
3863            content_chunks,
3864            footer_height,
3865        }
3866    }
3867
3868    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3869        let content_start = self.range.context.start.to_offset(&self.buffer);
3870        let bytes_start = content_start + range.start;
3871        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3872        let footer_height = if self.has_trailing_newline
3873            && range.start <= self.text_summary.len
3874            && range.end > self.text_summary.len
3875        {
3876            1
3877        } else {
3878            0
3879        };
3880        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3881
3882        ExcerptBytes {
3883            content_bytes,
3884            padding_height: footer_height,
3885            reversed: false,
3886        }
3887    }
3888
3889    fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3890        let content_start = self.range.context.start.to_offset(&self.buffer);
3891        let bytes_start = content_start + range.start;
3892        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3893        let footer_height = if self.has_trailing_newline
3894            && range.start <= self.text_summary.len
3895            && range.end > self.text_summary.len
3896        {
3897            1
3898        } else {
3899            0
3900        };
3901        let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3902
3903        ExcerptBytes {
3904            content_bytes,
3905            padding_height: footer_height,
3906            reversed: true,
3907        }
3908    }
3909
3910    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3911        if text_anchor
3912            .cmp(&self.range.context.start, &self.buffer)
3913            .is_lt()
3914        {
3915            self.range.context.start
3916        } else if text_anchor
3917            .cmp(&self.range.context.end, &self.buffer)
3918            .is_gt()
3919        {
3920            self.range.context.end
3921        } else {
3922            text_anchor
3923        }
3924    }
3925
3926    fn contains(&self, anchor: &Anchor) -> bool {
3927        Some(self.buffer_id) == anchor.buffer_id
3928            && self
3929                .range
3930                .context
3931                .start
3932                .cmp(&anchor.text_anchor, &self.buffer)
3933                .is_le()
3934            && self
3935                .range
3936                .context
3937                .end
3938                .cmp(&anchor.text_anchor, &self.buffer)
3939                .is_ge()
3940    }
3941
3942    /// The [`Excerpt`]'s start offset in its [`Buffer`]
3943    fn buffer_start_offset(&self) -> usize {
3944        self.range.context.start.to_offset(&self.buffer)
3945    }
3946
3947    /// The [`Excerpt`]'s end offset in its [`Buffer`]
3948    fn buffer_end_offset(&self) -> usize {
3949        self.buffer_start_offset() + self.text_summary.len
3950    }
3951}
3952
3953impl<'a> MultiBufferExcerpt<'a> {
3954    fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
3955        MultiBufferExcerpt {
3956            excerpt,
3957            excerpt_offset,
3958        }
3959    }
3960
3961    pub fn buffer(&self) -> &'a BufferSnapshot {
3962        &self.excerpt.buffer
3963    }
3964
3965    /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
3966    pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
3967        self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
3968    }
3969
3970    /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
3971    pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
3972        self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
3973    }
3974
3975    /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
3976    pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
3977        let mut buffer_offset_in_excerpt =
3978            buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
3979        buffer_offset_in_excerpt =
3980            cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
3981
3982        self.excerpt_offset + buffer_offset_in_excerpt
3983    }
3984
3985    /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
3986    pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
3987        self.map_offset_from_buffer(buffer_range.start)
3988            ..self.map_offset_from_buffer(buffer_range.end)
3989    }
3990
3991    /// Returns true if the entirety of the given range is in the buffer's excerpt
3992    pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
3993        range.start >= self.excerpt.buffer_start_offset()
3994            && range.end <= self.excerpt.buffer_end_offset()
3995    }
3996}
3997
3998impl ExcerptId {
3999    pub fn min() -> Self {
4000        Self(0)
4001    }
4002
4003    pub fn max() -> Self {
4004        Self(usize::MAX)
4005    }
4006
4007    pub fn to_proto(&self) -> u64 {
4008        self.0 as _
4009    }
4010
4011    pub fn from_proto(proto: u64) -> Self {
4012        Self(proto as _)
4013    }
4014
4015    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
4016        let a = snapshot.excerpt_locator_for_id(*self);
4017        let b = snapshot.excerpt_locator_for_id(*other);
4018        a.cmp(b).then_with(|| self.0.cmp(&other.0))
4019    }
4020}
4021
4022impl Into<usize> for ExcerptId {
4023    fn into(self) -> usize {
4024        self.0
4025    }
4026}
4027
4028impl fmt::Debug for Excerpt {
4029    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4030        f.debug_struct("Excerpt")
4031            .field("id", &self.id)
4032            .field("locator", &self.locator)
4033            .field("buffer_id", &self.buffer_id)
4034            .field("range", &self.range)
4035            .field("text_summary", &self.text_summary)
4036            .field("has_trailing_newline", &self.has_trailing_newline)
4037            .finish()
4038    }
4039}
4040
4041impl sum_tree::Item for Excerpt {
4042    type Summary = ExcerptSummary;
4043
4044    fn summary(&self) -> Self::Summary {
4045        let mut text = self.text_summary.clone();
4046        if self.has_trailing_newline {
4047            text += TextSummary::from("\n");
4048        }
4049        ExcerptSummary {
4050            excerpt_id: self.id,
4051            excerpt_locator: self.locator.clone(),
4052            max_buffer_row: self.max_buffer_row,
4053            text,
4054        }
4055    }
4056}
4057
4058impl sum_tree::Item for ExcerptIdMapping {
4059    type Summary = ExcerptId;
4060
4061    fn summary(&self) -> Self::Summary {
4062        self.id
4063    }
4064}
4065
4066impl sum_tree::KeyedItem for ExcerptIdMapping {
4067    type Key = ExcerptId;
4068
4069    fn key(&self) -> Self::Key {
4070        self.id
4071    }
4072}
4073
4074impl sum_tree::Summary for ExcerptId {
4075    type Context = ();
4076
4077    fn add_summary(&mut self, other: &Self, _: &()) {
4078        *self = *other;
4079    }
4080}
4081
4082impl sum_tree::Summary for ExcerptSummary {
4083    type Context = ();
4084
4085    fn add_summary(&mut self, summary: &Self, _: &()) {
4086        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
4087        self.excerpt_locator = summary.excerpt_locator.clone();
4088        self.text.add_summary(&summary.text, &());
4089        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
4090    }
4091}
4092
4093impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
4094    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4095        *self += &summary.text;
4096    }
4097}
4098
4099impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
4100    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4101        *self += summary.text.len;
4102    }
4103}
4104
4105impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
4106    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4107        Ord::cmp(self, &cursor_location.text.len)
4108    }
4109}
4110
4111impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
4112    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
4113        Ord::cmp(&Some(self), cursor_location)
4114    }
4115}
4116
4117impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
4118    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
4119        Ord::cmp(self, &cursor_location.excerpt_locator)
4120    }
4121}
4122
4123impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
4124    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4125        *self += summary.text.len_utf16;
4126    }
4127}
4128
4129impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
4130    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4131        *self += summary.text.lines;
4132    }
4133}
4134
4135impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
4136    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4137        *self += summary.text.lines_utf16()
4138    }
4139}
4140
4141impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
4142    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4143        *self = Some(&summary.excerpt_locator);
4144    }
4145}
4146
4147impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
4148    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
4149        *self = Some(summary.excerpt_id);
4150    }
4151}
4152
4153impl<'a> MultiBufferRows<'a> {
4154    pub fn seek(&mut self, row: u32) {
4155        self.buffer_row_range = 0..0;
4156
4157        self.excerpts
4158            .seek_forward(&Point::new(row, 0), Bias::Right, &());
4159        if self.excerpts.item().is_none() {
4160            self.excerpts.prev(&());
4161
4162            if self.excerpts.item().is_none() && row == 0 {
4163                self.buffer_row_range = 0..1;
4164                return;
4165            }
4166        }
4167
4168        if let Some(excerpt) = self.excerpts.item() {
4169            let overshoot = row - self.excerpts.start().row;
4170            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4171            self.buffer_row_range.start = excerpt_start + overshoot;
4172            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4173        }
4174    }
4175}
4176
4177impl<'a> Iterator for MultiBufferRows<'a> {
4178    type Item = Option<u32>;
4179
4180    fn next(&mut self) -> Option<Self::Item> {
4181        loop {
4182            if !self.buffer_row_range.is_empty() {
4183                let row = Some(self.buffer_row_range.start);
4184                self.buffer_row_range.start += 1;
4185                return Some(row);
4186            }
4187            self.excerpts.item()?;
4188            self.excerpts.next(&());
4189            let excerpt = self.excerpts.item()?;
4190            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4191            self.buffer_row_range.end =
4192                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4193        }
4194    }
4195}
4196
4197impl<'a> MultiBufferChunks<'a> {
4198    pub fn offset(&self) -> usize {
4199        self.range.start
4200    }
4201
4202    pub fn seek(&mut self, offset: usize) {
4203        self.range.start = offset;
4204        self.excerpts.seek(&offset, Bias::Right, &());
4205        if let Some(excerpt) = self.excerpts.item() {
4206            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4207                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
4208                self.language_aware,
4209            ));
4210        } else {
4211            self.excerpt_chunks = None;
4212        }
4213    }
4214}
4215
4216impl<'a> Iterator for MultiBufferChunks<'a> {
4217    type Item = Chunk<'a>;
4218
4219    fn next(&mut self) -> Option<Self::Item> {
4220        if self.range.is_empty() {
4221            None
4222        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4223            self.range.start += chunk.text.len();
4224            Some(chunk)
4225        } else {
4226            self.excerpts.next(&());
4227            let excerpt = self.excerpts.item()?;
4228            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4229                0..self.range.end - self.excerpts.start(),
4230                self.language_aware,
4231            ));
4232            self.next()
4233        }
4234    }
4235}
4236
4237impl<'a> MultiBufferBytes<'a> {
4238    fn consume(&mut self, len: usize) {
4239        self.range.start += len;
4240        self.chunk = &self.chunk[len..];
4241
4242        if !self.range.is_empty() && self.chunk.is_empty() {
4243            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4244                self.chunk = chunk;
4245            } else {
4246                self.excerpts.next(&());
4247                if let Some(excerpt) = self.excerpts.item() {
4248                    let mut excerpt_bytes =
4249                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4250                    self.chunk = excerpt_bytes.next().unwrap();
4251                    self.excerpt_bytes = Some(excerpt_bytes);
4252                }
4253            }
4254        }
4255    }
4256}
4257
4258impl<'a> Iterator for MultiBufferBytes<'a> {
4259    type Item = &'a [u8];
4260
4261    fn next(&mut self) -> Option<Self::Item> {
4262        let chunk = self.chunk;
4263        if chunk.is_empty() {
4264            None
4265        } else {
4266            self.consume(chunk.len());
4267            Some(chunk)
4268        }
4269    }
4270}
4271
4272impl<'a> io::Read for MultiBufferBytes<'a> {
4273    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4274        let len = cmp::min(buf.len(), self.chunk.len());
4275        buf[..len].copy_from_slice(&self.chunk[..len]);
4276        if len > 0 {
4277            self.consume(len);
4278        }
4279        Ok(len)
4280    }
4281}
4282
4283impl<'a> ReversedMultiBufferBytes<'a> {
4284    fn consume(&mut self, len: usize) {
4285        self.range.end -= len;
4286        self.chunk = &self.chunk[..self.chunk.len() - len];
4287
4288        if !self.range.is_empty() && self.chunk.is_empty() {
4289            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4290                self.chunk = chunk;
4291            } else {
4292                self.excerpts.prev(&());
4293                if let Some(excerpt) = self.excerpts.item() {
4294                    let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
4295                        self.range.start.saturating_sub(*self.excerpts.start())..usize::MAX,
4296                    );
4297                    self.chunk = excerpt_bytes.next().unwrap();
4298                    self.excerpt_bytes = Some(excerpt_bytes);
4299                }
4300            }
4301        } else {
4302        }
4303    }
4304}
4305
4306impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4307    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4308        let len = cmp::min(buf.len(), self.chunk.len());
4309        buf[..len].copy_from_slice(&self.chunk[..len]);
4310        buf[..len].reverse();
4311        if len > 0 {
4312            self.consume(len);
4313        }
4314        Ok(len)
4315    }
4316}
4317impl<'a> Iterator for ExcerptBytes<'a> {
4318    type Item = &'a [u8];
4319
4320    fn next(&mut self) -> Option<Self::Item> {
4321        if self.reversed && self.padding_height > 0 {
4322            let result = &NEWLINES[..self.padding_height];
4323            self.padding_height = 0;
4324            return Some(result);
4325        }
4326
4327        if let Some(chunk) = self.content_bytes.next() {
4328            if !chunk.is_empty() {
4329                return Some(chunk);
4330            }
4331        }
4332
4333        if self.padding_height > 0 {
4334            let result = &NEWLINES[..self.padding_height];
4335            self.padding_height = 0;
4336            return Some(result);
4337        }
4338
4339        None
4340    }
4341}
4342
4343impl<'a> Iterator for ExcerptChunks<'a> {
4344    type Item = Chunk<'a>;
4345
4346    fn next(&mut self) -> Option<Self::Item> {
4347        if let Some(chunk) = self.content_chunks.next() {
4348            return Some(chunk);
4349        }
4350
4351        if self.footer_height > 0 {
4352            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4353            self.footer_height = 0;
4354            return Some(Chunk {
4355                text,
4356                ..Default::default()
4357            });
4358        }
4359
4360        None
4361    }
4362}
4363
4364impl ToOffset for Point {
4365    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4366        snapshot.point_to_offset(*self)
4367    }
4368}
4369
4370impl ToOffset for usize {
4371    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4372        assert!(*self <= snapshot.len(), "offset is out of range");
4373        *self
4374    }
4375}
4376
4377impl ToOffset for OffsetUtf16 {
4378    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4379        snapshot.offset_utf16_to_offset(*self)
4380    }
4381}
4382
4383impl ToOffset for PointUtf16 {
4384    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4385        snapshot.point_utf16_to_offset(*self)
4386    }
4387}
4388
4389impl ToOffsetUtf16 for OffsetUtf16 {
4390    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4391        *self
4392    }
4393}
4394
4395impl ToOffsetUtf16 for usize {
4396    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4397        snapshot.offset_to_offset_utf16(*self)
4398    }
4399}
4400
4401impl ToPoint for usize {
4402    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
4403        snapshot.offset_to_point(*self)
4404    }
4405}
4406
4407impl ToPoint for Point {
4408    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
4409        *self
4410    }
4411}
4412
4413impl ToPointUtf16 for usize {
4414    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4415        snapshot.offset_to_point_utf16(*self)
4416    }
4417}
4418
4419impl ToPointUtf16 for Point {
4420    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4421        snapshot.point_to_point_utf16(*self)
4422    }
4423}
4424
4425impl ToPointUtf16 for PointUtf16 {
4426    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
4427        *self
4428    }
4429}
4430
4431fn build_excerpt_ranges<T>(
4432    buffer: &BufferSnapshot,
4433    ranges: &[Range<T>],
4434    context_line_count: u32,
4435) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
4436where
4437    T: text::ToPoint,
4438{
4439    let max_point = buffer.max_point();
4440    let mut range_counts = Vec::new();
4441    let mut excerpt_ranges = Vec::new();
4442    let mut range_iter = ranges
4443        .iter()
4444        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
4445        .peekable();
4446    while let Some(range) = range_iter.next() {
4447        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
4448        // These + 1s ensure that we select the whole next line
4449        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
4450
4451        let mut ranges_in_excerpt = 1;
4452
4453        while let Some(next_range) = range_iter.peek() {
4454            if next_range.start.row <= excerpt_end.row + context_line_count {
4455                excerpt_end =
4456                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
4457                ranges_in_excerpt += 1;
4458                range_iter.next();
4459            } else {
4460                break;
4461            }
4462        }
4463
4464        excerpt_ranges.push(ExcerptRange {
4465            context: excerpt_start..excerpt_end,
4466            primary: Some(range),
4467        });
4468        range_counts.push(ranges_in_excerpt);
4469    }
4470
4471    (excerpt_ranges, range_counts)
4472}
4473
4474#[cfg(test)]
4475mod tests {
4476    use super::*;
4477    use futures::StreamExt;
4478    use gpui::{AppContext, Context, TestAppContext};
4479    use language::{Buffer, Rope};
4480    use parking_lot::RwLock;
4481    use rand::prelude::*;
4482    use settings::SettingsStore;
4483    use std::env;
4484    use util::test::sample_text;
4485
4486    #[ctor::ctor]
4487    fn init_logger() {
4488        if std::env::var("RUST_LOG").is_ok() {
4489            env_logger::init();
4490        }
4491    }
4492
4493    #[gpui::test]
4494    fn test_singleton(cx: &mut AppContext) {
4495        let buffer = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4496        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4497
4498        let snapshot = multibuffer.read(cx).snapshot(cx);
4499        assert_eq!(snapshot.text(), buffer.read(cx).text());
4500
4501        assert_eq!(
4502            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4503            (0..buffer.read(cx).row_count())
4504                .map(Some)
4505                .collect::<Vec<_>>()
4506        );
4507
4508        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4509        let snapshot = multibuffer.read(cx).snapshot(cx);
4510
4511        assert_eq!(snapshot.text(), buffer.read(cx).text());
4512        assert_eq!(
4513            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4514            (0..buffer.read(cx).row_count())
4515                .map(Some)
4516                .collect::<Vec<_>>()
4517        );
4518    }
4519
4520    #[gpui::test]
4521    fn test_remote(cx: &mut AppContext) {
4522        let host_buffer = cx.new_model(|cx| Buffer::local("a", cx));
4523        let guest_buffer = cx.new_model(|cx| {
4524            let state = host_buffer.read(cx).to_proto();
4525            let ops = cx
4526                .background_executor()
4527                .block(host_buffer.read(cx).serialize_ops(None, cx));
4528            let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
4529            buffer
4530                .apply_ops(
4531                    ops.into_iter()
4532                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
4533                    cx,
4534                )
4535                .unwrap();
4536            buffer
4537        });
4538        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4539        let snapshot = multibuffer.read(cx).snapshot(cx);
4540        assert_eq!(snapshot.text(), "a");
4541
4542        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4543        let snapshot = multibuffer.read(cx).snapshot(cx);
4544        assert_eq!(snapshot.text(), "ab");
4545
4546        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4547        let snapshot = multibuffer.read(cx).snapshot(cx);
4548        assert_eq!(snapshot.text(), "abc");
4549    }
4550
4551    #[gpui::test]
4552    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4553        let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
4554        let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
4555        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4556
4557        let events = Arc::new(RwLock::new(Vec::<Event>::new()));
4558        multibuffer.update(cx, |_, cx| {
4559            let events = events.clone();
4560            cx.subscribe(&multibuffer, move |_, _, event, _| {
4561                if let Event::Edited { .. } = event {
4562                    events.write().push(event.clone())
4563                }
4564            })
4565            .detach();
4566        });
4567
4568        let subscription = multibuffer.update(cx, |multibuffer, cx| {
4569            let subscription = multibuffer.subscribe();
4570            multibuffer.push_excerpts(
4571                buffer_1.clone(),
4572                [ExcerptRange {
4573                    context: Point::new(1, 2)..Point::new(2, 5),
4574                    primary: None,
4575                }],
4576                cx,
4577            );
4578            assert_eq!(
4579                subscription.consume().into_inner(),
4580                [Edit {
4581                    old: 0..0,
4582                    new: 0..10
4583                }]
4584            );
4585
4586            multibuffer.push_excerpts(
4587                buffer_1.clone(),
4588                [ExcerptRange {
4589                    context: Point::new(3, 3)..Point::new(4, 4),
4590                    primary: None,
4591                }],
4592                cx,
4593            );
4594            multibuffer.push_excerpts(
4595                buffer_2.clone(),
4596                [ExcerptRange {
4597                    context: Point::new(3, 1)..Point::new(3, 3),
4598                    primary: None,
4599                }],
4600                cx,
4601            );
4602            assert_eq!(
4603                subscription.consume().into_inner(),
4604                [Edit {
4605                    old: 10..10,
4606                    new: 10..22
4607                }]
4608            );
4609
4610            subscription
4611        });
4612
4613        // Adding excerpts emits an edited event.
4614        assert_eq!(
4615            events.read().as_slice(),
4616            &[
4617                Event::Edited {
4618                    singleton_buffer_edited: false
4619                },
4620                Event::Edited {
4621                    singleton_buffer_edited: false
4622                },
4623                Event::Edited {
4624                    singleton_buffer_edited: false
4625                }
4626            ]
4627        );
4628
4629        let snapshot = multibuffer.read(cx).snapshot(cx);
4630        assert_eq!(
4631            snapshot.text(),
4632            concat!(
4633                "bbbb\n",  // Preserve newlines
4634                "ccccc\n", //
4635                "ddd\n",   //
4636                "eeee\n",  //
4637                "jj"       //
4638            )
4639        );
4640        assert_eq!(
4641            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4642            [Some(1), Some(2), Some(3), Some(4), Some(3)]
4643        );
4644        assert_eq!(
4645            snapshot.buffer_rows(2).collect::<Vec<_>>(),
4646            [Some(3), Some(4), Some(3)]
4647        );
4648        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4649        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4650
4651        assert_eq!(
4652            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4653            &[
4654                (0, "bbbb\nccccc".to_string(), true),
4655                (2, "ddd\neeee".to_string(), false),
4656                (4, "jj".to_string(), true),
4657            ]
4658        );
4659        assert_eq!(
4660            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4661            &[(0, "bbbb\nccccc".to_string(), true)]
4662        );
4663        assert_eq!(
4664            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4665            &[]
4666        );
4667        assert_eq!(
4668            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4669            &[]
4670        );
4671        assert_eq!(
4672            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4673            &[(2, "ddd\neeee".to_string(), false)]
4674        );
4675        assert_eq!(
4676            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4677            &[(2, "ddd\neeee".to_string(), false)]
4678        );
4679        assert_eq!(
4680            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4681            &[(2, "ddd\neeee".to_string(), false)]
4682        );
4683        assert_eq!(
4684            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4685            &[(4, "jj".to_string(), true)]
4686        );
4687        assert_eq!(
4688            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4689            &[]
4690        );
4691
4692        buffer_1.update(cx, |buffer, cx| {
4693            let text = "\n";
4694            buffer.edit(
4695                [
4696                    (Point::new(0, 0)..Point::new(0, 0), text),
4697                    (Point::new(2, 1)..Point::new(2, 3), text),
4698                ],
4699                None,
4700                cx,
4701            );
4702        });
4703
4704        let snapshot = multibuffer.read(cx).snapshot(cx);
4705        assert_eq!(
4706            snapshot.text(),
4707            concat!(
4708                "bbbb\n", // Preserve newlines
4709                "c\n",    //
4710                "cc\n",   //
4711                "ddd\n",  //
4712                "eeee\n", //
4713                "jj"      //
4714            )
4715        );
4716
4717        assert_eq!(
4718            subscription.consume().into_inner(),
4719            [Edit {
4720                old: 6..8,
4721                new: 6..7
4722            }]
4723        );
4724
4725        let snapshot = multibuffer.read(cx).snapshot(cx);
4726        assert_eq!(
4727            snapshot.clip_point(Point::new(0, 5), Bias::Left),
4728            Point::new(0, 4)
4729        );
4730        assert_eq!(
4731            snapshot.clip_point(Point::new(0, 5), Bias::Right),
4732            Point::new(0, 4)
4733        );
4734        assert_eq!(
4735            snapshot.clip_point(Point::new(5, 1), Bias::Right),
4736            Point::new(5, 1)
4737        );
4738        assert_eq!(
4739            snapshot.clip_point(Point::new(5, 2), Bias::Right),
4740            Point::new(5, 2)
4741        );
4742        assert_eq!(
4743            snapshot.clip_point(Point::new(5, 3), Bias::Right),
4744            Point::new(5, 2)
4745        );
4746
4747        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4748            let (buffer_2_excerpt_id, _) =
4749                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4750            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4751            multibuffer.snapshot(cx)
4752        });
4753
4754        assert_eq!(
4755            snapshot.text(),
4756            concat!(
4757                "bbbb\n", // Preserve newlines
4758                "c\n",    //
4759                "cc\n",   //
4760                "ddd\n",  //
4761                "eeee",   //
4762            )
4763        );
4764
4765        fn boundaries_in_range(
4766            range: Range<Point>,
4767            snapshot: &MultiBufferSnapshot,
4768        ) -> Vec<(u32, String, bool)> {
4769            snapshot
4770                .excerpt_boundaries_in_range(range)
4771                .map(|boundary| {
4772                    (
4773                        boundary.row,
4774                        boundary
4775                            .buffer
4776                            .text_for_range(boundary.range.context)
4777                            .collect::<String>(),
4778                        boundary.starts_new_buffer,
4779                    )
4780                })
4781                .collect::<Vec<_>>()
4782        }
4783    }
4784
4785    #[gpui::test]
4786    fn test_excerpt_events(cx: &mut AppContext) {
4787        let buffer_1 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
4788        let buffer_2 = cx.new_model(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
4789
4790        let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4791        let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4792        let follower_edit_event_count = Arc::new(RwLock::new(0));
4793
4794        follower_multibuffer.update(cx, |_, cx| {
4795            let follower_edit_event_count = follower_edit_event_count.clone();
4796            cx.subscribe(
4797                &leader_multibuffer,
4798                move |follower, _, event, cx| match event.clone() {
4799                    Event::ExcerptsAdded {
4800                        buffer,
4801                        predecessor,
4802                        excerpts,
4803                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4804                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4805                    Event::Edited { .. } => {
4806                        *follower_edit_event_count.write() += 1;
4807                    }
4808                    _ => {}
4809                },
4810            )
4811            .detach();
4812        });
4813
4814        leader_multibuffer.update(cx, |leader, cx| {
4815            leader.push_excerpts(
4816                buffer_1.clone(),
4817                [
4818                    ExcerptRange {
4819                        context: 0..8,
4820                        primary: None,
4821                    },
4822                    ExcerptRange {
4823                        context: 12..16,
4824                        primary: None,
4825                    },
4826                ],
4827                cx,
4828            );
4829            leader.insert_excerpts_after(
4830                leader.excerpt_ids()[0],
4831                buffer_2.clone(),
4832                [
4833                    ExcerptRange {
4834                        context: 0..5,
4835                        primary: None,
4836                    },
4837                    ExcerptRange {
4838                        context: 10..15,
4839                        primary: None,
4840                    },
4841                ],
4842                cx,
4843            )
4844        });
4845        assert_eq!(
4846            leader_multibuffer.read(cx).snapshot(cx).text(),
4847            follower_multibuffer.read(cx).snapshot(cx).text(),
4848        );
4849        assert_eq!(*follower_edit_event_count.read(), 2);
4850
4851        leader_multibuffer.update(cx, |leader, cx| {
4852            let excerpt_ids = leader.excerpt_ids();
4853            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4854        });
4855        assert_eq!(
4856            leader_multibuffer.read(cx).snapshot(cx).text(),
4857            follower_multibuffer.read(cx).snapshot(cx).text(),
4858        );
4859        assert_eq!(*follower_edit_event_count.read(), 3);
4860
4861        // Removing an empty set of excerpts is a noop.
4862        leader_multibuffer.update(cx, |leader, cx| {
4863            leader.remove_excerpts([], cx);
4864        });
4865        assert_eq!(
4866            leader_multibuffer.read(cx).snapshot(cx).text(),
4867            follower_multibuffer.read(cx).snapshot(cx).text(),
4868        );
4869        assert_eq!(*follower_edit_event_count.read(), 3);
4870
4871        // Adding an empty set of excerpts is a noop.
4872        leader_multibuffer.update(cx, |leader, cx| {
4873            leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4874        });
4875        assert_eq!(
4876            leader_multibuffer.read(cx).snapshot(cx).text(),
4877            follower_multibuffer.read(cx).snapshot(cx).text(),
4878        );
4879        assert_eq!(*follower_edit_event_count.read(), 3);
4880
4881        leader_multibuffer.update(cx, |leader, cx| {
4882            leader.clear(cx);
4883        });
4884        assert_eq!(
4885            leader_multibuffer.read(cx).snapshot(cx).text(),
4886            follower_multibuffer.read(cx).snapshot(cx).text(),
4887        );
4888        assert_eq!(*follower_edit_event_count.read(), 4);
4889    }
4890
4891    #[gpui::test]
4892    fn test_expand_excerpts(cx: &mut AppContext) {
4893        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
4894        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4895
4896        multibuffer.update(cx, |multibuffer, cx| {
4897            multibuffer.push_excerpts_with_context_lines(
4898                buffer.clone(),
4899                vec![
4900                    // Note that in this test, this first excerpt
4901                    // does not contain a new line
4902                    Point::new(3, 2)..Point::new(3, 3),
4903                    Point::new(7, 1)..Point::new(7, 3),
4904                    Point::new(15, 0)..Point::new(15, 0),
4905                ],
4906                1,
4907                cx,
4908            )
4909        });
4910
4911        multibuffer.update(cx, |multibuffer, cx| {
4912            multibuffer.expand_excerpts(multibuffer.excerpt_ids(), 1, cx)
4913        });
4914
4915        let snapshot = multibuffer.read(cx).snapshot(cx);
4916
4917        // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
4918        // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
4919        // that are tracking excerpt ids.
4920        assert_eq!(
4921            snapshot.text(),
4922            concat!(
4923                "bbb\n", // Preserve newlines
4924                "ccc\n", //
4925                "ddd\n", //
4926                "eee\n", //
4927                "fff\n", // <- Same as below
4928                "\n",    // Excerpt boundary
4929                "fff\n", // <- Same as above
4930                "ggg\n", //
4931                "hhh\n", //
4932                "iii\n", //
4933                "jjj\n", //
4934                "\n",    //
4935                "nnn\n", //
4936                "ooo\n", //
4937                "ppp\n", //
4938                "qqq\n", //
4939                "rrr\n", //
4940            )
4941        );
4942    }
4943
4944    #[gpui::test]
4945    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4946        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
4947        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4948        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4949            multibuffer.push_excerpts_with_context_lines(
4950                buffer.clone(),
4951                vec![
4952                    // Note that in this test, this first excerpt
4953                    // does contain a new line
4954                    Point::new(3, 2)..Point::new(4, 2),
4955                    Point::new(7, 1)..Point::new(7, 3),
4956                    Point::new(15, 0)..Point::new(15, 0),
4957                ],
4958                2,
4959                cx,
4960            )
4961        });
4962
4963        let snapshot = multibuffer.read(cx).snapshot(cx);
4964        assert_eq!(
4965            snapshot.text(),
4966            concat!(
4967                "bbb\n", // Preserve newlines
4968                "ccc\n", //
4969                "ddd\n", //
4970                "eee\n", //
4971                "fff\n", //
4972                "ggg\n", //
4973                "hhh\n", //
4974                "iii\n", //
4975                "jjj\n", //
4976                "\n",    //
4977                "nnn\n", //
4978                "ooo\n", //
4979                "ppp\n", //
4980                "qqq\n", //
4981                "rrr\n", //
4982            )
4983        );
4984
4985        assert_eq!(
4986            anchor_ranges
4987                .iter()
4988                .map(|range| range.to_point(&snapshot))
4989                .collect::<Vec<_>>(),
4990            vec![
4991                Point::new(2, 2)..Point::new(3, 2),
4992                Point::new(6, 1)..Point::new(6, 3),
4993                Point::new(12, 0)..Point::new(12, 0)
4994            ]
4995        );
4996    }
4997
4998    #[gpui::test]
4999    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
5000        let buffer = cx.new_model(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
5001        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5002        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
5003            let snapshot = buffer.read(cx);
5004            let ranges = vec![
5005                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
5006                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
5007                snapshot.anchor_before(Point::new(15, 0))
5008                    ..snapshot.anchor_before(Point::new(15, 0)),
5009            ];
5010            multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
5011        });
5012
5013        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
5014
5015        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
5016        assert_eq!(
5017            snapshot.text(),
5018            concat!(
5019                "bbb\n", //
5020                "ccc\n", //
5021                "ddd\n", //
5022                "eee\n", //
5023                "fff\n", //
5024                "ggg\n", //
5025                "hhh\n", //
5026                "iii\n", //
5027                "jjj\n", //
5028                "\n",    //
5029                "nnn\n", //
5030                "ooo\n", //
5031                "ppp\n", //
5032                "qqq\n", //
5033                "rrr\n", //
5034            )
5035        );
5036
5037        assert_eq!(
5038            anchor_ranges
5039                .iter()
5040                .map(|range| range.to_point(&snapshot))
5041                .collect::<Vec<_>>(),
5042            vec![
5043                Point::new(2, 2)..Point::new(3, 2),
5044                Point::new(6, 1)..Point::new(6, 3),
5045                Point::new(12, 0)..Point::new(12, 0)
5046            ]
5047        );
5048    }
5049
5050    #[gpui::test]
5051    fn test_empty_multibuffer(cx: &mut AppContext) {
5052        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5053
5054        let snapshot = multibuffer.read(cx).snapshot(cx);
5055        assert_eq!(snapshot.text(), "");
5056        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
5057        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
5058    }
5059
5060    #[gpui::test]
5061    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
5062        let buffer = cx.new_model(|cx| Buffer::local("abcd", cx));
5063        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
5064        let old_snapshot = multibuffer.read(cx).snapshot(cx);
5065        buffer.update(cx, |buffer, cx| {
5066            buffer.edit([(0..0, "X")], None, cx);
5067            buffer.edit([(5..5, "Y")], None, cx);
5068        });
5069        let new_snapshot = multibuffer.read(cx).snapshot(cx);
5070
5071        assert_eq!(old_snapshot.text(), "abcd");
5072        assert_eq!(new_snapshot.text(), "XabcdY");
5073
5074        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5075        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5076        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
5077        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
5078    }
5079
5080    #[gpui::test]
5081    fn test_multibuffer_anchors(cx: &mut AppContext) {
5082        let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5083        let buffer_2 = cx.new_model(|cx| Buffer::local("efghi", cx));
5084        let multibuffer = cx.new_model(|cx| {
5085            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
5086            multibuffer.push_excerpts(
5087                buffer_1.clone(),
5088                [ExcerptRange {
5089                    context: 0..4,
5090                    primary: None,
5091                }],
5092                cx,
5093            );
5094            multibuffer.push_excerpts(
5095                buffer_2.clone(),
5096                [ExcerptRange {
5097                    context: 0..5,
5098                    primary: None,
5099                }],
5100                cx,
5101            );
5102            multibuffer
5103        });
5104        let old_snapshot = multibuffer.read(cx).snapshot(cx);
5105
5106        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
5107        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
5108        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5109        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
5110        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5111        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
5112
5113        buffer_1.update(cx, |buffer, cx| {
5114            buffer.edit([(0..0, "W")], None, cx);
5115            buffer.edit([(5..5, "X")], None, cx);
5116        });
5117        buffer_2.update(cx, |buffer, cx| {
5118            buffer.edit([(0..0, "Y")], None, cx);
5119            buffer.edit([(6..6, "Z")], None, cx);
5120        });
5121        let new_snapshot = multibuffer.read(cx).snapshot(cx);
5122
5123        assert_eq!(old_snapshot.text(), "abcd\nefghi");
5124        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
5125
5126        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
5127        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
5128        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
5129        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
5130        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
5131        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
5132        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
5133        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
5134        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
5135        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
5136    }
5137
5138    #[gpui::test]
5139    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
5140        let buffer_1 = cx.new_model(|cx| Buffer::local("abcd", cx));
5141        let buffer_2 = cx.new_model(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
5142        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5143
5144        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
5145        // Add an excerpt from buffer 1 that spans this new insertion.
5146        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
5147        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
5148            multibuffer
5149                .push_excerpts(
5150                    buffer_1.clone(),
5151                    [ExcerptRange {
5152                        context: 0..7,
5153                        primary: None,
5154                    }],
5155                    cx,
5156                )
5157                .pop()
5158                .unwrap()
5159        });
5160
5161        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
5162        assert_eq!(snapshot_1.text(), "abcd123");
5163
5164        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
5165        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
5166            multibuffer.remove_excerpts([excerpt_id_1], cx);
5167            let mut ids = multibuffer
5168                .push_excerpts(
5169                    buffer_2.clone(),
5170                    [
5171                        ExcerptRange {
5172                            context: 0..4,
5173                            primary: None,
5174                        },
5175                        ExcerptRange {
5176                            context: 6..10,
5177                            primary: None,
5178                        },
5179                        ExcerptRange {
5180                            context: 12..16,
5181                            primary: None,
5182                        },
5183                    ],
5184                    cx,
5185                )
5186                .into_iter();
5187            (ids.next().unwrap(), ids.next().unwrap())
5188        });
5189        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
5190        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
5191
5192        // The old excerpt id doesn't get reused.
5193        assert_ne!(excerpt_id_2, excerpt_id_1);
5194
5195        // Resolve some anchors from the previous snapshot in the new snapshot.
5196        // The current excerpts are from a different buffer, so we don't attempt to
5197        // resolve the old text anchor in the new buffer.
5198        assert_eq!(
5199            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
5200            0
5201        );
5202        assert_eq!(
5203            snapshot_2.summaries_for_anchors::<usize, _>(&[
5204                snapshot_1.anchor_before(2),
5205                snapshot_1.anchor_after(3)
5206            ]),
5207            vec![0, 0]
5208        );
5209
5210        // Refresh anchors from the old snapshot. The return value indicates that both
5211        // anchors lost their original excerpt.
5212        let refresh =
5213            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5214        assert_eq!(
5215            refresh,
5216            &[
5217                (0, snapshot_2.anchor_before(0), false),
5218                (1, snapshot_2.anchor_after(0), false),
5219            ]
5220        );
5221
5222        // Replace the middle excerpt with a smaller excerpt in buffer 2,
5223        // that intersects the old excerpt.
5224        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5225            multibuffer.remove_excerpts([excerpt_id_3], cx);
5226            multibuffer
5227                .insert_excerpts_after(
5228                    excerpt_id_2,
5229                    buffer_2.clone(),
5230                    [ExcerptRange {
5231                        context: 5..8,
5232                        primary: None,
5233                    }],
5234                    cx,
5235                )
5236                .pop()
5237                .unwrap()
5238        });
5239
5240        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5241        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5242        assert_ne!(excerpt_id_5, excerpt_id_3);
5243
5244        // Resolve some anchors from the previous snapshot in the new snapshot.
5245        // The third anchor can't be resolved, since its excerpt has been removed,
5246        // so it resolves to the same position as its predecessor.
5247        let anchors = [
5248            snapshot_2.anchor_before(0),
5249            snapshot_2.anchor_after(2),
5250            snapshot_2.anchor_after(6),
5251            snapshot_2.anchor_after(14),
5252        ];
5253        assert_eq!(
5254            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5255            &[0, 2, 9, 13]
5256        );
5257
5258        let new_anchors = snapshot_3.refresh_anchors(&anchors);
5259        assert_eq!(
5260            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5261            &[(0, true), (1, true), (2, true), (3, true)]
5262        );
5263        assert_eq!(
5264            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5265            &[0, 2, 7, 13]
5266        );
5267    }
5268
5269    #[gpui::test(iterations = 100)]
5270    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5271        let operations = env::var("OPERATIONS")
5272            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5273            .unwrap_or(10);
5274
5275        let mut buffers: Vec<Model<Buffer>> = Vec::new();
5276        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5277        let mut excerpt_ids = Vec::<ExcerptId>::new();
5278        let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5279        let mut anchors = Vec::new();
5280        let mut old_versions = Vec::new();
5281
5282        for _ in 0..operations {
5283            match rng.gen_range(0..100) {
5284                0..=14 if !buffers.is_empty() => {
5285                    let buffer = buffers.choose(&mut rng).unwrap();
5286                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5287                }
5288                15..=19 if !expected_excerpts.is_empty() => {
5289                    multibuffer.update(cx, |multibuffer, cx| {
5290                        let ids = multibuffer.excerpt_ids();
5291                        let mut excerpts = HashSet::default();
5292                        for _ in 0..rng.gen_range(0..ids.len()) {
5293                            excerpts.extend(ids.choose(&mut rng).copied());
5294                        }
5295
5296                        let line_count = rng.gen_range(0..5);
5297
5298                        let excerpt_ixs = excerpts
5299                            .iter()
5300                            .map(|id| excerpt_ids.iter().position(|i| i == id).unwrap())
5301                            .collect::<Vec<_>>();
5302                        log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
5303                        multibuffer.expand_excerpts(excerpts.iter().cloned(), line_count, cx);
5304
5305                        if line_count > 0 {
5306                            for id in excerpts {
5307                                let excerpt_ix = excerpt_ids.iter().position(|&i| i == id).unwrap();
5308                                let (buffer, range) = &mut expected_excerpts[excerpt_ix];
5309                                let snapshot = buffer.read(cx).snapshot();
5310                                let mut point_range = range.to_point(&snapshot);
5311                                point_range.start =
5312                                    Point::new(point_range.start.row.saturating_sub(line_count), 0);
5313                                point_range.end = snapshot.clip_point(
5314                                    Point::new(point_range.end.row + line_count, 0),
5315                                    Bias::Left,
5316                                );
5317                                *range = snapshot.anchor_before(point_range.start)
5318                                    ..snapshot.anchor_after(point_range.end);
5319                            }
5320                        }
5321                    });
5322                }
5323                20..=29 if !expected_excerpts.is_empty() => {
5324                    let mut ids_to_remove = vec![];
5325                    for _ in 0..rng.gen_range(1..=3) {
5326                        if expected_excerpts.is_empty() {
5327                            break;
5328                        }
5329
5330                        let ix = rng.gen_range(0..expected_excerpts.len());
5331                        ids_to_remove.push(excerpt_ids.remove(ix));
5332                        let (buffer, range) = expected_excerpts.remove(ix);
5333                        let buffer = buffer.read(cx);
5334                        log::info!(
5335                            "Removing excerpt {}: {:?}",
5336                            ix,
5337                            buffer
5338                                .text_for_range(range.to_offset(buffer))
5339                                .collect::<String>(),
5340                        );
5341                    }
5342                    let snapshot = multibuffer.read(cx).read(cx);
5343                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
5344                    drop(snapshot);
5345                    multibuffer.update(cx, |multibuffer, cx| {
5346                        multibuffer.remove_excerpts(ids_to_remove, cx)
5347                    });
5348                }
5349                30..=39 if !expected_excerpts.is_empty() => {
5350                    let multibuffer = multibuffer.read(cx).read(cx);
5351                    let offset =
5352                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
5353                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
5354                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
5355                    anchors.push(multibuffer.anchor_at(offset, bias));
5356                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
5357                }
5358                40..=44 if !anchors.is_empty() => {
5359                    let multibuffer = multibuffer.read(cx).read(cx);
5360                    let prev_len = anchors.len();
5361                    anchors = multibuffer
5362                        .refresh_anchors(&anchors)
5363                        .into_iter()
5364                        .map(|a| a.1)
5365                        .collect();
5366
5367                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
5368                    // overshoot its boundaries.
5369                    assert_eq!(anchors.len(), prev_len);
5370                    for anchor in &anchors {
5371                        if anchor.excerpt_id == ExcerptId::min()
5372                            || anchor.excerpt_id == ExcerptId::max()
5373                        {
5374                            continue;
5375                        }
5376
5377                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
5378                        assert_eq!(excerpt.id, anchor.excerpt_id);
5379                        assert!(excerpt.contains(anchor));
5380                    }
5381                }
5382                _ => {
5383                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
5384                        let base_text = util::RandomCharIter::new(&mut rng)
5385                            .take(25)
5386                            .collect::<String>();
5387
5388                        buffers.push(cx.new_model(|cx| Buffer::local(base_text, cx)));
5389                        buffers.last().unwrap()
5390                    } else {
5391                        buffers.choose(&mut rng).unwrap()
5392                    };
5393
5394                    let buffer = buffer_handle.read(cx);
5395                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
5396                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5397                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
5398                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
5399                    let prev_excerpt_id = excerpt_ids
5400                        .get(prev_excerpt_ix)
5401                        .cloned()
5402                        .unwrap_or_else(ExcerptId::max);
5403                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
5404
5405                    log::info!(
5406                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
5407                        excerpt_ix,
5408                        expected_excerpts.len(),
5409                        buffer_handle.read(cx).remote_id(),
5410                        buffer.text(),
5411                        start_ix..end_ix,
5412                        &buffer.text()[start_ix..end_ix]
5413                    );
5414
5415                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
5416                        multibuffer
5417                            .insert_excerpts_after(
5418                                prev_excerpt_id,
5419                                buffer_handle.clone(),
5420                                [ExcerptRange {
5421                                    context: start_ix..end_ix,
5422                                    primary: None,
5423                                }],
5424                                cx,
5425                            )
5426                            .pop()
5427                            .unwrap()
5428                    });
5429
5430                    excerpt_ids.insert(excerpt_ix, excerpt_id);
5431                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5432                }
5433            }
5434
5435            if rng.gen_bool(0.3) {
5436                multibuffer.update(cx, |multibuffer, cx| {
5437                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5438                })
5439            }
5440
5441            let snapshot = multibuffer.read(cx).snapshot(cx);
5442
5443            let mut excerpt_starts = Vec::new();
5444            let mut expected_text = String::new();
5445            let mut expected_buffer_rows = Vec::new();
5446            for (buffer, range) in &expected_excerpts {
5447                let buffer = buffer.read(cx);
5448                let buffer_range = range.to_offset(buffer);
5449
5450                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5451                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5452                expected_text.push('\n');
5453
5454                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5455                    ..=buffer.offset_to_point(buffer_range.end).row;
5456                for row in buffer_row_range {
5457                    expected_buffer_rows.push(Some(row));
5458                }
5459            }
5460            // Remove final trailing newline.
5461            if !expected_excerpts.is_empty() {
5462                expected_text.pop();
5463            }
5464
5465            // Always report one buffer row
5466            if expected_buffer_rows.is_empty() {
5467                expected_buffer_rows.push(Some(0));
5468            }
5469
5470            assert_eq!(snapshot.text(), expected_text);
5471            log::info!("MultiBuffer text: {:?}", expected_text);
5472
5473            assert_eq!(
5474                snapshot.buffer_rows(0).collect::<Vec<_>>(),
5475                expected_buffer_rows,
5476            );
5477
5478            for _ in 0..5 {
5479                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5480                assert_eq!(
5481                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
5482                    &expected_buffer_rows[start_row..],
5483                    "buffer_rows({})",
5484                    start_row
5485                );
5486            }
5487
5488            assert_eq!(
5489                snapshot.max_buffer_row(),
5490                expected_buffer_rows.into_iter().flatten().max().unwrap()
5491            );
5492
5493            let mut excerpt_starts = excerpt_starts.into_iter();
5494            for (buffer, range) in &expected_excerpts {
5495                let buffer = buffer.read(cx);
5496                let buffer_id = buffer.remote_id();
5497                let buffer_range = range.to_offset(buffer);
5498                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5499                let buffer_start_point_utf16 =
5500                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5501
5502                let excerpt_start = excerpt_starts.next().unwrap();
5503                let mut offset = excerpt_start.len;
5504                let mut buffer_offset = buffer_range.start;
5505                let mut point = excerpt_start.lines;
5506                let mut buffer_point = buffer_start_point;
5507                let mut point_utf16 = excerpt_start.lines_utf16();
5508                let mut buffer_point_utf16 = buffer_start_point_utf16;
5509                for ch in buffer
5510                    .snapshot()
5511                    .chunks(buffer_range.clone(), false)
5512                    .flat_map(|c| c.text.chars())
5513                {
5514                    for _ in 0..ch.len_utf8() {
5515                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
5516                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
5517                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5518                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5519                        assert_eq!(
5520                            left_offset,
5521                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
5522                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5523                            offset,
5524                            buffer_id,
5525                            buffer_offset,
5526                        );
5527                        assert_eq!(
5528                            right_offset,
5529                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
5530                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5531                            offset,
5532                            buffer_id,
5533                            buffer_offset,
5534                        );
5535
5536                        let left_point = snapshot.clip_point(point, Bias::Left);
5537                        let right_point = snapshot.clip_point(point, Bias::Right);
5538                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5539                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5540                        assert_eq!(
5541                            left_point,
5542                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
5543                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5544                            point,
5545                            buffer_id,
5546                            buffer_point,
5547                        );
5548                        assert_eq!(
5549                            right_point,
5550                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
5551                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5552                            point,
5553                            buffer_id,
5554                            buffer_point,
5555                        );
5556
5557                        assert_eq!(
5558                            snapshot.point_to_offset(left_point),
5559                            left_offset,
5560                            "point_to_offset({:?})",
5561                            left_point,
5562                        );
5563                        assert_eq!(
5564                            snapshot.offset_to_point(left_offset),
5565                            left_point,
5566                            "offset_to_point({:?})",
5567                            left_offset,
5568                        );
5569
5570                        offset += 1;
5571                        buffer_offset += 1;
5572                        if ch == '\n' {
5573                            point += Point::new(1, 0);
5574                            buffer_point += Point::new(1, 0);
5575                        } else {
5576                            point += Point::new(0, 1);
5577                            buffer_point += Point::new(0, 1);
5578                        }
5579                    }
5580
5581                    for _ in 0..ch.len_utf16() {
5582                        let left_point_utf16 =
5583                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5584                        let right_point_utf16 =
5585                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5586                        let buffer_left_point_utf16 =
5587                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5588                        let buffer_right_point_utf16 =
5589                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5590                        assert_eq!(
5591                            left_point_utf16,
5592                            excerpt_start.lines_utf16()
5593                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
5594                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5595                            point_utf16,
5596                            buffer_id,
5597                            buffer_point_utf16,
5598                        );
5599                        assert_eq!(
5600                            right_point_utf16,
5601                            excerpt_start.lines_utf16()
5602                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
5603                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5604                            point_utf16,
5605                            buffer_id,
5606                            buffer_point_utf16,
5607                        );
5608
5609                        if ch == '\n' {
5610                            point_utf16 += PointUtf16::new(1, 0);
5611                            buffer_point_utf16 += PointUtf16::new(1, 0);
5612                        } else {
5613                            point_utf16 += PointUtf16::new(0, 1);
5614                            buffer_point_utf16 += PointUtf16::new(0, 1);
5615                        }
5616                    }
5617                }
5618            }
5619
5620            for (row, line) in expected_text.split('\n').enumerate() {
5621                assert_eq!(
5622                    snapshot.line_len(row as u32),
5623                    line.len() as u32,
5624                    "line_len({}).",
5625                    row
5626                );
5627            }
5628
5629            let text_rope = Rope::from(expected_text.as_str());
5630            for _ in 0..10 {
5631                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5632                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5633
5634                let text_for_range = snapshot
5635                    .text_for_range(start_ix..end_ix)
5636                    .collect::<String>();
5637                assert_eq!(
5638                    text_for_range,
5639                    &expected_text[start_ix..end_ix],
5640                    "incorrect text for range {:?}",
5641                    start_ix..end_ix
5642                );
5643
5644                let excerpted_buffer_ranges = multibuffer
5645                    .read(cx)
5646                    .range_to_buffer_ranges(start_ix..end_ix, cx);
5647                let excerpted_buffers_text = excerpted_buffer_ranges
5648                    .iter()
5649                    .map(|(buffer, buffer_range, _)| {
5650                        buffer
5651                            .read(cx)
5652                            .text_for_range(buffer_range.clone())
5653                            .collect::<String>()
5654                    })
5655                    .collect::<Vec<_>>()
5656                    .join("\n");
5657                assert_eq!(excerpted_buffers_text, text_for_range);
5658                if !expected_excerpts.is_empty() {
5659                    assert!(!excerpted_buffer_ranges.is_empty());
5660                }
5661
5662                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5663                assert_eq!(
5664                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5665                    expected_summary,
5666                    "incorrect summary for range {:?}",
5667                    start_ix..end_ix
5668                );
5669            }
5670
5671            // Anchor resolution
5672            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5673            assert_eq!(anchors.len(), summaries.len());
5674            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5675                assert!(resolved_offset <= snapshot.len());
5676                assert_eq!(
5677                    snapshot.summary_for_anchor::<usize>(anchor),
5678                    resolved_offset
5679                );
5680            }
5681
5682            for _ in 0..10 {
5683                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5684                assert_eq!(
5685                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
5686                    expected_text[..end_ix].chars().rev().collect::<String>(),
5687                );
5688            }
5689
5690            for _ in 0..10 {
5691                let end_ix = rng.gen_range(0..=text_rope.len());
5692                let start_ix = rng.gen_range(0..=end_ix);
5693                assert_eq!(
5694                    snapshot
5695                        .bytes_in_range(start_ix..end_ix)
5696                        .flatten()
5697                        .copied()
5698                        .collect::<Vec<_>>(),
5699                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5700                    "bytes_in_range({:?})",
5701                    start_ix..end_ix,
5702                );
5703            }
5704        }
5705
5706        let snapshot = multibuffer.read(cx).snapshot(cx);
5707        for (old_snapshot, subscription) in old_versions {
5708            let edits = subscription.consume().into_inner();
5709
5710            log::info!(
5711                "applying subscription edits to old text: {:?}: {:?}",
5712                old_snapshot.text(),
5713                edits,
5714            );
5715
5716            let mut text = old_snapshot.text();
5717            for edit in edits {
5718                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5719                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5720            }
5721            assert_eq!(text.to_string(), snapshot.text());
5722        }
5723    }
5724
5725    #[gpui::test]
5726    fn test_history(cx: &mut AppContext) {
5727        let test_settings = SettingsStore::test(cx);
5728        cx.set_global(test_settings);
5729
5730        let buffer_1 = cx.new_model(|cx| Buffer::local("1234", cx));
5731        let buffer_2 = cx.new_model(|cx| Buffer::local("5678", cx));
5732        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5733        let group_interval = multibuffer.read(cx).history.group_interval;
5734        multibuffer.update(cx, |multibuffer, cx| {
5735            multibuffer.push_excerpts(
5736                buffer_1.clone(),
5737                [ExcerptRange {
5738                    context: 0..buffer_1.read(cx).len(),
5739                    primary: None,
5740                }],
5741                cx,
5742            );
5743            multibuffer.push_excerpts(
5744                buffer_2.clone(),
5745                [ExcerptRange {
5746                    context: 0..buffer_2.read(cx).len(),
5747                    primary: None,
5748                }],
5749                cx,
5750            );
5751        });
5752
5753        let mut now = Instant::now();
5754
5755        multibuffer.update(cx, |multibuffer, cx| {
5756            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5757            multibuffer.edit(
5758                [
5759                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5760                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5761                ],
5762                None,
5763                cx,
5764            );
5765            multibuffer.edit(
5766                [
5767                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5768                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5769                ],
5770                None,
5771                cx,
5772            );
5773            multibuffer.end_transaction_at(now, cx);
5774            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5775
5776            // Edit buffer 1 through the multibuffer
5777            now += 2 * group_interval;
5778            multibuffer.start_transaction_at(now, cx);
5779            multibuffer.edit([(2..2, "C")], None, cx);
5780            multibuffer.end_transaction_at(now, cx);
5781            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5782
5783            // Edit buffer 1 independently
5784            buffer_1.update(cx, |buffer_1, cx| {
5785                buffer_1.start_transaction_at(now);
5786                buffer_1.edit([(3..3, "D")], None, cx);
5787                buffer_1.end_transaction_at(now, cx);
5788
5789                now += 2 * group_interval;
5790                buffer_1.start_transaction_at(now);
5791                buffer_1.edit([(4..4, "E")], None, cx);
5792                buffer_1.end_transaction_at(now, cx);
5793            });
5794            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5795
5796            // An undo in the multibuffer undoes the multibuffer transaction
5797            // and also any individual buffer edits that have occurred since
5798            // that transaction.
5799            multibuffer.undo(cx);
5800            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5801
5802            multibuffer.undo(cx);
5803            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5804
5805            multibuffer.redo(cx);
5806            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5807
5808            multibuffer.redo(cx);
5809            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5810
5811            // Undo buffer 2 independently.
5812            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5813            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5814
5815            // An undo in the multibuffer undoes the components of the
5816            // the last multibuffer transaction that are not already undone.
5817            multibuffer.undo(cx);
5818            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5819
5820            multibuffer.undo(cx);
5821            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5822
5823            multibuffer.redo(cx);
5824            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5825
5826            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5827            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5828
5829            // Redo stack gets cleared after an edit.
5830            now += 2 * group_interval;
5831            multibuffer.start_transaction_at(now, cx);
5832            multibuffer.edit([(0..0, "X")], None, cx);
5833            multibuffer.end_transaction_at(now, cx);
5834            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5835            multibuffer.redo(cx);
5836            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5837            multibuffer.undo(cx);
5838            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5839            multibuffer.undo(cx);
5840            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5841
5842            // Transactions can be grouped manually.
5843            multibuffer.redo(cx);
5844            multibuffer.redo(cx);
5845            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5846            multibuffer.group_until_transaction(transaction_1, cx);
5847            multibuffer.undo(cx);
5848            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5849            multibuffer.redo(cx);
5850            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5851        });
5852    }
5853}