multi_buffer.rs

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