multi_buffer.rs

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