multi_buffer.rs

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