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