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