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