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