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