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(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                    if 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                    }
1362
1363                    break;
1364                }
1365
1366                // When removing the last excerpt, remove the trailing newline from
1367                // the previous excerpt.
1368                if cursor.item().is_none() && old_start > 0 {
1369                    old_start -= 1;
1370                    new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
1371                }
1372
1373                // Push an edit for the removal of this run of excerpts.
1374                let old_end = cursor.start().1;
1375                let new_start = new_excerpts.summary().text.len;
1376                edits.push(Edit {
1377                    old: old_start..old_end,
1378                    new: new_start..new_start,
1379                });
1380            }
1381        }
1382        let suffix = cursor.suffix(&());
1383        let changed_trailing_excerpt = suffix.is_empty();
1384        new_excerpts.append(suffix, &());
1385        drop(cursor);
1386        snapshot.excerpts = new_excerpts;
1387
1388        if changed_trailing_excerpt {
1389            snapshot.trailing_excerpt_update_count += 1;
1390        }
1391
1392        self.subscriptions.publish_mut(edits);
1393        cx.emit(Event::Edited {
1394            singleton_buffer_edited: false,
1395        });
1396        cx.emit(Event::ExcerptsRemoved { ids });
1397        cx.notify();
1398    }
1399
1400    pub fn wait_for_anchors<'a>(
1401        &self,
1402        anchors: impl 'a + Iterator<Item = Anchor>,
1403        cx: &mut ModelContext<Self>,
1404    ) -> impl 'static + Future<Output = Result<()>> {
1405        let borrow = self.buffers.borrow();
1406        let mut error = None;
1407        let mut futures = Vec::new();
1408        for anchor in anchors {
1409            if let Some(buffer_id) = anchor.buffer_id {
1410                if let Some(buffer) = borrow.get(&buffer_id) {
1411                    buffer.buffer.update(cx, |buffer, _| {
1412                        futures.push(buffer.wait_for_anchors([anchor.text_anchor]))
1413                    });
1414                } else {
1415                    error = Some(anyhow!(
1416                        "buffer {buffer_id} is not part of this multi-buffer"
1417                    ));
1418                    break;
1419                }
1420            }
1421        }
1422        async move {
1423            if let Some(error) = error {
1424                Err(error)?;
1425            }
1426            for future in futures {
1427                future.await?;
1428            }
1429            Ok(())
1430        }
1431    }
1432
1433    pub fn text_anchor_for_position<T: ToOffset>(
1434        &self,
1435        position: T,
1436        cx: &AppContext,
1437    ) -> Option<(Model<Buffer>, language::Anchor)> {
1438        let snapshot = self.read(cx);
1439        let anchor = snapshot.anchor_before(position);
1440        let buffer = self
1441            .buffers
1442            .borrow()
1443            .get(&anchor.buffer_id?)?
1444            .buffer
1445            .clone();
1446        Some((buffer, anchor.text_anchor))
1447    }
1448
1449    fn on_buffer_event(
1450        &mut self,
1451        buffer: Model<Buffer>,
1452        event: &language::Event,
1453        cx: &mut ModelContext<Self>,
1454    ) {
1455        cx.emit(match event {
1456            language::Event::Edited => Event::Edited {
1457                singleton_buffer_edited: true,
1458            },
1459            language::Event::DirtyChanged => Event::DirtyChanged,
1460            language::Event::Saved => Event::Saved,
1461            language::Event::FileHandleChanged => Event::FileHandleChanged,
1462            language::Event::Reloaded => Event::Reloaded,
1463            language::Event::DiffBaseChanged => Event::DiffBaseChanged,
1464            language::Event::LanguageChanged => Event::LanguageChanged,
1465            language::Event::Reparsed => Event::Reparsed,
1466            language::Event::DiagnosticsUpdated => Event::DiagnosticsUpdated,
1467            language::Event::Closed => Event::Closed,
1468            language::Event::CapabilityChanged => {
1469                self.capability = buffer.read(cx).capability();
1470                Event::CapabilityChanged
1471            }
1472
1473            //
1474            language::Event::Operation(_) => return,
1475        });
1476    }
1477
1478    pub fn all_buffers(&self) -> HashSet<Model<Buffer>> {
1479        self.buffers
1480            .borrow()
1481            .values()
1482            .map(|state| state.buffer.clone())
1483            .collect()
1484    }
1485
1486    pub fn buffer(&self, buffer_id: BufferId) -> Option<Model<Buffer>> {
1487        self.buffers
1488            .borrow()
1489            .get(&buffer_id)
1490            .map(|state| state.buffer.clone())
1491    }
1492
1493    pub fn is_completion_trigger(&self, position: Anchor, text: &str, cx: &AppContext) -> bool {
1494        let mut chars = text.chars();
1495        let char = if let Some(char) = chars.next() {
1496            char
1497        } else {
1498            return false;
1499        };
1500        if chars.next().is_some() {
1501            return false;
1502        }
1503
1504        let snapshot = self.snapshot(cx);
1505        let position = position.to_offset(&snapshot);
1506        let scope = snapshot.language_scope_at(position);
1507        if char_kind(&scope, char) == CharKind::Word {
1508            return true;
1509        }
1510
1511        let anchor = snapshot.anchor_before(position);
1512        anchor
1513            .buffer_id
1514            .and_then(|buffer_id| {
1515                let buffer = self.buffers.borrow().get(&buffer_id)?.buffer.clone();
1516                Some(
1517                    buffer
1518                        .read(cx)
1519                        .completion_triggers()
1520                        .iter()
1521                        .any(|string| string == text),
1522                )
1523            })
1524            .unwrap_or(false)
1525    }
1526
1527    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1528        self.point_to_buffer_offset(point, cx)
1529            .and_then(|(buffer, offset, _)| buffer.read(cx).language_at(offset))
1530    }
1531
1532    pub fn settings_at<'a, T: ToOffset>(
1533        &self,
1534        point: T,
1535        cx: &'a AppContext,
1536    ) -> &'a LanguageSettings {
1537        let mut language = None;
1538        let mut file = None;
1539        if let Some((buffer, offset, _)) = self.point_to_buffer_offset(point, cx) {
1540            let buffer = buffer.read(cx);
1541            language = buffer.language_at(offset);
1542            file = buffer.file();
1543        }
1544        language_settings(language.as_ref(), file, cx)
1545    }
1546
1547    pub fn for_each_buffer(&self, mut f: impl FnMut(&Model<Buffer>)) {
1548        self.buffers
1549            .borrow()
1550            .values()
1551            .for_each(|state| f(&state.buffer))
1552    }
1553
1554    pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1555        if let Some(title) = self.title.as_ref() {
1556            return title.into();
1557        }
1558
1559        if let Some(buffer) = self.as_singleton() {
1560            if let Some(file) = buffer.read(cx).file() {
1561                return file.file_name(cx).to_string_lossy();
1562            }
1563        }
1564
1565        "untitled".into()
1566    }
1567
1568    #[cfg(any(test, feature = "test-support"))]
1569    pub fn is_parsing(&self, cx: &AppContext) -> bool {
1570        self.as_singleton().unwrap().read(cx).is_parsing()
1571    }
1572
1573    fn sync(&self, cx: &AppContext) {
1574        let mut snapshot = self.snapshot.borrow_mut();
1575        let mut excerpts_to_edit = Vec::new();
1576        let mut reparsed = false;
1577        let mut diagnostics_updated = false;
1578        let mut git_diff_updated = false;
1579        let mut is_dirty = false;
1580        let mut has_conflict = false;
1581        let mut edited = false;
1582        let mut buffers = self.buffers.borrow_mut();
1583        for buffer_state in buffers.values_mut() {
1584            let buffer = buffer_state.buffer.read(cx);
1585            let version = buffer.version();
1586            let parse_count = buffer.parse_count();
1587            let selections_update_count = buffer.selections_update_count();
1588            let diagnostics_update_count = buffer.diagnostics_update_count();
1589            let file_update_count = buffer.file_update_count();
1590            let git_diff_update_count = buffer.git_diff_update_count();
1591
1592            let buffer_edited = version.changed_since(&buffer_state.last_version);
1593            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1594            let buffer_selections_updated =
1595                selections_update_count > buffer_state.last_selections_update_count;
1596            let buffer_diagnostics_updated =
1597                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1598            let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1599            let buffer_git_diff_updated =
1600                git_diff_update_count > buffer_state.last_git_diff_update_count;
1601            if buffer_edited
1602                || buffer_reparsed
1603                || buffer_selections_updated
1604                || buffer_diagnostics_updated
1605                || buffer_file_updated
1606                || buffer_git_diff_updated
1607            {
1608                buffer_state.last_version = version;
1609                buffer_state.last_parse_count = parse_count;
1610                buffer_state.last_selections_update_count = selections_update_count;
1611                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1612                buffer_state.last_file_update_count = file_update_count;
1613                buffer_state.last_git_diff_update_count = git_diff_update_count;
1614                excerpts_to_edit.extend(
1615                    buffer_state
1616                        .excerpts
1617                        .iter()
1618                        .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1619                );
1620            }
1621
1622            edited |= buffer_edited;
1623            reparsed |= buffer_reparsed;
1624            diagnostics_updated |= buffer_diagnostics_updated;
1625            git_diff_updated |= buffer_git_diff_updated;
1626            is_dirty |= buffer.is_dirty();
1627            has_conflict |= buffer.has_conflict();
1628        }
1629        if edited {
1630            snapshot.edit_count += 1;
1631        }
1632        if reparsed {
1633            snapshot.parse_count += 1;
1634        }
1635        if diagnostics_updated {
1636            snapshot.diagnostics_update_count += 1;
1637        }
1638        if git_diff_updated {
1639            snapshot.git_diff_update_count += 1;
1640        }
1641        snapshot.is_dirty = is_dirty;
1642        snapshot.has_conflict = has_conflict;
1643
1644        excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1645
1646        let mut edits = Vec::new();
1647        let mut new_excerpts = SumTree::new();
1648        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1649
1650        for (locator, buffer, buffer_edited) in excerpts_to_edit {
1651            new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
1652            let old_excerpt = cursor.item().unwrap();
1653            let buffer = buffer.read(cx);
1654            let buffer_id = buffer.remote_id();
1655
1656            let mut new_excerpt;
1657            if buffer_edited {
1658                edits.extend(
1659                    buffer
1660                        .edits_since_in_range::<usize>(
1661                            old_excerpt.buffer.version(),
1662                            old_excerpt.range.context.clone(),
1663                        )
1664                        .map(|mut edit| {
1665                            let excerpt_old_start = cursor.start().1;
1666                            let excerpt_new_start = new_excerpts.summary().text.len;
1667                            edit.old.start += excerpt_old_start;
1668                            edit.old.end += excerpt_old_start;
1669                            edit.new.start += excerpt_new_start;
1670                            edit.new.end += excerpt_new_start;
1671                            edit
1672                        }),
1673                );
1674
1675                new_excerpt = Excerpt::new(
1676                    old_excerpt.id,
1677                    locator.clone(),
1678                    buffer_id,
1679                    buffer.snapshot(),
1680                    old_excerpt.range.clone(),
1681                    old_excerpt.has_trailing_newline,
1682                );
1683            } else {
1684                new_excerpt = old_excerpt.clone();
1685                new_excerpt.buffer = buffer.snapshot();
1686            }
1687
1688            new_excerpts.push(new_excerpt, &());
1689            cursor.next(&());
1690        }
1691        new_excerpts.append(cursor.suffix(&()), &());
1692
1693        drop(cursor);
1694        snapshot.excerpts = new_excerpts;
1695
1696        self.subscriptions.publish(edits);
1697    }
1698}
1699
1700#[cfg(any(test, feature = "test-support"))]
1701impl MultiBuffer {
1702    pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> Model<Self> {
1703        let buffer = cx
1704            .new_model(|cx| Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text));
1705        cx.new_model(|cx| Self::singleton(buffer, cx))
1706    }
1707
1708    pub fn build_multi<const COUNT: usize>(
1709        excerpts: [(&str, Vec<Range<Point>>); COUNT],
1710        cx: &mut gpui::AppContext,
1711    ) -> Model<Self> {
1712        let multi = cx.new_model(|_| Self::new(0, Capability::ReadWrite));
1713        for (text, ranges) in excerpts {
1714            let buffer = cx.new_model(|cx| {
1715                Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
1716            });
1717            let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
1718                context: range,
1719                primary: None,
1720            });
1721            multi.update(cx, |multi, cx| {
1722                multi.push_excerpts(buffer, excerpt_ranges, cx)
1723            });
1724        }
1725
1726        multi
1727    }
1728
1729    pub fn build_from_buffer(buffer: Model<Buffer>, cx: &mut gpui::AppContext) -> Model<Self> {
1730        cx.new_model(|cx| Self::singleton(buffer, cx))
1731    }
1732
1733    pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> Model<Self> {
1734        cx.new_model(|cx| {
1735            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
1736            let mutation_count = rng.gen_range(1..=5);
1737            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1738            multibuffer
1739        })
1740    }
1741
1742    pub fn randomly_edit(
1743        &mut self,
1744        rng: &mut impl rand::Rng,
1745        edit_count: usize,
1746        cx: &mut ModelContext<Self>,
1747    ) {
1748        use util::RandomCharIter;
1749
1750        let snapshot = self.read(cx);
1751        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1752        let mut last_end = None;
1753        for _ in 0..edit_count {
1754            if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1755                break;
1756            }
1757
1758            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1759            let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1760            let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1761            last_end = Some(end);
1762
1763            let mut range = start..end;
1764            if rng.gen_bool(0.2) {
1765                mem::swap(&mut range.start, &mut range.end);
1766            }
1767
1768            let new_text_len = rng.gen_range(0..10);
1769            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1770
1771            edits.push((range, new_text.into()));
1772        }
1773        log::info!("mutating multi-buffer with {:?}", edits);
1774        drop(snapshot);
1775
1776        self.edit(edits, None, cx);
1777    }
1778
1779    pub fn randomly_edit_excerpts(
1780        &mut self,
1781        rng: &mut impl rand::Rng,
1782        mutation_count: usize,
1783        cx: &mut ModelContext<Self>,
1784    ) {
1785        use rand::prelude::*;
1786        use std::env;
1787        use util::RandomCharIter;
1788
1789        let max_excerpts = env::var("MAX_EXCERPTS")
1790            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1791            .unwrap_or(5);
1792
1793        let mut buffers = Vec::new();
1794        for _ in 0..mutation_count {
1795            if rng.gen_bool(0.05) {
1796                log::info!("Clearing multi-buffer");
1797                self.clear(cx);
1798                continue;
1799            }
1800
1801            let excerpt_ids = self.excerpt_ids();
1802            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1803                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1804                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1805                    buffers.push(cx.new_model(|cx| {
1806                        Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), text)
1807                    }));
1808                    let buffer = buffers.last().unwrap().read(cx);
1809                    log::info!(
1810                        "Creating new buffer {} with text: {:?}",
1811                        buffer.remote_id(),
1812                        buffer.text()
1813                    );
1814                    buffers.last().unwrap().clone()
1815                } else {
1816                    self.buffers
1817                        .borrow()
1818                        .values()
1819                        .choose(rng)
1820                        .unwrap()
1821                        .buffer
1822                        .clone()
1823                };
1824
1825                let buffer = buffer_handle.read(cx);
1826                let buffer_text = buffer.text();
1827                let ranges = (0..rng.gen_range(0..5))
1828                    .map(|_| {
1829                        let end_ix =
1830                            buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1831                        let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1832                        ExcerptRange {
1833                            context: start_ix..end_ix,
1834                            primary: None,
1835                        }
1836                    })
1837                    .collect::<Vec<_>>();
1838                log::info!(
1839                    "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1840                    buffer_handle.read(cx).remote_id(),
1841                    ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1842                    ranges
1843                        .iter()
1844                        .map(|r| &buffer_text[r.context.clone()])
1845                        .collect::<Vec<_>>()
1846                );
1847
1848                let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1849                log::info!("Inserted with ids: {:?}", excerpt_id);
1850            } else {
1851                let remove_count = rng.gen_range(1..=excerpt_ids.len());
1852                let mut excerpts_to_remove = excerpt_ids
1853                    .choose_multiple(rng, remove_count)
1854                    .cloned()
1855                    .collect::<Vec<_>>();
1856                let snapshot = self.snapshot.borrow();
1857                excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
1858                drop(snapshot);
1859                log::info!("Removing excerpts {:?}", excerpts_to_remove);
1860                self.remove_excerpts(excerpts_to_remove, cx);
1861            }
1862        }
1863    }
1864
1865    pub fn randomly_mutate(
1866        &mut self,
1867        rng: &mut impl rand::Rng,
1868        mutation_count: usize,
1869        cx: &mut ModelContext<Self>,
1870    ) {
1871        use rand::prelude::*;
1872
1873        if rng.gen_bool(0.7) || self.singleton {
1874            let buffer = self
1875                .buffers
1876                .borrow()
1877                .values()
1878                .choose(rng)
1879                .map(|state| state.buffer.clone());
1880
1881            if let Some(buffer) = buffer {
1882                buffer.update(cx, |buffer, cx| {
1883                    if rng.gen() {
1884                        buffer.randomly_edit(rng, mutation_count, cx);
1885                    } else {
1886                        buffer.randomly_undo_redo(rng, cx);
1887                    }
1888                });
1889            } else {
1890                self.randomly_edit(rng, mutation_count, cx);
1891            }
1892        } else {
1893            self.randomly_edit_excerpts(rng, mutation_count, cx);
1894        }
1895
1896        self.check_invariants(cx);
1897    }
1898
1899    fn check_invariants(&self, cx: &mut ModelContext<Self>) {
1900        let snapshot = self.read(cx);
1901        let excerpts = snapshot.excerpts.items(&());
1902        let excerpt_ids = snapshot.excerpt_ids.items(&());
1903
1904        for (ix, excerpt) in excerpts.iter().enumerate() {
1905            if ix == 0 {
1906                if excerpt.locator <= Locator::min() {
1907                    panic!("invalid first excerpt locator {:?}", excerpt.locator);
1908                }
1909            } else {
1910                if excerpt.locator <= excerpts[ix - 1].locator {
1911                    panic!("excerpts are out-of-order: {:?}", excerpts);
1912                }
1913            }
1914        }
1915
1916        for (ix, entry) in excerpt_ids.iter().enumerate() {
1917            if ix == 0 {
1918                if entry.id.cmp(&ExcerptId::min(), &snapshot).is_le() {
1919                    panic!("invalid first excerpt id {:?}", entry.id);
1920                }
1921            } else {
1922                if entry.id <= excerpt_ids[ix - 1].id {
1923                    panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
1924                }
1925            }
1926        }
1927    }
1928}
1929
1930impl EventEmitter<Event> for MultiBuffer {}
1931
1932impl MultiBufferSnapshot {
1933    pub fn text(&self) -> String {
1934        self.chunks(0..self.len(), false)
1935            .map(|chunk| chunk.text)
1936            .collect()
1937    }
1938
1939    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1940        let mut offset = position.to_offset(self);
1941        let mut cursor = self.excerpts.cursor::<usize>();
1942        cursor.seek(&offset, Bias::Left, &());
1943        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1944            let end_before_footer = cursor.start() + excerpt.text_summary.len;
1945            let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1946            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1947            excerpt.buffer.reversed_chunks_in_range(start..end)
1948        });
1949        iter::from_fn(move || {
1950            if offset == *cursor.start() {
1951                cursor.prev(&());
1952                let excerpt = cursor.item()?;
1953                excerpt_chunks = Some(
1954                    excerpt
1955                        .buffer
1956                        .reversed_chunks_in_range(excerpt.range.context.clone()),
1957                );
1958            }
1959
1960            let excerpt = cursor.item().unwrap();
1961            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1962                offset -= 1;
1963                Some("\n")
1964            } else {
1965                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1966                offset -= chunk.len();
1967                Some(chunk)
1968            }
1969        })
1970        .flat_map(|c| c.chars().rev())
1971    }
1972
1973    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1974        let offset = position.to_offset(self);
1975        self.text_for_range(offset..self.len())
1976            .flat_map(|chunk| chunk.chars())
1977    }
1978
1979    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
1980        self.chunks(range, false).map(|chunk| chunk.text)
1981    }
1982
1983    pub fn is_line_blank(&self, row: u32) -> bool {
1984        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1985            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1986    }
1987
1988    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1989    where
1990        T: ToOffset,
1991    {
1992        let position = position.to_offset(self);
1993        position == self.clip_offset(position, Bias::Left)
1994            && self
1995                .bytes_in_range(position..self.len())
1996                .flatten()
1997                .copied()
1998                .take(needle.len())
1999                .eq(needle.bytes())
2000    }
2001
2002    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
2003        let mut start = start.to_offset(self);
2004        let mut end = start;
2005        let mut next_chars = self.chars_at(start).peekable();
2006        let mut prev_chars = self.reversed_chars_at(start).peekable();
2007
2008        let scope = self.language_scope_at(start);
2009        let kind = |c| char_kind(&scope, c);
2010        let word_kind = cmp::max(
2011            prev_chars.peek().copied().map(kind),
2012            next_chars.peek().copied().map(kind),
2013        );
2014
2015        for ch in prev_chars {
2016            if Some(kind(ch)) == word_kind && ch != '\n' {
2017                start -= ch.len_utf8();
2018            } else {
2019                break;
2020            }
2021        }
2022
2023        for ch in next_chars {
2024            if Some(kind(ch)) == word_kind && ch != '\n' {
2025                end += ch.len_utf8();
2026            } else {
2027                break;
2028            }
2029        }
2030
2031        (start..end, word_kind)
2032    }
2033
2034    pub fn as_singleton(&self) -> Option<(&ExcerptId, BufferId, &BufferSnapshot)> {
2035        if self.singleton {
2036            self.excerpts
2037                .iter()
2038                .next()
2039                .map(|e| (&e.id, e.buffer_id, &e.buffer))
2040        } else {
2041            None
2042        }
2043    }
2044
2045    pub fn len(&self) -> usize {
2046        self.excerpts.summary().text.len
2047    }
2048
2049    pub fn is_empty(&self) -> bool {
2050        self.excerpts.summary().text.len == 0
2051    }
2052
2053    pub fn max_buffer_row(&self) -> u32 {
2054        self.excerpts.summary().max_buffer_row
2055    }
2056
2057    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
2058        if let Some((_, _, buffer)) = self.as_singleton() {
2059            return buffer.clip_offset(offset, bias);
2060        }
2061
2062        let mut cursor = self.excerpts.cursor::<usize>();
2063        cursor.seek(&offset, Bias::Right, &());
2064        let overshoot = if let Some(excerpt) = cursor.item() {
2065            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2066            let buffer_offset = excerpt
2067                .buffer
2068                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
2069            buffer_offset.saturating_sub(excerpt_start)
2070        } else {
2071            0
2072        };
2073        cursor.start() + overshoot
2074    }
2075
2076    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
2077        if let Some((_, _, buffer)) = self.as_singleton() {
2078            return buffer.clip_point(point, bias);
2079        }
2080
2081        let mut cursor = self.excerpts.cursor::<Point>();
2082        cursor.seek(&point, Bias::Right, &());
2083        let overshoot = if let Some(excerpt) = cursor.item() {
2084            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2085            let buffer_point = excerpt
2086                .buffer
2087                .clip_point(excerpt_start + (point - cursor.start()), bias);
2088            buffer_point.saturating_sub(excerpt_start)
2089        } else {
2090            Point::zero()
2091        };
2092        *cursor.start() + overshoot
2093    }
2094
2095    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
2096        if let Some((_, _, buffer)) = self.as_singleton() {
2097            return buffer.clip_offset_utf16(offset, bias);
2098        }
2099
2100        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
2101        cursor.seek(&offset, Bias::Right, &());
2102        let overshoot = if let Some(excerpt) = cursor.item() {
2103            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2104            let buffer_offset = excerpt
2105                .buffer
2106                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
2107            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
2108        } else {
2109            OffsetUtf16(0)
2110        };
2111        *cursor.start() + overshoot
2112    }
2113
2114    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
2115        if let Some((_, _, buffer)) = self.as_singleton() {
2116            return buffer.clip_point_utf16(point, bias);
2117        }
2118
2119        let mut cursor = self.excerpts.cursor::<PointUtf16>();
2120        cursor.seek(&point.0, Bias::Right, &());
2121        let overshoot = if let Some(excerpt) = cursor.item() {
2122            let excerpt_start = excerpt
2123                .buffer
2124                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2125            let buffer_point = excerpt
2126                .buffer
2127                .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
2128            buffer_point.saturating_sub(excerpt_start)
2129        } else {
2130            PointUtf16::zero()
2131        };
2132        *cursor.start() + overshoot
2133    }
2134
2135    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
2136        let range = range.start.to_offset(self)..range.end.to_offset(self);
2137        let mut excerpts = self.excerpts.cursor::<usize>();
2138        excerpts.seek(&range.start, Bias::Right, &());
2139
2140        let mut chunk = &[][..];
2141        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2142            let mut excerpt_bytes = excerpt
2143                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
2144            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2145            Some(excerpt_bytes)
2146        } else {
2147            None
2148        };
2149        MultiBufferBytes {
2150            range,
2151            excerpts,
2152            excerpt_bytes,
2153            chunk,
2154        }
2155    }
2156
2157    pub fn reversed_bytes_in_range<T: ToOffset>(
2158        &self,
2159        range: Range<T>,
2160    ) -> ReversedMultiBufferBytes {
2161        let range = range.start.to_offset(self)..range.end.to_offset(self);
2162        let mut excerpts = self.excerpts.cursor::<usize>();
2163        excerpts.seek(&range.end, Bias::Left, &());
2164
2165        let mut chunk = &[][..];
2166        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2167            let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
2168                range.start - excerpts.start()..range.end - excerpts.start(),
2169            );
2170            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2171            Some(excerpt_bytes)
2172        } else {
2173            None
2174        };
2175
2176        ReversedMultiBufferBytes {
2177            range,
2178            excerpts,
2179            excerpt_bytes,
2180            chunk,
2181        }
2182    }
2183
2184    pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
2185        let mut result = MultiBufferRows {
2186            buffer_row_range: 0..0,
2187            excerpts: self.excerpts.cursor(),
2188        };
2189        result.seek(start_row);
2190        result
2191    }
2192
2193    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
2194        let range = range.start.to_offset(self)..range.end.to_offset(self);
2195        let mut chunks = MultiBufferChunks {
2196            range: range.clone(),
2197            excerpts: self.excerpts.cursor(),
2198            excerpt_chunks: None,
2199            language_aware,
2200        };
2201        chunks.seek(range.start);
2202        chunks
2203    }
2204
2205    pub fn offset_to_point(&self, offset: usize) -> Point {
2206        if let Some((_, _, buffer)) = self.as_singleton() {
2207            return buffer.offset_to_point(offset);
2208        }
2209
2210        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2211        cursor.seek(&offset, Bias::Right, &());
2212        if let Some(excerpt) = cursor.item() {
2213            let (start_offset, start_point) = cursor.start();
2214            let overshoot = offset - start_offset;
2215            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2216            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2217            let buffer_point = excerpt
2218                .buffer
2219                .offset_to_point(excerpt_start_offset + overshoot);
2220            *start_point + (buffer_point - excerpt_start_point)
2221        } else {
2222            self.excerpts.summary().text.lines
2223        }
2224    }
2225
2226    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
2227        if let Some((_, _, buffer)) = self.as_singleton() {
2228            return buffer.offset_to_point_utf16(offset);
2229        }
2230
2231        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
2232        cursor.seek(&offset, Bias::Right, &());
2233        if let Some(excerpt) = cursor.item() {
2234            let (start_offset, start_point) = cursor.start();
2235            let overshoot = offset - start_offset;
2236            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2237            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2238            let buffer_point = excerpt
2239                .buffer
2240                .offset_to_point_utf16(excerpt_start_offset + overshoot);
2241            *start_point + (buffer_point - excerpt_start_point)
2242        } else {
2243            self.excerpts.summary().text.lines_utf16()
2244        }
2245    }
2246
2247    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
2248        if let Some((_, _, buffer)) = self.as_singleton() {
2249            return buffer.point_to_point_utf16(point);
2250        }
2251
2252        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
2253        cursor.seek(&point, Bias::Right, &());
2254        if let Some(excerpt) = cursor.item() {
2255            let (start_offset, start_point) = cursor.start();
2256            let overshoot = point - start_offset;
2257            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2258            let excerpt_start_point_utf16 =
2259                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2260            let buffer_point = excerpt
2261                .buffer
2262                .point_to_point_utf16(excerpt_start_point + overshoot);
2263            *start_point + (buffer_point - excerpt_start_point_utf16)
2264        } else {
2265            self.excerpts.summary().text.lines_utf16()
2266        }
2267    }
2268
2269    pub fn point_to_offset(&self, point: Point) -> usize {
2270        if let Some((_, _, buffer)) = self.as_singleton() {
2271            return buffer.point_to_offset(point);
2272        }
2273
2274        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2275        cursor.seek(&point, Bias::Right, &());
2276        if let Some(excerpt) = cursor.item() {
2277            let (start_point, start_offset) = cursor.start();
2278            let overshoot = point - start_point;
2279            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2280            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2281            let buffer_offset = excerpt
2282                .buffer
2283                .point_to_offset(excerpt_start_point + overshoot);
2284            *start_offset + buffer_offset - excerpt_start_offset
2285        } else {
2286            self.excerpts.summary().text.len
2287        }
2288    }
2289
2290    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2291        if let Some((_, _, buffer)) = self.as_singleton() {
2292            return buffer.offset_utf16_to_offset(offset_utf16);
2293        }
2294
2295        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2296        cursor.seek(&offset_utf16, Bias::Right, &());
2297        if let Some(excerpt) = cursor.item() {
2298            let (start_offset_utf16, start_offset) = cursor.start();
2299            let overshoot = offset_utf16 - start_offset_utf16;
2300            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2301            let excerpt_start_offset_utf16 =
2302                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2303            let buffer_offset = excerpt
2304                .buffer
2305                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2306            *start_offset + (buffer_offset - excerpt_start_offset)
2307        } else {
2308            self.excerpts.summary().text.len
2309        }
2310    }
2311
2312    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2313        if let Some((_, _, buffer)) = self.as_singleton() {
2314            return buffer.offset_to_offset_utf16(offset);
2315        }
2316
2317        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2318        cursor.seek(&offset, Bias::Right, &());
2319        if let Some(excerpt) = cursor.item() {
2320            let (start_offset, start_offset_utf16) = cursor.start();
2321            let overshoot = offset - start_offset;
2322            let excerpt_start_offset_utf16 =
2323                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2324            let excerpt_start_offset = excerpt
2325                .buffer
2326                .offset_utf16_to_offset(excerpt_start_offset_utf16);
2327            let buffer_offset_utf16 = excerpt
2328                .buffer
2329                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2330            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2331        } else {
2332            self.excerpts.summary().text.len_utf16
2333        }
2334    }
2335
2336    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2337        if let Some((_, _, buffer)) = self.as_singleton() {
2338            return buffer.point_utf16_to_offset(point);
2339        }
2340
2341        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2342        cursor.seek(&point, Bias::Right, &());
2343        if let Some(excerpt) = cursor.item() {
2344            let (start_point, start_offset) = cursor.start();
2345            let overshoot = point - start_point;
2346            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2347            let excerpt_start_point = excerpt
2348                .buffer
2349                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2350            let buffer_offset = excerpt
2351                .buffer
2352                .point_utf16_to_offset(excerpt_start_point + overshoot);
2353            *start_offset + (buffer_offset - excerpt_start_offset)
2354        } else {
2355            self.excerpts.summary().text.len
2356        }
2357    }
2358
2359    pub fn point_to_buffer_offset<T: ToOffset>(
2360        &self,
2361        point: T,
2362    ) -> Option<(&BufferSnapshot, usize)> {
2363        let offset = point.to_offset(self);
2364        let mut cursor = self.excerpts.cursor::<usize>();
2365        cursor.seek(&offset, Bias::Right, &());
2366        if cursor.item().is_none() {
2367            cursor.prev(&());
2368        }
2369
2370        cursor.item().map(|excerpt| {
2371            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2372            let buffer_point = excerpt_start + offset - *cursor.start();
2373            (&excerpt.buffer, buffer_point)
2374        })
2375    }
2376
2377    pub fn suggested_indents(
2378        &self,
2379        rows: impl IntoIterator<Item = u32>,
2380        cx: &AppContext,
2381    ) -> BTreeMap<u32, IndentSize> {
2382        let mut result = BTreeMap::new();
2383
2384        let mut rows_for_excerpt = Vec::new();
2385        let mut cursor = self.excerpts.cursor::<Point>();
2386        let mut rows = rows.into_iter().peekable();
2387        let mut prev_row = u32::MAX;
2388        let mut prev_language_indent_size = IndentSize::default();
2389
2390        while let Some(row) = rows.next() {
2391            cursor.seek(&Point::new(row, 0), Bias::Right, &());
2392            let excerpt = match cursor.item() {
2393                Some(excerpt) => excerpt,
2394                _ => continue,
2395            };
2396
2397            // Retrieve the language and indent size once for each disjoint region being indented.
2398            let single_indent_size = if row.saturating_sub(1) == prev_row {
2399                prev_language_indent_size
2400            } else {
2401                excerpt
2402                    .buffer
2403                    .language_indent_size_at(Point::new(row, 0), cx)
2404            };
2405            prev_language_indent_size = single_indent_size;
2406            prev_row = row;
2407
2408            let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2409            let start_multibuffer_row = cursor.start().row;
2410
2411            rows_for_excerpt.push(row);
2412            while let Some(next_row) = rows.peek().copied() {
2413                if cursor.end(&()).row > next_row {
2414                    rows_for_excerpt.push(next_row);
2415                    rows.next();
2416                } else {
2417                    break;
2418                }
2419            }
2420
2421            let buffer_rows = rows_for_excerpt
2422                .drain(..)
2423                .map(|row| start_buffer_row + row - start_multibuffer_row);
2424            let buffer_indents = excerpt
2425                .buffer
2426                .suggested_indents(buffer_rows, single_indent_size);
2427            let multibuffer_indents = buffer_indents
2428                .into_iter()
2429                .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2430            result.extend(multibuffer_indents);
2431        }
2432
2433        result
2434    }
2435
2436    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2437        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2438            let mut size = buffer.indent_size_for_line(range.start.row);
2439            size.len = size
2440                .len
2441                .min(range.end.column)
2442                .saturating_sub(range.start.column);
2443            size
2444        } else {
2445            IndentSize::spaces(0)
2446        }
2447    }
2448
2449    pub fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
2450        while row > 0 {
2451            row -= 1;
2452            if !self.is_line_blank(row) {
2453                return Some(row);
2454            }
2455        }
2456        None
2457    }
2458
2459    pub fn line_len(&self, row: u32) -> u32 {
2460        if let Some((_, range)) = self.buffer_line_for_row(row) {
2461            range.end.column - range.start.column
2462        } else {
2463            0
2464        }
2465    }
2466
2467    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2468        let mut cursor = self.excerpts.cursor::<Point>();
2469        let point = Point::new(row, 0);
2470        cursor.seek(&point, Bias::Right, &());
2471        if cursor.item().is_none() && *cursor.start() == point {
2472            cursor.prev(&());
2473        }
2474        if let Some(excerpt) = cursor.item() {
2475            let overshoot = row - cursor.start().row;
2476            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2477            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2478            let buffer_row = excerpt_start.row + overshoot;
2479            let line_start = Point::new(buffer_row, 0);
2480            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2481            return Some((
2482                &excerpt.buffer,
2483                line_start.max(excerpt_start)..line_end.min(excerpt_end),
2484            ));
2485        }
2486        None
2487    }
2488
2489    pub fn max_point(&self) -> Point {
2490        self.text_summary().lines
2491    }
2492
2493    pub fn text_summary(&self) -> TextSummary {
2494        self.excerpts.summary().text.clone()
2495    }
2496
2497    pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2498    where
2499        D: TextDimension,
2500        O: ToOffset,
2501    {
2502        let mut summary = D::default();
2503        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2504        let mut cursor = self.excerpts.cursor::<usize>();
2505        cursor.seek(&range.start, Bias::Right, &());
2506        if let Some(excerpt) = cursor.item() {
2507            let mut end_before_newline = cursor.end(&());
2508            if excerpt.has_trailing_newline {
2509                end_before_newline -= 1;
2510            }
2511
2512            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2513            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2514            let end_in_excerpt =
2515                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2516            summary.add_assign(
2517                &excerpt
2518                    .buffer
2519                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2520            );
2521
2522            if range.end > end_before_newline {
2523                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2524            }
2525
2526            cursor.next(&());
2527        }
2528
2529        if range.end > *cursor.start() {
2530            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2531                &range.end,
2532                Bias::Right,
2533                &(),
2534            )));
2535            if let Some(excerpt) = cursor.item() {
2536                range.end = cmp::max(*cursor.start(), range.end);
2537
2538                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2539                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2540                summary.add_assign(
2541                    &excerpt
2542                        .buffer
2543                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2544                );
2545            }
2546        }
2547
2548        summary
2549    }
2550
2551    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2552    where
2553        D: TextDimension + Ord + Sub<D, Output = D>,
2554    {
2555        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2556        let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2557
2558        cursor.seek(locator, Bias::Left, &());
2559        if cursor.item().is_none() {
2560            cursor.next(&());
2561        }
2562
2563        let mut position = D::from_text_summary(&cursor.start().text);
2564        if let Some(excerpt) = cursor.item() {
2565            if excerpt.id == anchor.excerpt_id {
2566                let excerpt_buffer_start =
2567                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2568                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2569                let buffer_position = cmp::min(
2570                    excerpt_buffer_end,
2571                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2572                );
2573                if buffer_position > excerpt_buffer_start {
2574                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2575                }
2576            }
2577        }
2578        position
2579    }
2580
2581    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2582    where
2583        D: TextDimension + Ord + Sub<D, Output = D>,
2584        I: 'a + IntoIterator<Item = &'a Anchor>,
2585    {
2586        if let Some((_, _, buffer)) = self.as_singleton() {
2587            return buffer
2588                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2589                .collect();
2590        }
2591
2592        let mut anchors = anchors.into_iter().peekable();
2593        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2594        let mut summaries = Vec::new();
2595        while let Some(anchor) = anchors.peek() {
2596            let excerpt_id = anchor.excerpt_id;
2597            let excerpt_anchors = iter::from_fn(|| {
2598                let anchor = anchors.peek()?;
2599                if anchor.excerpt_id == excerpt_id {
2600                    Some(&anchors.next().unwrap().text_anchor)
2601                } else {
2602                    None
2603                }
2604            });
2605
2606            let locator = self.excerpt_locator_for_id(excerpt_id);
2607            cursor.seek_forward(locator, Bias::Left, &());
2608            if cursor.item().is_none() {
2609                cursor.next(&());
2610            }
2611
2612            let position = D::from_text_summary(&cursor.start().text);
2613            if let Some(excerpt) = cursor.item() {
2614                if excerpt.id == excerpt_id {
2615                    let excerpt_buffer_start =
2616                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2617                    let excerpt_buffer_end =
2618                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2619                    summaries.extend(
2620                        excerpt
2621                            .buffer
2622                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2623                            .map(move |summary| {
2624                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2625                                let mut position = position.clone();
2626                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2627                                if summary > excerpt_buffer_start {
2628                                    position.add_assign(&(summary - excerpt_buffer_start));
2629                                }
2630                                position
2631                            }),
2632                    );
2633                    continue;
2634                }
2635            }
2636
2637            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2638        }
2639
2640        summaries
2641    }
2642
2643    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2644    where
2645        I: 'a + IntoIterator<Item = &'a Anchor>,
2646    {
2647        let mut anchors = anchors.into_iter().enumerate().peekable();
2648        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2649        cursor.next(&());
2650
2651        let mut result = Vec::new();
2652
2653        while let Some((_, anchor)) = anchors.peek() {
2654            let old_excerpt_id = anchor.excerpt_id;
2655
2656            // Find the location where this anchor's excerpt should be.
2657            let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2658            cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2659
2660            if cursor.item().is_none() {
2661                cursor.next(&());
2662            }
2663
2664            let next_excerpt = cursor.item();
2665            let prev_excerpt = cursor.prev_item();
2666
2667            // Process all of the anchors for this excerpt.
2668            while let Some((_, anchor)) = anchors.peek() {
2669                if anchor.excerpt_id != old_excerpt_id {
2670                    break;
2671                }
2672                let (anchor_ix, anchor) = anchors.next().unwrap();
2673                let mut anchor = *anchor;
2674
2675                // Leave min and max anchors unchanged if invalid or
2676                // if the old excerpt still exists at this location
2677                let mut kept_position = next_excerpt
2678                    .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2679                    || old_excerpt_id == ExcerptId::max()
2680                    || old_excerpt_id == ExcerptId::min();
2681
2682                // If the old excerpt no longer exists at this location, then attempt to
2683                // find an equivalent position for this anchor in an adjacent excerpt.
2684                if !kept_position {
2685                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2686                        if excerpt.contains(&anchor) {
2687                            anchor.excerpt_id = excerpt.id;
2688                            kept_position = true;
2689                            break;
2690                        }
2691                    }
2692                }
2693
2694                // If there's no adjacent excerpt that contains the anchor's position,
2695                // then report that the anchor has lost its position.
2696                if !kept_position {
2697                    anchor = if let Some(excerpt) = next_excerpt {
2698                        let mut text_anchor = excerpt
2699                            .range
2700                            .context
2701                            .start
2702                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2703                        if text_anchor
2704                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2705                            .is_gt()
2706                        {
2707                            text_anchor = excerpt.range.context.end;
2708                        }
2709                        Anchor {
2710                            buffer_id: Some(excerpt.buffer_id),
2711                            excerpt_id: excerpt.id,
2712                            text_anchor,
2713                        }
2714                    } else if let Some(excerpt) = prev_excerpt {
2715                        let mut text_anchor = excerpt
2716                            .range
2717                            .context
2718                            .end
2719                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2720                        if text_anchor
2721                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2722                            .is_lt()
2723                        {
2724                            text_anchor = excerpt.range.context.start;
2725                        }
2726                        Anchor {
2727                            buffer_id: Some(excerpt.buffer_id),
2728                            excerpt_id: excerpt.id,
2729                            text_anchor,
2730                        }
2731                    } else if anchor.text_anchor.bias == Bias::Left {
2732                        Anchor::min()
2733                    } else {
2734                        Anchor::max()
2735                    };
2736                }
2737
2738                result.push((anchor_ix, anchor, kept_position));
2739            }
2740        }
2741        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2742        result
2743    }
2744
2745    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2746        self.anchor_at(position, Bias::Left)
2747    }
2748
2749    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2750        self.anchor_at(position, Bias::Right)
2751    }
2752
2753    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2754        let offset = position.to_offset(self);
2755        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2756            return Anchor {
2757                buffer_id: Some(buffer_id),
2758                excerpt_id: *excerpt_id,
2759                text_anchor: buffer.anchor_at(offset, bias),
2760            };
2761        }
2762
2763        let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2764        cursor.seek(&offset, Bias::Right, &());
2765        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2766            cursor.prev(&());
2767        }
2768        if let Some(excerpt) = cursor.item() {
2769            let mut overshoot = offset.saturating_sub(cursor.start().0);
2770            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2771                overshoot -= 1;
2772                bias = Bias::Right;
2773            }
2774
2775            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2776            let text_anchor =
2777                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2778            Anchor {
2779                buffer_id: Some(excerpt.buffer_id),
2780                excerpt_id: excerpt.id,
2781                text_anchor,
2782            }
2783        } else if offset == 0 && bias == Bias::Left {
2784            Anchor::min()
2785        } else {
2786            Anchor::max()
2787        }
2788    }
2789
2790    /// Returns an anchor for the given excerpt and text anchor,
2791    /// returns None if the excerpt_id is no longer valid.
2792    pub fn anchor_in_excerpt(
2793        &self,
2794        excerpt_id: ExcerptId,
2795        text_anchor: text::Anchor,
2796    ) -> Option<Anchor> {
2797        let locator = self.excerpt_locator_for_id(excerpt_id);
2798        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2799        cursor.seek(locator, Bias::Left, &());
2800        if let Some(excerpt) = cursor.item() {
2801            if excerpt.id == excerpt_id {
2802                let text_anchor = excerpt.clip_anchor(text_anchor);
2803                drop(cursor);
2804                return Some(Anchor {
2805                    buffer_id: Some(excerpt.buffer_id),
2806                    excerpt_id,
2807                    text_anchor,
2808                });
2809            }
2810        }
2811        None
2812    }
2813
2814    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2815        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2816            true
2817        } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2818            excerpt.buffer.can_resolve(&anchor.text_anchor)
2819        } else {
2820            false
2821        }
2822    }
2823
2824    pub fn excerpts(
2825        &self,
2826    ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2827        self.excerpts
2828            .iter()
2829            .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2830    }
2831
2832    fn excerpts_for_range<T: ToOffset>(
2833        &self,
2834        range: Range<T>,
2835    ) -> impl Iterator<Item = (&Excerpt, usize)> + '_ {
2836        let range = range.start.to_offset(self)..range.end.to_offset(self);
2837
2838        let mut cursor = self.excerpts.cursor::<usize>();
2839        cursor.seek(&range.start, Bias::Right, &());
2840        cursor.prev(&());
2841
2842        iter::from_fn(move || {
2843            cursor.next(&());
2844            if cursor.start() < &range.end {
2845                cursor.item().map(|item| (item, *cursor.start()))
2846            } else {
2847                None
2848            }
2849        })
2850    }
2851
2852    pub fn excerpt_boundaries_in_range<R, T>(
2853        &self,
2854        range: R,
2855    ) -> impl Iterator<Item = ExcerptBoundary> + '_
2856    where
2857        R: RangeBounds<T>,
2858        T: ToOffset,
2859    {
2860        let start_offset;
2861        let start = match range.start_bound() {
2862            Bound::Included(start) => {
2863                start_offset = start.to_offset(self);
2864                Bound::Included(start_offset)
2865            }
2866            Bound::Excluded(start) => {
2867                start_offset = start.to_offset(self);
2868                Bound::Excluded(start_offset)
2869            }
2870            Bound::Unbounded => {
2871                start_offset = 0;
2872                Bound::Unbounded
2873            }
2874        };
2875        let end = match range.end_bound() {
2876            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2877            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2878            Bound::Unbounded => Bound::Unbounded,
2879        };
2880        let bounds = (start, end);
2881
2882        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2883        cursor.seek(&start_offset, Bias::Right, &());
2884        if cursor.item().is_none() {
2885            cursor.prev(&());
2886        }
2887        if !bounds.contains(&cursor.start().0) {
2888            cursor.next(&());
2889        }
2890
2891        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2892        std::iter::from_fn(move || {
2893            if self.singleton {
2894                None
2895            } else if bounds.contains(&cursor.start().0) {
2896                let excerpt = cursor.item()?;
2897                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2898                let boundary = ExcerptBoundary {
2899                    id: excerpt.id,
2900                    row: cursor.start().1.row,
2901                    buffer: excerpt.buffer.clone(),
2902                    range: excerpt.range.clone(),
2903                    starts_new_buffer,
2904                };
2905
2906                prev_buffer_id = Some(excerpt.buffer_id);
2907                cursor.next(&());
2908                Some(boundary)
2909            } else {
2910                None
2911            }
2912        })
2913    }
2914
2915    pub fn edit_count(&self) -> usize {
2916        self.edit_count
2917    }
2918
2919    pub fn parse_count(&self) -> usize {
2920        self.parse_count
2921    }
2922
2923    /// Returns the smallest enclosing bracket ranges containing the given range or
2924    /// None if no brackets contain range or the range is not contained in a single
2925    /// excerpt
2926    ///
2927    /// Can optionally pass a range_filter to filter the ranges of brackets to consider
2928    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2929        &self,
2930        range: Range<T>,
2931        range_filter: Option<&dyn Fn(Range<usize>, Range<usize>) -> bool>,
2932    ) -> Option<(Range<usize>, Range<usize>)> {
2933        let range = range.start.to_offset(self)..range.end.to_offset(self);
2934        let excerpt = self.excerpt_containing(range.clone())?;
2935
2936        // Filter to ranges contained in the excerpt
2937        let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
2938            excerpt.contains_buffer_range(open.start..close.end)
2939                && range_filter.map_or(true, |filter| {
2940                    filter(
2941                        excerpt.map_range_from_buffer(open),
2942                        excerpt.map_range_from_buffer(close),
2943                    )
2944                })
2945        };
2946
2947        let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
2948            excerpt.map_range_to_buffer(range),
2949            Some(&range_filter),
2950        )?;
2951
2952        Some((
2953            excerpt.map_range_from_buffer(open),
2954            excerpt.map_range_from_buffer(close),
2955        ))
2956    }
2957
2958    /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2959    /// not contained in a single excerpt
2960    pub fn enclosing_bracket_ranges<T: ToOffset>(
2961        &self,
2962        range: Range<T>,
2963    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
2964        let range = range.start.to_offset(self)..range.end.to_offset(self);
2965        let excerpt = self.excerpt_containing(range.clone())?;
2966
2967        Some(
2968            excerpt
2969                .buffer()
2970                .enclosing_bracket_ranges(excerpt.map_range_to_buffer(range))
2971                .filter_map(move |(open, close)| {
2972                    if excerpt.contains_buffer_range(open.start..close.end) {
2973                        Some((
2974                            excerpt.map_range_from_buffer(open),
2975                            excerpt.map_range_from_buffer(close),
2976                        ))
2977                    } else {
2978                        None
2979                    }
2980                }),
2981        )
2982    }
2983
2984    /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2985    /// not contained in a single excerpt
2986    pub fn bracket_ranges<T: ToOffset>(
2987        &self,
2988        range: Range<T>,
2989    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + '_> {
2990        let range = range.start.to_offset(self)..range.end.to_offset(self);
2991        let excerpt = self.excerpt_containing(range.clone())?;
2992
2993        Some(
2994            excerpt
2995                .buffer()
2996                .bracket_ranges(excerpt.map_range_to_buffer(range))
2997                .filter_map(move |(start_bracket_range, close_bracket_range)| {
2998                    let buffer_range = start_bracket_range.start..close_bracket_range.end;
2999                    if excerpt.contains_buffer_range(buffer_range) {
3000                        Some((
3001                            excerpt.map_range_from_buffer(start_bracket_range),
3002                            excerpt.map_range_from_buffer(close_bracket_range),
3003                        ))
3004                    } else {
3005                        None
3006                    }
3007                }),
3008        )
3009    }
3010
3011    pub fn redacted_ranges<'a, T: ToOffset>(
3012        &'a self,
3013        range: Range<T>,
3014        redaction_enabled: impl Fn(Option<&Arc<dyn File>>) -> bool + 'a,
3015    ) -> impl Iterator<Item = Range<usize>> + 'a {
3016        let range = range.start.to_offset(self)..range.end.to_offset(self);
3017        self.excerpts_for_range(range.clone())
3018            .filter_map(move |(excerpt, excerpt_offset)| {
3019                redaction_enabled(excerpt.buffer.file()).then(move || {
3020                    let excerpt_buffer_start =
3021                        excerpt.range.context.start.to_offset(&excerpt.buffer);
3022
3023                    excerpt
3024                        .buffer
3025                        .redacted_ranges(excerpt.range.context.clone())
3026                        .map(move |mut redacted_range| {
3027                            // Re-base onto the excerpts coordinates in the multibuffer
3028                            redacted_range.start =
3029                                excerpt_offset + (redacted_range.start - excerpt_buffer_start);
3030                            redacted_range.end =
3031                                excerpt_offset + (redacted_range.end - excerpt_buffer_start);
3032
3033                            redacted_range
3034                        })
3035                        .skip_while(move |redacted_range| redacted_range.end < range.start)
3036                        .take_while(move |redacted_range| redacted_range.start < range.end)
3037                })
3038            })
3039            .flatten()
3040    }
3041
3042    pub fn diagnostics_update_count(&self) -> usize {
3043        self.diagnostics_update_count
3044    }
3045
3046    pub fn git_diff_update_count(&self) -> usize {
3047        self.git_diff_update_count
3048    }
3049
3050    pub fn trailing_excerpt_update_count(&self) -> usize {
3051        self.trailing_excerpt_update_count
3052    }
3053
3054    pub fn file_at<T: ToOffset>(&self, point: T) -> Option<&Arc<dyn File>> {
3055        self.point_to_buffer_offset(point)
3056            .and_then(|(buffer, _)| buffer.file())
3057    }
3058
3059    pub fn language_at<T: ToOffset>(&self, point: T) -> Option<&Arc<Language>> {
3060        self.point_to_buffer_offset(point)
3061            .and_then(|(buffer, offset)| buffer.language_at(offset))
3062    }
3063
3064    pub fn settings_at<'a, T: ToOffset>(
3065        &'a self,
3066        point: T,
3067        cx: &'a AppContext,
3068    ) -> &'a LanguageSettings {
3069        let mut language = None;
3070        let mut file = None;
3071        if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
3072            language = buffer.language_at(offset);
3073            file = buffer.file();
3074        }
3075        language_settings(language, file, cx)
3076    }
3077
3078    pub fn language_scope_at<T: ToOffset>(&self, point: T) -> Option<LanguageScope> {
3079        self.point_to_buffer_offset(point)
3080            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
3081    }
3082
3083    pub fn language_indent_size_at<T: ToOffset>(
3084        &self,
3085        position: T,
3086        cx: &AppContext,
3087    ) -> Option<IndentSize> {
3088        let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
3089        Some(buffer_snapshot.language_indent_size_at(offset, cx))
3090    }
3091
3092    pub fn is_dirty(&self) -> bool {
3093        self.is_dirty
3094    }
3095
3096    pub fn has_conflict(&self) -> bool {
3097        self.has_conflict
3098    }
3099
3100    pub fn has_diagnostics(&self) -> bool {
3101        self.excerpts
3102            .iter()
3103            .any(|excerpt| excerpt.buffer.has_diagnostics())
3104    }
3105
3106    pub fn diagnostic_group<'a, O>(
3107        &'a self,
3108        group_id: usize,
3109    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3110    where
3111        O: text::FromAnchor + 'a,
3112    {
3113        self.as_singleton()
3114            .into_iter()
3115            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
3116    }
3117
3118    pub fn diagnostics_in_range<'a, T, O>(
3119        &'a self,
3120        range: Range<T>,
3121        reversed: bool,
3122    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
3123    where
3124        T: 'a + ToOffset,
3125        O: 'a + text::FromAnchor + Ord,
3126    {
3127        self.as_singleton()
3128            .into_iter()
3129            .flat_map(move |(_, _, buffer)| {
3130                buffer.diagnostics_in_range(
3131                    range.start.to_offset(self)..range.end.to_offset(self),
3132                    reversed,
3133                )
3134            })
3135    }
3136
3137    pub fn has_git_diffs(&self) -> bool {
3138        for excerpt in self.excerpts.iter() {
3139            if excerpt.buffer.has_git_diff() {
3140                return true;
3141            }
3142        }
3143        false
3144    }
3145
3146    pub fn git_diff_hunks_in_range_rev(
3147        &self,
3148        row_range: Range<u32>,
3149    ) -> impl Iterator<Item = DiffHunk<u32>> + '_ {
3150        let mut cursor = self.excerpts.cursor::<Point>();
3151
3152        cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
3153        if cursor.item().is_none() {
3154            cursor.prev(&());
3155        }
3156
3157        std::iter::from_fn(move || {
3158            let excerpt = cursor.item()?;
3159            let multibuffer_start = *cursor.start();
3160            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3161            if multibuffer_start.row >= row_range.end {
3162                return None;
3163            }
3164
3165            let mut buffer_start = excerpt.range.context.start;
3166            let mut buffer_end = excerpt.range.context.end;
3167            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3168            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3169
3170            if row_range.start > multibuffer_start.row {
3171                let buffer_start_point =
3172                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3173                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3174            }
3175
3176            if row_range.end < multibuffer_end.row {
3177                let buffer_end_point =
3178                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3179                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3180            }
3181
3182            let buffer_hunks = excerpt
3183                .buffer
3184                .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
3185                .map(move |hunk| {
3186                    let start = multibuffer_start.row
3187                        + hunk
3188                            .associated_range
3189                            .start
3190                            .saturating_sub(excerpt_start_point.row);
3191                    let end = multibuffer_start.row
3192                        + hunk
3193                            .associated_range
3194                            .end
3195                            .min(excerpt_end_point.row + 1)
3196                            .saturating_sub(excerpt_start_point.row);
3197
3198                    DiffHunk {
3199                        associated_range: start..end,
3200                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3201                        buffer_range: hunk.buffer_range.clone(),
3202                        buffer_id: hunk.buffer_id,
3203                    }
3204                });
3205
3206            cursor.prev(&());
3207
3208            Some(buffer_hunks)
3209        })
3210        .flatten()
3211    }
3212
3213    pub fn git_diff_hunks_in_range(
3214        &self,
3215        row_range: Range<u32>,
3216    ) -> impl Iterator<Item = DiffHunk<u32>> + '_ {
3217        let mut cursor = self.excerpts.cursor::<Point>();
3218
3219        cursor.seek(&Point::new(row_range.start, 0), Bias::Left, &());
3220
3221        std::iter::from_fn(move || {
3222            let excerpt = cursor.item()?;
3223            let multibuffer_start = *cursor.start();
3224            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3225            let mut buffer_start = excerpt.range.context.start;
3226            let mut buffer_end = excerpt.range.context.end;
3227
3228            let excerpt_rows = match multibuffer_start.row.cmp(&row_range.end) {
3229                cmp::Ordering::Less => {
3230                    let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3231                    let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3232
3233                    if row_range.start > multibuffer_start.row {
3234                        let buffer_start_point = excerpt_start_point
3235                            + Point::new(row_range.start - multibuffer_start.row, 0);
3236                        buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3237                    }
3238
3239                    if row_range.end < multibuffer_end.row {
3240                        let buffer_end_point = excerpt_start_point
3241                            + Point::new(row_range.end - multibuffer_start.row, 0);
3242                        buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3243                    }
3244                    excerpt_start_point.row..excerpt_end_point.row
3245                }
3246                cmp::Ordering::Equal if row_range.end == 0 => {
3247                    buffer_end = buffer_start;
3248                    0..0
3249                }
3250                cmp::Ordering::Greater | cmp::Ordering::Equal => return None,
3251            };
3252
3253            let buffer_hunks = excerpt
3254                .buffer
3255                .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3256                .map(move |hunk| {
3257                    let buffer_range = if excerpt_rows.start == 0 && excerpt_rows.end == 0 {
3258                        0..1
3259                    } else {
3260                        let start = multibuffer_start.row
3261                            + hunk
3262                                .associated_range
3263                                .start
3264                                .saturating_sub(excerpt_rows.start);
3265                        let end = multibuffer_start.row
3266                            + hunk
3267                                .associated_range
3268                                .end
3269                                .min(excerpt_rows.end + 1)
3270                                .saturating_sub(excerpt_rows.start);
3271                        start..end
3272                    };
3273                    DiffHunk {
3274                        associated_range: buffer_range,
3275                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3276                        buffer_range: hunk.buffer_range.clone(),
3277                        buffer_id: hunk.buffer_id,
3278                    }
3279                });
3280
3281            cursor.next(&());
3282
3283            Some(buffer_hunks)
3284        })
3285        .flatten()
3286    }
3287
3288    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3289        let range = range.start.to_offset(self)..range.end.to_offset(self);
3290        let excerpt = self.excerpt_containing(range.clone())?;
3291
3292        let ancestor_buffer_range = excerpt
3293            .buffer()
3294            .range_for_syntax_ancestor(excerpt.map_range_to_buffer(range))?;
3295
3296        Some(excerpt.map_range_from_buffer(ancestor_buffer_range))
3297    }
3298
3299    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3300        let (excerpt_id, _, buffer) = self.as_singleton()?;
3301        let outline = buffer.outline(theme)?;
3302        Some(Outline::new(
3303            outline
3304                .items
3305                .into_iter()
3306                .flat_map(|item| {
3307                    Some(OutlineItem {
3308                        depth: item.depth,
3309                        range: self.anchor_in_excerpt(*excerpt_id, item.range.start)?
3310                            ..self.anchor_in_excerpt(*excerpt_id, item.range.end)?,
3311                        text: item.text,
3312                        highlight_ranges: item.highlight_ranges,
3313                        name_ranges: item.name_ranges,
3314                    })
3315                })
3316                .collect(),
3317        ))
3318    }
3319
3320    pub fn symbols_containing<T: ToOffset>(
3321        &self,
3322        offset: T,
3323        theme: Option<&SyntaxTheme>,
3324    ) -> Option<(BufferId, Vec<OutlineItem<Anchor>>)> {
3325        let anchor = self.anchor_before(offset);
3326        let excerpt_id = anchor.excerpt_id;
3327        let excerpt = self.excerpt(excerpt_id)?;
3328        Some((
3329            excerpt.buffer_id,
3330            excerpt
3331                .buffer
3332                .symbols_containing(anchor.text_anchor, theme)
3333                .into_iter()
3334                .flatten()
3335                .flat_map(|item| {
3336                    Some(OutlineItem {
3337                        depth: item.depth,
3338                        range: self.anchor_in_excerpt(excerpt_id, item.range.start)?
3339                            ..self.anchor_in_excerpt(excerpt_id, item.range.end)?,
3340                        text: item.text,
3341                        highlight_ranges: item.highlight_ranges,
3342                        name_ranges: item.name_ranges,
3343                    })
3344                })
3345                .collect(),
3346        ))
3347    }
3348
3349    fn excerpt_locator_for_id(&self, id: ExcerptId) -> &Locator {
3350        if id == ExcerptId::min() {
3351            Locator::min_ref()
3352        } else if id == ExcerptId::max() {
3353            Locator::max_ref()
3354        } else {
3355            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3356            cursor.seek(&id, Bias::Left, &());
3357            if let Some(entry) = cursor.item() {
3358                if entry.id == id {
3359                    return &entry.locator;
3360                }
3361            }
3362            panic!("invalid excerpt id {:?}", id)
3363        }
3364    }
3365
3366    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<BufferId> {
3367        Some(self.excerpt(excerpt_id)?.buffer_id)
3368    }
3369
3370    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3371        Some(&self.excerpt(excerpt_id)?.buffer)
3372    }
3373
3374    fn excerpt(&self, excerpt_id: ExcerptId) -> Option<&Excerpt> {
3375        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3376        let locator = self.excerpt_locator_for_id(excerpt_id);
3377        cursor.seek(&Some(locator), Bias::Left, &());
3378        if let Some(excerpt) = cursor.item() {
3379            if excerpt.id == excerpt_id {
3380                return Some(excerpt);
3381            }
3382        }
3383        None
3384    }
3385
3386    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3387    pub fn excerpt_containing<T: ToOffset>(&self, range: Range<T>) -> Option<MultiBufferExcerpt> {
3388        let range = range.start.to_offset(self)..range.end.to_offset(self);
3389
3390        let mut cursor = self.excerpts.cursor::<usize>();
3391        cursor.seek(&range.start, Bias::Right, &());
3392        let start_excerpt = cursor.item()?;
3393
3394        if range.start == range.end {
3395            return Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()));
3396        }
3397
3398        cursor.seek(&range.end, Bias::Right, &());
3399        let end_excerpt = cursor.item()?;
3400
3401        if start_excerpt.id != end_excerpt.id {
3402            None
3403        } else {
3404            Some(MultiBufferExcerpt::new(start_excerpt, *cursor.start()))
3405        }
3406    }
3407
3408    pub fn remote_selections_in_range<'a>(
3409        &'a self,
3410        range: &'a Range<Anchor>,
3411    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3412        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3413        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3414        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3415        cursor.seek(start_locator, Bias::Left, &());
3416        cursor
3417            .take_while(move |excerpt| excerpt.locator <= *end_locator)
3418            .flat_map(move |excerpt| {
3419                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3420                if excerpt.id == range.start.excerpt_id {
3421                    query_range.start = range.start.text_anchor;
3422                }
3423                if excerpt.id == range.end.excerpt_id {
3424                    query_range.end = range.end.text_anchor;
3425                }
3426
3427                excerpt
3428                    .buffer
3429                    .remote_selections_in_range(query_range)
3430                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3431                        selections.map(move |selection| {
3432                            let mut start = Anchor {
3433                                buffer_id: Some(excerpt.buffer_id),
3434                                excerpt_id: excerpt.id,
3435                                text_anchor: selection.start,
3436                            };
3437                            let mut end = Anchor {
3438                                buffer_id: Some(excerpt.buffer_id),
3439                                excerpt_id: excerpt.id,
3440                                text_anchor: selection.end,
3441                            };
3442                            if range.start.cmp(&start, self).is_gt() {
3443                                start = range.start;
3444                            }
3445                            if range.end.cmp(&end, self).is_lt() {
3446                                end = range.end;
3447                            }
3448
3449                            (
3450                                replica_id,
3451                                line_mode,
3452                                cursor_shape,
3453                                Selection {
3454                                    id: selection.id,
3455                                    start,
3456                                    end,
3457                                    reversed: selection.reversed,
3458                                    goal: selection.goal,
3459                                },
3460                            )
3461                        })
3462                    })
3463            })
3464    }
3465}
3466
3467#[cfg(any(test, feature = "test-support"))]
3468impl MultiBufferSnapshot {
3469    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3470        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3471        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3472        start..end
3473    }
3474}
3475
3476impl History {
3477    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3478        self.transaction_depth += 1;
3479        if self.transaction_depth == 1 {
3480            let id = self.next_transaction_id.tick();
3481            self.undo_stack.push(Transaction {
3482                id,
3483                buffer_transactions: Default::default(),
3484                first_edit_at: now,
3485                last_edit_at: now,
3486                suppress_grouping: false,
3487            });
3488            Some(id)
3489        } else {
3490            None
3491        }
3492    }
3493
3494    fn end_transaction(
3495        &mut self,
3496        now: Instant,
3497        buffer_transactions: HashMap<BufferId, TransactionId>,
3498    ) -> bool {
3499        assert_ne!(self.transaction_depth, 0);
3500        self.transaction_depth -= 1;
3501        if self.transaction_depth == 0 {
3502            if buffer_transactions.is_empty() {
3503                self.undo_stack.pop();
3504                false
3505            } else {
3506                self.redo_stack.clear();
3507                let transaction = self.undo_stack.last_mut().unwrap();
3508                transaction.last_edit_at = now;
3509                for (buffer_id, transaction_id) in buffer_transactions {
3510                    transaction
3511                        .buffer_transactions
3512                        .entry(buffer_id)
3513                        .or_insert(transaction_id);
3514                }
3515                true
3516            }
3517        } else {
3518            false
3519        }
3520    }
3521
3522    fn push_transaction<'a, T>(
3523        &mut self,
3524        buffer_transactions: T,
3525        now: Instant,
3526        cx: &mut ModelContext<MultiBuffer>,
3527    ) where
3528        T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
3529    {
3530        assert_eq!(self.transaction_depth, 0);
3531        let transaction = Transaction {
3532            id: self.next_transaction_id.tick(),
3533            buffer_transactions: buffer_transactions
3534                .into_iter()
3535                .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3536                .collect(),
3537            first_edit_at: now,
3538            last_edit_at: now,
3539            suppress_grouping: false,
3540        };
3541        if !transaction.buffer_transactions.is_empty() {
3542            self.undo_stack.push(transaction);
3543            self.redo_stack.clear();
3544        }
3545    }
3546
3547    fn finalize_last_transaction(&mut self) {
3548        if let Some(transaction) = self.undo_stack.last_mut() {
3549            transaction.suppress_grouping = true;
3550        }
3551    }
3552
3553    fn forget(&mut self, transaction_id: TransactionId) -> Option<Transaction> {
3554        if let Some(ix) = self
3555            .undo_stack
3556            .iter()
3557            .rposition(|transaction| transaction.id == transaction_id)
3558        {
3559            Some(self.undo_stack.remove(ix))
3560        } else if let Some(ix) = self
3561            .redo_stack
3562            .iter()
3563            .rposition(|transaction| transaction.id == transaction_id)
3564        {
3565            Some(self.redo_stack.remove(ix))
3566        } else {
3567            None
3568        }
3569    }
3570
3571    fn transaction_mut(&mut self, transaction_id: TransactionId) -> Option<&mut Transaction> {
3572        self.undo_stack
3573            .iter_mut()
3574            .find(|transaction| transaction.id == transaction_id)
3575            .or_else(|| {
3576                self.redo_stack
3577                    .iter_mut()
3578                    .find(|transaction| transaction.id == transaction_id)
3579            })
3580    }
3581
3582    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3583        assert_eq!(self.transaction_depth, 0);
3584        if let Some(transaction) = self.undo_stack.pop() {
3585            self.redo_stack.push(transaction);
3586            self.redo_stack.last_mut()
3587        } else {
3588            None
3589        }
3590    }
3591
3592    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3593        assert_eq!(self.transaction_depth, 0);
3594        if let Some(transaction) = self.redo_stack.pop() {
3595            self.undo_stack.push(transaction);
3596            self.undo_stack.last_mut()
3597        } else {
3598            None
3599        }
3600    }
3601
3602    fn remove_from_undo(&mut self, transaction_id: TransactionId) -> Option<&Transaction> {
3603        let ix = self
3604            .undo_stack
3605            .iter()
3606            .rposition(|transaction| transaction.id == transaction_id)?;
3607        let transaction = self.undo_stack.remove(ix);
3608        self.redo_stack.push(transaction);
3609        self.redo_stack.last()
3610    }
3611
3612    fn group(&mut self) -> Option<TransactionId> {
3613        let mut count = 0;
3614        let mut transactions = self.undo_stack.iter();
3615        if let Some(mut transaction) = transactions.next_back() {
3616            while let Some(prev_transaction) = transactions.next_back() {
3617                if !prev_transaction.suppress_grouping
3618                    && transaction.first_edit_at - prev_transaction.last_edit_at
3619                        <= self.group_interval
3620                {
3621                    transaction = prev_transaction;
3622                    count += 1;
3623                } else {
3624                    break;
3625                }
3626            }
3627        }
3628        self.group_trailing(count)
3629    }
3630
3631    fn group_until(&mut self, transaction_id: TransactionId) {
3632        let mut count = 0;
3633        for transaction in self.undo_stack.iter().rev() {
3634            if transaction.id == transaction_id {
3635                self.group_trailing(count);
3636                break;
3637            } else if transaction.suppress_grouping {
3638                break;
3639            } else {
3640                count += 1;
3641            }
3642        }
3643    }
3644
3645    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3646        let new_len = self.undo_stack.len() - n;
3647        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3648        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3649            if let Some(transaction) = transactions_to_merge.last() {
3650                last_transaction.last_edit_at = transaction.last_edit_at;
3651            }
3652            for to_merge in transactions_to_merge {
3653                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3654                    last_transaction
3655                        .buffer_transactions
3656                        .entry(*buffer_id)
3657                        .or_insert(*transaction_id);
3658                }
3659            }
3660        }
3661
3662        self.undo_stack.truncate(new_len);
3663        self.undo_stack.last().map(|t| t.id)
3664    }
3665}
3666
3667impl Excerpt {
3668    fn new(
3669        id: ExcerptId,
3670        locator: Locator,
3671        buffer_id: BufferId,
3672        buffer: BufferSnapshot,
3673        range: ExcerptRange<text::Anchor>,
3674        has_trailing_newline: bool,
3675    ) -> Self {
3676        Excerpt {
3677            id,
3678            locator,
3679            max_buffer_row: range.context.end.to_point(&buffer).row,
3680            text_summary: buffer
3681                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3682            buffer_id,
3683            buffer,
3684            range,
3685            has_trailing_newline,
3686        }
3687    }
3688
3689    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3690        let content_start = self.range.context.start.to_offset(&self.buffer);
3691        let chunks_start = content_start + range.start;
3692        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3693
3694        let footer_height = if self.has_trailing_newline
3695            && range.start <= self.text_summary.len
3696            && range.end > self.text_summary.len
3697        {
3698            1
3699        } else {
3700            0
3701        };
3702
3703        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3704
3705        ExcerptChunks {
3706            content_chunks,
3707            footer_height,
3708        }
3709    }
3710
3711    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3712        let content_start = self.range.context.start.to_offset(&self.buffer);
3713        let bytes_start = content_start + range.start;
3714        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3715        let footer_height = if self.has_trailing_newline
3716            && range.start <= self.text_summary.len
3717            && range.end > self.text_summary.len
3718        {
3719            1
3720        } else {
3721            0
3722        };
3723        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3724
3725        ExcerptBytes {
3726            content_bytes,
3727            footer_height,
3728        }
3729    }
3730
3731    fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3732        let content_start = self.range.context.start.to_offset(&self.buffer);
3733        let bytes_start = content_start + range.start;
3734        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3735        let footer_height = if self.has_trailing_newline
3736            && range.start <= self.text_summary.len
3737            && range.end > self.text_summary.len
3738        {
3739            1
3740        } else {
3741            0
3742        };
3743        let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3744
3745        ExcerptBytes {
3746            content_bytes,
3747            footer_height,
3748        }
3749    }
3750
3751    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3752        if text_anchor
3753            .cmp(&self.range.context.start, &self.buffer)
3754            .is_lt()
3755        {
3756            self.range.context.start
3757        } else if text_anchor
3758            .cmp(&self.range.context.end, &self.buffer)
3759            .is_gt()
3760        {
3761            self.range.context.end
3762        } else {
3763            text_anchor
3764        }
3765    }
3766
3767    fn contains(&self, anchor: &Anchor) -> bool {
3768        Some(self.buffer_id) == anchor.buffer_id
3769            && self
3770                .range
3771                .context
3772                .start
3773                .cmp(&anchor.text_anchor, &self.buffer)
3774                .is_le()
3775            && self
3776                .range
3777                .context
3778                .end
3779                .cmp(&anchor.text_anchor, &self.buffer)
3780                .is_ge()
3781    }
3782
3783    /// The [`Excerpt`]'s start offset in its [`Buffer`]
3784    fn buffer_start_offset(&self) -> usize {
3785        self.range.context.start.to_offset(&self.buffer)
3786    }
3787
3788    /// The [`Excerpt`]'s end offset in its [`Buffer`]
3789    fn buffer_end_offset(&self) -> usize {
3790        self.buffer_start_offset() + self.text_summary.len
3791    }
3792}
3793
3794impl<'a> MultiBufferExcerpt<'a> {
3795    fn new(excerpt: &'a Excerpt, excerpt_offset: usize) -> Self {
3796        MultiBufferExcerpt {
3797            excerpt,
3798            excerpt_offset,
3799        }
3800    }
3801
3802    pub fn buffer(&self) -> &'a BufferSnapshot {
3803        &self.excerpt.buffer
3804    }
3805
3806    /// Maps an offset within the [`MultiBuffer`] to an offset within the [`Buffer`]
3807    pub fn map_offset_to_buffer(&self, offset: usize) -> usize {
3808        self.excerpt.buffer_start_offset() + offset.saturating_sub(self.excerpt_offset)
3809    }
3810
3811    /// Maps a range within the [`MultiBuffer`] to a range within the [`Buffer`]
3812    pub fn map_range_to_buffer(&self, range: Range<usize>) -> Range<usize> {
3813        self.map_offset_to_buffer(range.start)..self.map_offset_to_buffer(range.end)
3814    }
3815
3816    /// Map an offset within the [`Buffer`] to an offset within the [`MultiBuffer`]
3817    pub fn map_offset_from_buffer(&self, buffer_offset: usize) -> usize {
3818        let mut buffer_offset_in_excerpt =
3819            buffer_offset.saturating_sub(self.excerpt.buffer_start_offset());
3820        buffer_offset_in_excerpt =
3821            cmp::min(buffer_offset_in_excerpt, self.excerpt.text_summary.len);
3822
3823        self.excerpt_offset + buffer_offset_in_excerpt
3824    }
3825
3826    /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
3827    pub fn map_range_from_buffer(&self, buffer_range: Range<usize>) -> Range<usize> {
3828        self.map_offset_from_buffer(buffer_range.start)
3829            ..self.map_offset_from_buffer(buffer_range.end)
3830    }
3831
3832    /// Returns true if the entirety of the given range is in the buffer's excerpt
3833    pub fn contains_buffer_range(&self, range: Range<usize>) -> bool {
3834        range.start >= self.excerpt.buffer_start_offset()
3835            && range.end <= self.excerpt.buffer_end_offset()
3836    }
3837}
3838
3839impl ExcerptId {
3840    pub fn min() -> Self {
3841        Self(0)
3842    }
3843
3844    pub fn max() -> Self {
3845        Self(usize::MAX)
3846    }
3847
3848    pub fn to_proto(&self) -> u64 {
3849        self.0 as _
3850    }
3851
3852    pub fn from_proto(proto: u64) -> Self {
3853        Self(proto as _)
3854    }
3855
3856    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3857        let a = snapshot.excerpt_locator_for_id(*self);
3858        let b = snapshot.excerpt_locator_for_id(*other);
3859        a.cmp(b).then_with(|| self.0.cmp(&other.0))
3860    }
3861}
3862
3863impl Into<usize> for ExcerptId {
3864    fn into(self) -> usize {
3865        self.0
3866    }
3867}
3868
3869impl fmt::Debug for Excerpt {
3870    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3871        f.debug_struct("Excerpt")
3872            .field("id", &self.id)
3873            .field("locator", &self.locator)
3874            .field("buffer_id", &self.buffer_id)
3875            .field("range", &self.range)
3876            .field("text_summary", &self.text_summary)
3877            .field("has_trailing_newline", &self.has_trailing_newline)
3878            .finish()
3879    }
3880}
3881
3882impl sum_tree::Item for Excerpt {
3883    type Summary = ExcerptSummary;
3884
3885    fn summary(&self) -> Self::Summary {
3886        let mut text = self.text_summary.clone();
3887        if self.has_trailing_newline {
3888            text += TextSummary::from("\n");
3889        }
3890        ExcerptSummary {
3891            excerpt_id: self.id,
3892            excerpt_locator: self.locator.clone(),
3893            max_buffer_row: self.max_buffer_row,
3894            text,
3895        }
3896    }
3897}
3898
3899impl sum_tree::Item for ExcerptIdMapping {
3900    type Summary = ExcerptId;
3901
3902    fn summary(&self) -> Self::Summary {
3903        self.id
3904    }
3905}
3906
3907impl sum_tree::KeyedItem for ExcerptIdMapping {
3908    type Key = ExcerptId;
3909
3910    fn key(&self) -> Self::Key {
3911        self.id
3912    }
3913}
3914
3915impl sum_tree::Summary for ExcerptId {
3916    type Context = ();
3917
3918    fn add_summary(&mut self, other: &Self, _: &()) {
3919        *self = *other;
3920    }
3921}
3922
3923impl sum_tree::Summary for ExcerptSummary {
3924    type Context = ();
3925
3926    fn add_summary(&mut self, summary: &Self, _: &()) {
3927        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3928        self.excerpt_locator = summary.excerpt_locator.clone();
3929        self.text.add_summary(&summary.text, &());
3930        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3931    }
3932}
3933
3934impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3935    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3936        *self += &summary.text;
3937    }
3938}
3939
3940impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3941    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3942        *self += summary.text.len;
3943    }
3944}
3945
3946impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3947    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3948        Ord::cmp(self, &cursor_location.text.len)
3949    }
3950}
3951
3952impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3953    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3954        Ord::cmp(&Some(self), cursor_location)
3955    }
3956}
3957
3958impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3959    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3960        Ord::cmp(self, &cursor_location.excerpt_locator)
3961    }
3962}
3963
3964impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3965    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3966        *self += summary.text.len_utf16;
3967    }
3968}
3969
3970impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3971    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3972        *self += summary.text.lines;
3973    }
3974}
3975
3976impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3977    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3978        *self += summary.text.lines_utf16()
3979    }
3980}
3981
3982impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3983    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3984        *self = Some(&summary.excerpt_locator);
3985    }
3986}
3987
3988impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3989    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3990        *self = Some(summary.excerpt_id);
3991    }
3992}
3993
3994impl<'a> MultiBufferRows<'a> {
3995    pub fn seek(&mut self, row: u32) {
3996        self.buffer_row_range = 0..0;
3997
3998        self.excerpts
3999            .seek_forward(&Point::new(row, 0), Bias::Right, &());
4000        if self.excerpts.item().is_none() {
4001            self.excerpts.prev(&());
4002
4003            if self.excerpts.item().is_none() && row == 0 {
4004                self.buffer_row_range = 0..1;
4005                return;
4006            }
4007        }
4008
4009        if let Some(excerpt) = self.excerpts.item() {
4010            let overshoot = row - self.excerpts.start().row;
4011            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4012            self.buffer_row_range.start = excerpt_start + overshoot;
4013            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
4014        }
4015    }
4016}
4017
4018impl<'a> Iterator for MultiBufferRows<'a> {
4019    type Item = Option<u32>;
4020
4021    fn next(&mut self) -> Option<Self::Item> {
4022        loop {
4023            if !self.buffer_row_range.is_empty() {
4024                let row = Some(self.buffer_row_range.start);
4025                self.buffer_row_range.start += 1;
4026                return Some(row);
4027            }
4028            self.excerpts.item()?;
4029            self.excerpts.next(&());
4030            let excerpt = self.excerpts.item()?;
4031            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
4032            self.buffer_row_range.end =
4033                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
4034        }
4035    }
4036}
4037
4038impl<'a> MultiBufferChunks<'a> {
4039    pub fn offset(&self) -> usize {
4040        self.range.start
4041    }
4042
4043    pub fn seek(&mut self, offset: usize) {
4044        self.range.start = offset;
4045        self.excerpts.seek(&offset, Bias::Right, &());
4046        if let Some(excerpt) = self.excerpts.item() {
4047            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4048                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
4049                self.language_aware,
4050            ));
4051        } else {
4052            self.excerpt_chunks = None;
4053        }
4054    }
4055}
4056
4057impl<'a> Iterator for MultiBufferChunks<'a> {
4058    type Item = Chunk<'a>;
4059
4060    fn next(&mut self) -> Option<Self::Item> {
4061        if self.range.is_empty() {
4062            None
4063        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
4064            self.range.start += chunk.text.len();
4065            Some(chunk)
4066        } else {
4067            self.excerpts.next(&());
4068            let excerpt = self.excerpts.item()?;
4069            self.excerpt_chunks = Some(excerpt.chunks_in_range(
4070                0..self.range.end - self.excerpts.start(),
4071                self.language_aware,
4072            ));
4073            self.next()
4074        }
4075    }
4076}
4077
4078impl<'a> MultiBufferBytes<'a> {
4079    fn consume(&mut self, len: usize) {
4080        self.range.start += len;
4081        self.chunk = &self.chunk[len..];
4082
4083        if !self.range.is_empty() && self.chunk.is_empty() {
4084            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4085                self.chunk = chunk;
4086            } else {
4087                self.excerpts.next(&());
4088                if let Some(excerpt) = self.excerpts.item() {
4089                    let mut excerpt_bytes =
4090                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4091                    self.chunk = excerpt_bytes.next().unwrap();
4092                    self.excerpt_bytes = Some(excerpt_bytes);
4093                }
4094            }
4095        }
4096    }
4097}
4098
4099impl<'a> Iterator for MultiBufferBytes<'a> {
4100    type Item = &'a [u8];
4101
4102    fn next(&mut self) -> Option<Self::Item> {
4103        let chunk = self.chunk;
4104        if chunk.is_empty() {
4105            None
4106        } else {
4107            self.consume(chunk.len());
4108            Some(chunk)
4109        }
4110    }
4111}
4112
4113impl<'a> io::Read for MultiBufferBytes<'a> {
4114    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4115        let len = cmp::min(buf.len(), self.chunk.len());
4116        buf[..len].copy_from_slice(&self.chunk[..len]);
4117        if len > 0 {
4118            self.consume(len);
4119        }
4120        Ok(len)
4121    }
4122}
4123
4124impl<'a> ReversedMultiBufferBytes<'a> {
4125    fn consume(&mut self, len: usize) {
4126        self.range.end -= len;
4127        self.chunk = &self.chunk[..self.chunk.len() - len];
4128
4129        if !self.range.is_empty() && self.chunk.is_empty() {
4130            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
4131                self.chunk = chunk;
4132            } else {
4133                self.excerpts.next(&());
4134                if let Some(excerpt) = self.excerpts.item() {
4135                    let mut excerpt_bytes =
4136                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
4137                    self.chunk = excerpt_bytes.next().unwrap();
4138                    self.excerpt_bytes = Some(excerpt_bytes);
4139                }
4140            }
4141        }
4142    }
4143}
4144
4145impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
4146    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
4147        let len = cmp::min(buf.len(), self.chunk.len());
4148        buf[..len].copy_from_slice(&self.chunk[..len]);
4149        buf[..len].reverse();
4150        if len > 0 {
4151            self.consume(len);
4152        }
4153        Ok(len)
4154    }
4155}
4156impl<'a> Iterator for ExcerptBytes<'a> {
4157    type Item = &'a [u8];
4158
4159    fn next(&mut self) -> Option<Self::Item> {
4160        if let Some(chunk) = self.content_bytes.next() {
4161            if !chunk.is_empty() {
4162                return Some(chunk);
4163            }
4164        }
4165
4166        if self.footer_height > 0 {
4167            let result = &NEWLINES[..self.footer_height];
4168            self.footer_height = 0;
4169            return Some(result);
4170        }
4171
4172        None
4173    }
4174}
4175
4176impl<'a> Iterator for ExcerptChunks<'a> {
4177    type Item = Chunk<'a>;
4178
4179    fn next(&mut self) -> Option<Self::Item> {
4180        if let Some(chunk) = self.content_chunks.next() {
4181            return Some(chunk);
4182        }
4183
4184        if self.footer_height > 0 {
4185            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
4186            self.footer_height = 0;
4187            return Some(Chunk {
4188                text,
4189                ..Default::default()
4190            });
4191        }
4192
4193        None
4194    }
4195}
4196
4197impl ToOffset for Point {
4198    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4199        snapshot.point_to_offset(*self)
4200    }
4201}
4202
4203impl ToOffset for usize {
4204    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4205        assert!(*self <= snapshot.len(), "offset is out of range");
4206        *self
4207    }
4208}
4209
4210impl ToOffset for OffsetUtf16 {
4211    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4212        snapshot.offset_utf16_to_offset(*self)
4213    }
4214}
4215
4216impl ToOffset for PointUtf16 {
4217    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
4218        snapshot.point_utf16_to_offset(*self)
4219    }
4220}
4221
4222impl ToOffsetUtf16 for OffsetUtf16 {
4223    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4224        *self
4225    }
4226}
4227
4228impl ToOffsetUtf16 for usize {
4229    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
4230        snapshot.offset_to_offset_utf16(*self)
4231    }
4232}
4233
4234impl ToPoint for usize {
4235    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
4236        snapshot.offset_to_point(*self)
4237    }
4238}
4239
4240impl ToPoint for Point {
4241    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
4242        *self
4243    }
4244}
4245
4246impl ToPointUtf16 for usize {
4247    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4248        snapshot.offset_to_point_utf16(*self)
4249    }
4250}
4251
4252impl ToPointUtf16 for Point {
4253    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
4254        snapshot.point_to_point_utf16(*self)
4255    }
4256}
4257
4258impl ToPointUtf16 for PointUtf16 {
4259    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
4260        *self
4261    }
4262}
4263
4264fn build_excerpt_ranges<T>(
4265    buffer: &BufferSnapshot,
4266    ranges: &[Range<T>],
4267    context_line_count: u32,
4268) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
4269where
4270    T: text::ToPoint,
4271{
4272    let max_point = buffer.max_point();
4273    let mut range_counts = Vec::new();
4274    let mut excerpt_ranges = Vec::new();
4275    let mut range_iter = ranges
4276        .iter()
4277        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
4278        .peekable();
4279    while let Some(range) = range_iter.next() {
4280        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
4281        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
4282        let mut ranges_in_excerpt = 1;
4283
4284        while let Some(next_range) = range_iter.peek() {
4285            if next_range.start.row <= excerpt_end.row + context_line_count {
4286                excerpt_end =
4287                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
4288                ranges_in_excerpt += 1;
4289                range_iter.next();
4290            } else {
4291                break;
4292            }
4293        }
4294
4295        excerpt_ranges.push(ExcerptRange {
4296            context: excerpt_start..excerpt_end,
4297            primary: Some(range),
4298        });
4299        range_counts.push(ranges_in_excerpt);
4300    }
4301
4302    (excerpt_ranges, range_counts)
4303}
4304
4305#[cfg(test)]
4306mod tests {
4307    use super::*;
4308    use futures::StreamExt;
4309    use gpui::{AppContext, Context, TestAppContext};
4310    use language::{Buffer, Rope};
4311    use parking_lot::RwLock;
4312    use rand::prelude::*;
4313    use settings::SettingsStore;
4314    use std::env;
4315    use util::test::sample_text;
4316
4317    #[gpui::test]
4318    fn test_singleton(cx: &mut AppContext) {
4319        let buffer = cx.new_model(|cx| {
4320            Buffer::new(
4321                0,
4322                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4323                sample_text(6, 6, 'a'),
4324            )
4325        });
4326        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4327
4328        let snapshot = multibuffer.read(cx).snapshot(cx);
4329        assert_eq!(snapshot.text(), buffer.read(cx).text());
4330
4331        assert_eq!(
4332            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4333            (0..buffer.read(cx).row_count())
4334                .map(Some)
4335                .collect::<Vec<_>>()
4336        );
4337
4338        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4339        let snapshot = multibuffer.read(cx).snapshot(cx);
4340
4341        assert_eq!(snapshot.text(), buffer.read(cx).text());
4342        assert_eq!(
4343            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4344            (0..buffer.read(cx).row_count())
4345                .map(Some)
4346                .collect::<Vec<_>>()
4347        );
4348    }
4349
4350    #[gpui::test]
4351    fn test_remote(cx: &mut AppContext) {
4352        let host_buffer =
4353            cx.new_model(|cx| Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "a"));
4354        let guest_buffer = cx.new_model(|cx| {
4355            let state = host_buffer.read(cx).to_proto();
4356            let ops = cx
4357                .background_executor()
4358                .block(host_buffer.read(cx).serialize_ops(None, cx));
4359            let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
4360            buffer
4361                .apply_ops(
4362                    ops.into_iter()
4363                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
4364                    cx,
4365                )
4366                .unwrap();
4367            buffer
4368        });
4369        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4370        let snapshot = multibuffer.read(cx).snapshot(cx);
4371        assert_eq!(snapshot.text(), "a");
4372
4373        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4374        let snapshot = multibuffer.read(cx).snapshot(cx);
4375        assert_eq!(snapshot.text(), "ab");
4376
4377        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4378        let snapshot = multibuffer.read(cx).snapshot(cx);
4379        assert_eq!(snapshot.text(), "abc");
4380    }
4381
4382    #[gpui::test]
4383    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4384        let buffer_1 = cx.new_model(|cx| {
4385            Buffer::new(
4386                0,
4387                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4388                sample_text(6, 6, 'a'),
4389            )
4390        });
4391        let buffer_2 = cx.new_model(|cx| {
4392            Buffer::new(
4393                0,
4394                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4395                sample_text(6, 6, 'g'),
4396            )
4397        });
4398        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4399
4400        let events = Arc::new(RwLock::new(Vec::<Event>::new()));
4401        multibuffer.update(cx, |_, cx| {
4402            let events = events.clone();
4403            cx.subscribe(&multibuffer, move |_, _, event, _| {
4404                if let Event::Edited { .. } = event {
4405                    events.write().push(event.clone())
4406                }
4407            })
4408            .detach();
4409        });
4410
4411        let subscription = multibuffer.update(cx, |multibuffer, cx| {
4412            let subscription = multibuffer.subscribe();
4413            multibuffer.push_excerpts(
4414                buffer_1.clone(),
4415                [ExcerptRange {
4416                    context: Point::new(1, 2)..Point::new(2, 5),
4417                    primary: None,
4418                }],
4419                cx,
4420            );
4421            assert_eq!(
4422                subscription.consume().into_inner(),
4423                [Edit {
4424                    old: 0..0,
4425                    new: 0..10
4426                }]
4427            );
4428
4429            multibuffer.push_excerpts(
4430                buffer_1.clone(),
4431                [ExcerptRange {
4432                    context: Point::new(3, 3)..Point::new(4, 4),
4433                    primary: None,
4434                }],
4435                cx,
4436            );
4437            multibuffer.push_excerpts(
4438                buffer_2.clone(),
4439                [ExcerptRange {
4440                    context: Point::new(3, 1)..Point::new(3, 3),
4441                    primary: None,
4442                }],
4443                cx,
4444            );
4445            assert_eq!(
4446                subscription.consume().into_inner(),
4447                [Edit {
4448                    old: 10..10,
4449                    new: 10..22
4450                }]
4451            );
4452
4453            subscription
4454        });
4455
4456        // Adding excerpts emits an edited event.
4457        assert_eq!(
4458            events.read().as_slice(),
4459            &[
4460                Event::Edited {
4461                    singleton_buffer_edited: false
4462                },
4463                Event::Edited {
4464                    singleton_buffer_edited: false
4465                },
4466                Event::Edited {
4467                    singleton_buffer_edited: false
4468                }
4469            ]
4470        );
4471
4472        let snapshot = multibuffer.read(cx).snapshot(cx);
4473        assert_eq!(
4474            snapshot.text(),
4475            concat!(
4476                "bbbb\n",  // Preserve newlines
4477                "ccccc\n", //
4478                "ddd\n",   //
4479                "eeee\n",  //
4480                "jj"       //
4481            )
4482        );
4483        assert_eq!(
4484            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4485            [Some(1), Some(2), Some(3), Some(4), Some(3)]
4486        );
4487        assert_eq!(
4488            snapshot.buffer_rows(2).collect::<Vec<_>>(),
4489            [Some(3), Some(4), Some(3)]
4490        );
4491        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4492        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4493
4494        assert_eq!(
4495            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4496            &[
4497                (0, "bbbb\nccccc".to_string(), true),
4498                (2, "ddd\neeee".to_string(), false),
4499                (4, "jj".to_string(), true),
4500            ]
4501        );
4502        assert_eq!(
4503            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4504            &[(0, "bbbb\nccccc".to_string(), true)]
4505        );
4506        assert_eq!(
4507            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4508            &[]
4509        );
4510        assert_eq!(
4511            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4512            &[]
4513        );
4514        assert_eq!(
4515            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4516            &[(2, "ddd\neeee".to_string(), false)]
4517        );
4518        assert_eq!(
4519            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4520            &[(2, "ddd\neeee".to_string(), false)]
4521        );
4522        assert_eq!(
4523            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4524            &[(2, "ddd\neeee".to_string(), false)]
4525        );
4526        assert_eq!(
4527            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4528            &[(4, "jj".to_string(), true)]
4529        );
4530        assert_eq!(
4531            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4532            &[]
4533        );
4534
4535        buffer_1.update(cx, |buffer, cx| {
4536            let text = "\n";
4537            buffer.edit(
4538                [
4539                    (Point::new(0, 0)..Point::new(0, 0), text),
4540                    (Point::new(2, 1)..Point::new(2, 3), text),
4541                ],
4542                None,
4543                cx,
4544            );
4545        });
4546
4547        let snapshot = multibuffer.read(cx).snapshot(cx);
4548        assert_eq!(
4549            snapshot.text(),
4550            concat!(
4551                "bbbb\n", // Preserve newlines
4552                "c\n",    //
4553                "cc\n",   //
4554                "ddd\n",  //
4555                "eeee\n", //
4556                "jj"      //
4557            )
4558        );
4559
4560        assert_eq!(
4561            subscription.consume().into_inner(),
4562            [Edit {
4563                old: 6..8,
4564                new: 6..7
4565            }]
4566        );
4567
4568        let snapshot = multibuffer.read(cx).snapshot(cx);
4569        assert_eq!(
4570            snapshot.clip_point(Point::new(0, 5), Bias::Left),
4571            Point::new(0, 4)
4572        );
4573        assert_eq!(
4574            snapshot.clip_point(Point::new(0, 5), Bias::Right),
4575            Point::new(0, 4)
4576        );
4577        assert_eq!(
4578            snapshot.clip_point(Point::new(5, 1), Bias::Right),
4579            Point::new(5, 1)
4580        );
4581        assert_eq!(
4582            snapshot.clip_point(Point::new(5, 2), Bias::Right),
4583            Point::new(5, 2)
4584        );
4585        assert_eq!(
4586            snapshot.clip_point(Point::new(5, 3), Bias::Right),
4587            Point::new(5, 2)
4588        );
4589
4590        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4591            let (buffer_2_excerpt_id, _) =
4592                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4593            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4594            multibuffer.snapshot(cx)
4595        });
4596
4597        assert_eq!(
4598            snapshot.text(),
4599            concat!(
4600                "bbbb\n", // Preserve newlines
4601                "c\n",    //
4602                "cc\n",   //
4603                "ddd\n",  //
4604                "eeee",   //
4605            )
4606        );
4607
4608        fn boundaries_in_range(
4609            range: Range<Point>,
4610            snapshot: &MultiBufferSnapshot,
4611        ) -> Vec<(u32, String, bool)> {
4612            snapshot
4613                .excerpt_boundaries_in_range(range)
4614                .map(|boundary| {
4615                    (
4616                        boundary.row,
4617                        boundary
4618                            .buffer
4619                            .text_for_range(boundary.range.context)
4620                            .collect::<String>(),
4621                        boundary.starts_new_buffer,
4622                    )
4623                })
4624                .collect::<Vec<_>>()
4625        }
4626    }
4627
4628    #[gpui::test]
4629    fn test_excerpt_events(cx: &mut AppContext) {
4630        let buffer_1 = cx.new_model(|cx| {
4631            Buffer::new(
4632                0,
4633                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4634                sample_text(10, 3, 'a'),
4635            )
4636        });
4637        let buffer_2 = cx.new_model(|cx| {
4638            Buffer::new(
4639                0,
4640                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4641                sample_text(10, 3, 'm'),
4642            )
4643        });
4644
4645        let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4646        let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4647        let follower_edit_event_count = Arc::new(RwLock::new(0));
4648
4649        follower_multibuffer.update(cx, |_, cx| {
4650            let follower_edit_event_count = follower_edit_event_count.clone();
4651            cx.subscribe(
4652                &leader_multibuffer,
4653                move |follower, _, event, cx| match event.clone() {
4654                    Event::ExcerptsAdded {
4655                        buffer,
4656                        predecessor,
4657                        excerpts,
4658                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4659                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4660                    Event::Edited { .. } => {
4661                        *follower_edit_event_count.write() += 1;
4662                    }
4663                    _ => {}
4664                },
4665            )
4666            .detach();
4667        });
4668
4669        leader_multibuffer.update(cx, |leader, cx| {
4670            leader.push_excerpts(
4671                buffer_1.clone(),
4672                [
4673                    ExcerptRange {
4674                        context: 0..8,
4675                        primary: None,
4676                    },
4677                    ExcerptRange {
4678                        context: 12..16,
4679                        primary: None,
4680                    },
4681                ],
4682                cx,
4683            );
4684            leader.insert_excerpts_after(
4685                leader.excerpt_ids()[0],
4686                buffer_2.clone(),
4687                [
4688                    ExcerptRange {
4689                        context: 0..5,
4690                        primary: None,
4691                    },
4692                    ExcerptRange {
4693                        context: 10..15,
4694                        primary: None,
4695                    },
4696                ],
4697                cx,
4698            )
4699        });
4700        assert_eq!(
4701            leader_multibuffer.read(cx).snapshot(cx).text(),
4702            follower_multibuffer.read(cx).snapshot(cx).text(),
4703        );
4704        assert_eq!(*follower_edit_event_count.read(), 2);
4705
4706        leader_multibuffer.update(cx, |leader, cx| {
4707            let excerpt_ids = leader.excerpt_ids();
4708            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], 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(), 3);
4715
4716        // Removing an empty set of excerpts is a noop.
4717        leader_multibuffer.update(cx, |leader, cx| {
4718            leader.remove_excerpts([], cx);
4719        });
4720        assert_eq!(
4721            leader_multibuffer.read(cx).snapshot(cx).text(),
4722            follower_multibuffer.read(cx).snapshot(cx).text(),
4723        );
4724        assert_eq!(*follower_edit_event_count.read(), 3);
4725
4726        // Adding an empty set of excerpts is a noop.
4727        leader_multibuffer.update(cx, |leader, cx| {
4728            leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4729        });
4730        assert_eq!(
4731            leader_multibuffer.read(cx).snapshot(cx).text(),
4732            follower_multibuffer.read(cx).snapshot(cx).text(),
4733        );
4734        assert_eq!(*follower_edit_event_count.read(), 3);
4735
4736        leader_multibuffer.update(cx, |leader, cx| {
4737            leader.clear(cx);
4738        });
4739        assert_eq!(
4740            leader_multibuffer.read(cx).snapshot(cx).text(),
4741            follower_multibuffer.read(cx).snapshot(cx).text(),
4742        );
4743        assert_eq!(*follower_edit_event_count.read(), 4);
4744    }
4745
4746    #[gpui::test]
4747    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4748        let buffer = cx.new_model(|cx| {
4749            Buffer::new(
4750                0,
4751                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4752                sample_text(20, 3, 'a'),
4753            )
4754        });
4755        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4756        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4757            multibuffer.push_excerpts_with_context_lines(
4758                buffer.clone(),
4759                vec![
4760                    Point::new(3, 2)..Point::new(4, 2),
4761                    Point::new(7, 1)..Point::new(7, 3),
4762                    Point::new(15, 0)..Point::new(15, 0),
4763                ],
4764                2,
4765                cx,
4766            )
4767        });
4768
4769        let snapshot = multibuffer.read(cx).snapshot(cx);
4770        assert_eq!(
4771            snapshot.text(),
4772            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4773        );
4774
4775        assert_eq!(
4776            anchor_ranges
4777                .iter()
4778                .map(|range| range.to_point(&snapshot))
4779                .collect::<Vec<_>>(),
4780            vec![
4781                Point::new(2, 2)..Point::new(3, 2),
4782                Point::new(6, 1)..Point::new(6, 3),
4783                Point::new(12, 0)..Point::new(12, 0)
4784            ]
4785        );
4786    }
4787
4788    #[gpui::test]
4789    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4790        let buffer = cx.new_model(|cx| {
4791            Buffer::new(
4792                0,
4793                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4794                sample_text(20, 3, 'a'),
4795            )
4796        });
4797        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4798        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4799            let snapshot = buffer.read(cx);
4800            let ranges = vec![
4801                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4802                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4803                snapshot.anchor_before(Point::new(15, 0))
4804                    ..snapshot.anchor_before(Point::new(15, 0)),
4805            ];
4806            multibuffer.stream_excerpts_with_context_lines(buffer.clone(), ranges, 2, cx)
4807        });
4808
4809        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4810
4811        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4812        assert_eq!(
4813            snapshot.text(),
4814            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4815        );
4816
4817        assert_eq!(
4818            anchor_ranges
4819                .iter()
4820                .map(|range| range.to_point(&snapshot))
4821                .collect::<Vec<_>>(),
4822            vec![
4823                Point::new(2, 2)..Point::new(3, 2),
4824                Point::new(6, 1)..Point::new(6, 3),
4825                Point::new(12, 0)..Point::new(12, 0)
4826            ]
4827        );
4828    }
4829
4830    #[gpui::test]
4831    fn test_empty_multibuffer(cx: &mut AppContext) {
4832        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4833
4834        let snapshot = multibuffer.read(cx).snapshot(cx);
4835        assert_eq!(snapshot.text(), "");
4836        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4837        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4838    }
4839
4840    #[gpui::test]
4841    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
4842        let buffer = cx.new_model(|cx| {
4843            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "abcd")
4844        });
4845        let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4846        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4847        buffer.update(cx, |buffer, cx| {
4848            buffer.edit([(0..0, "X")], None, cx);
4849            buffer.edit([(5..5, "Y")], None, cx);
4850        });
4851        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4852
4853        assert_eq!(old_snapshot.text(), "abcd");
4854        assert_eq!(new_snapshot.text(), "XabcdY");
4855
4856        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4857        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4858        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4859        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4860    }
4861
4862    #[gpui::test]
4863    fn test_multibuffer_anchors(cx: &mut AppContext) {
4864        let buffer_1 = cx.new_model(|cx| {
4865            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "abcd")
4866        });
4867        let buffer_2 = cx.new_model(|cx| {
4868            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "efghi")
4869        });
4870        let multibuffer = cx.new_model(|cx| {
4871            let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
4872            multibuffer.push_excerpts(
4873                buffer_1.clone(),
4874                [ExcerptRange {
4875                    context: 0..4,
4876                    primary: None,
4877                }],
4878                cx,
4879            );
4880            multibuffer.push_excerpts(
4881                buffer_2.clone(),
4882                [ExcerptRange {
4883                    context: 0..5,
4884                    primary: None,
4885                }],
4886                cx,
4887            );
4888            multibuffer
4889        });
4890        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4891
4892        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4893        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4894        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4895        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4896        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4897        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4898
4899        buffer_1.update(cx, |buffer, cx| {
4900            buffer.edit([(0..0, "W")], None, cx);
4901            buffer.edit([(5..5, "X")], None, cx);
4902        });
4903        buffer_2.update(cx, |buffer, cx| {
4904            buffer.edit([(0..0, "Y")], None, cx);
4905            buffer.edit([(6..6, "Z")], None, cx);
4906        });
4907        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4908
4909        assert_eq!(old_snapshot.text(), "abcd\nefghi");
4910        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4911
4912        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4913        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4914        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4915        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4916        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4917        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4918        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4919        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4920        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4921        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4922    }
4923
4924    #[gpui::test]
4925    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
4926        let buffer_1 = cx.new_model(|cx| {
4927            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "abcd")
4928        });
4929        let buffer_2 = cx.new_model(|cx| {
4930            Buffer::new(
4931                0,
4932                BufferId::new(cx.entity_id().as_u64()).unwrap(),
4933                "ABCDEFGHIJKLMNOP",
4934            )
4935        });
4936        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
4937
4938        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4939        // Add an excerpt from buffer 1 that spans this new insertion.
4940        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4941        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4942            multibuffer
4943                .push_excerpts(
4944                    buffer_1.clone(),
4945                    [ExcerptRange {
4946                        context: 0..7,
4947                        primary: None,
4948                    }],
4949                    cx,
4950                )
4951                .pop()
4952                .unwrap()
4953        });
4954
4955        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4956        assert_eq!(snapshot_1.text(), "abcd123");
4957
4958        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4959        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4960            multibuffer.remove_excerpts([excerpt_id_1], cx);
4961            let mut ids = multibuffer
4962                .push_excerpts(
4963                    buffer_2.clone(),
4964                    [
4965                        ExcerptRange {
4966                            context: 0..4,
4967                            primary: None,
4968                        },
4969                        ExcerptRange {
4970                            context: 6..10,
4971                            primary: None,
4972                        },
4973                        ExcerptRange {
4974                            context: 12..16,
4975                            primary: None,
4976                        },
4977                    ],
4978                    cx,
4979                )
4980                .into_iter();
4981            (ids.next().unwrap(), ids.next().unwrap())
4982        });
4983        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4984        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4985
4986        // The old excerpt id doesn't get reused.
4987        assert_ne!(excerpt_id_2, excerpt_id_1);
4988
4989        // Resolve some anchors from the previous snapshot in the new snapshot.
4990        // The current excerpts are from a different buffer, so we don't attempt to
4991        // resolve the old text anchor in the new buffer.
4992        assert_eq!(
4993            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4994            0
4995        );
4996        assert_eq!(
4997            snapshot_2.summaries_for_anchors::<usize, _>(&[
4998                snapshot_1.anchor_before(2),
4999                snapshot_1.anchor_after(3)
5000            ]),
5001            vec![0, 0]
5002        );
5003
5004        // Refresh anchors from the old snapshot. The return value indicates that both
5005        // anchors lost their original excerpt.
5006        let refresh =
5007            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
5008        assert_eq!(
5009            refresh,
5010            &[
5011                (0, snapshot_2.anchor_before(0), false),
5012                (1, snapshot_2.anchor_after(0), false),
5013            ]
5014        );
5015
5016        // Replace the middle excerpt with a smaller excerpt in buffer 2,
5017        // that intersects the old excerpt.
5018        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
5019            multibuffer.remove_excerpts([excerpt_id_3], cx);
5020            multibuffer
5021                .insert_excerpts_after(
5022                    excerpt_id_2,
5023                    buffer_2.clone(),
5024                    [ExcerptRange {
5025                        context: 5..8,
5026                        primary: None,
5027                    }],
5028                    cx,
5029                )
5030                .pop()
5031                .unwrap()
5032        });
5033
5034        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
5035        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
5036        assert_ne!(excerpt_id_5, excerpt_id_3);
5037
5038        // Resolve some anchors from the previous snapshot in the new snapshot.
5039        // The third anchor can't be resolved, since its excerpt has been removed,
5040        // so it resolves to the same position as its predecessor.
5041        let anchors = [
5042            snapshot_2.anchor_before(0),
5043            snapshot_2.anchor_after(2),
5044            snapshot_2.anchor_after(6),
5045            snapshot_2.anchor_after(14),
5046        ];
5047        assert_eq!(
5048            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
5049            &[0, 2, 9, 13]
5050        );
5051
5052        let new_anchors = snapshot_3.refresh_anchors(&anchors);
5053        assert_eq!(
5054            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
5055            &[(0, true), (1, true), (2, true), (3, true)]
5056        );
5057        assert_eq!(
5058            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
5059            &[0, 2, 7, 13]
5060        );
5061    }
5062
5063    #[gpui::test(iterations = 100)]
5064    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
5065        let operations = env::var("OPERATIONS")
5066            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
5067            .unwrap_or(10);
5068
5069        let mut buffers: Vec<Model<Buffer>> = Vec::new();
5070        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5071        let mut excerpt_ids = Vec::<ExcerptId>::new();
5072        let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
5073        let mut anchors = Vec::new();
5074        let mut old_versions = Vec::new();
5075
5076        for _ in 0..operations {
5077            match rng.gen_range(0..100) {
5078                0..=19 if !buffers.is_empty() => {
5079                    let buffer = buffers.choose(&mut rng).unwrap();
5080                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
5081                }
5082                20..=29 if !expected_excerpts.is_empty() => {
5083                    let mut ids_to_remove = vec![];
5084                    for _ in 0..rng.gen_range(1..=3) {
5085                        if expected_excerpts.is_empty() {
5086                            break;
5087                        }
5088
5089                        let ix = rng.gen_range(0..expected_excerpts.len());
5090                        ids_to_remove.push(excerpt_ids.remove(ix));
5091                        let (buffer, range) = expected_excerpts.remove(ix);
5092                        let buffer = buffer.read(cx);
5093                        log::info!(
5094                            "Removing excerpt {}: {:?}",
5095                            ix,
5096                            buffer
5097                                .text_for_range(range.to_offset(buffer))
5098                                .collect::<String>(),
5099                        );
5100                    }
5101                    let snapshot = multibuffer.read(cx).read(cx);
5102                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
5103                    drop(snapshot);
5104                    multibuffer.update(cx, |multibuffer, cx| {
5105                        multibuffer.remove_excerpts(ids_to_remove, cx)
5106                    });
5107                }
5108                30..=39 if !expected_excerpts.is_empty() => {
5109                    let multibuffer = multibuffer.read(cx).read(cx);
5110                    let offset =
5111                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
5112                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
5113                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
5114                    anchors.push(multibuffer.anchor_at(offset, bias));
5115                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
5116                }
5117                40..=44 if !anchors.is_empty() => {
5118                    let multibuffer = multibuffer.read(cx).read(cx);
5119                    let prev_len = anchors.len();
5120                    anchors = multibuffer
5121                        .refresh_anchors(&anchors)
5122                        .into_iter()
5123                        .map(|a| a.1)
5124                        .collect();
5125
5126                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
5127                    // overshoot its boundaries.
5128                    assert_eq!(anchors.len(), prev_len);
5129                    for anchor in &anchors {
5130                        if anchor.excerpt_id == ExcerptId::min()
5131                            || anchor.excerpt_id == ExcerptId::max()
5132                        {
5133                            continue;
5134                        }
5135
5136                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
5137                        assert_eq!(excerpt.id, anchor.excerpt_id);
5138                        assert!(excerpt.contains(anchor));
5139                    }
5140                }
5141                _ => {
5142                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
5143                        let base_text = util::RandomCharIter::new(&mut rng)
5144                            .take(10)
5145                            .collect::<String>();
5146                        buffers.push(cx.new_model(|cx| {
5147                            Buffer::new(
5148                                0,
5149                                BufferId::new(cx.entity_id().as_u64()).unwrap(),
5150                                base_text,
5151                            )
5152                        }));
5153                        buffers.last().unwrap()
5154                    } else {
5155                        buffers.choose(&mut rng).unwrap()
5156                    };
5157
5158                    let buffer = buffer_handle.read(cx);
5159                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
5160                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5161                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
5162                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
5163                    let prev_excerpt_id = excerpt_ids
5164                        .get(prev_excerpt_ix)
5165                        .cloned()
5166                        .unwrap_or_else(ExcerptId::max);
5167                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
5168
5169                    log::info!(
5170                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
5171                        excerpt_ix,
5172                        expected_excerpts.len(),
5173                        buffer_handle.read(cx).remote_id(),
5174                        buffer.text(),
5175                        start_ix..end_ix,
5176                        &buffer.text()[start_ix..end_ix]
5177                    );
5178
5179                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
5180                        multibuffer
5181                            .insert_excerpts_after(
5182                                prev_excerpt_id,
5183                                buffer_handle.clone(),
5184                                [ExcerptRange {
5185                                    context: start_ix..end_ix,
5186                                    primary: None,
5187                                }],
5188                                cx,
5189                            )
5190                            .pop()
5191                            .unwrap()
5192                    });
5193
5194                    excerpt_ids.insert(excerpt_ix, excerpt_id);
5195                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5196                }
5197            }
5198
5199            if rng.gen_bool(0.3) {
5200                multibuffer.update(cx, |multibuffer, cx| {
5201                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5202                })
5203            }
5204
5205            let snapshot = multibuffer.read(cx).snapshot(cx);
5206
5207            let mut excerpt_starts = Vec::new();
5208            let mut expected_text = String::new();
5209            let mut expected_buffer_rows = Vec::new();
5210            for (buffer, range) in &expected_excerpts {
5211                let buffer = buffer.read(cx);
5212                let buffer_range = range.to_offset(buffer);
5213
5214                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5215                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5216                expected_text.push('\n');
5217
5218                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5219                    ..=buffer.offset_to_point(buffer_range.end).row;
5220                for row in buffer_row_range {
5221                    expected_buffer_rows.push(Some(row));
5222                }
5223            }
5224            // Remove final trailing newline.
5225            if !expected_excerpts.is_empty() {
5226                expected_text.pop();
5227            }
5228
5229            // Always report one buffer row
5230            if expected_buffer_rows.is_empty() {
5231                expected_buffer_rows.push(Some(0));
5232            }
5233
5234            assert_eq!(snapshot.text(), expected_text);
5235            log::info!("MultiBuffer text: {:?}", expected_text);
5236
5237            assert_eq!(
5238                snapshot.buffer_rows(0).collect::<Vec<_>>(),
5239                expected_buffer_rows,
5240            );
5241
5242            for _ in 0..5 {
5243                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5244                assert_eq!(
5245                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
5246                    &expected_buffer_rows[start_row..],
5247                    "buffer_rows({})",
5248                    start_row
5249                );
5250            }
5251
5252            assert_eq!(
5253                snapshot.max_buffer_row(),
5254                expected_buffer_rows.into_iter().flatten().max().unwrap()
5255            );
5256
5257            let mut excerpt_starts = excerpt_starts.into_iter();
5258            for (buffer, range) in &expected_excerpts {
5259                let buffer = buffer.read(cx);
5260                let buffer_id = buffer.remote_id();
5261                let buffer_range = range.to_offset(buffer);
5262                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5263                let buffer_start_point_utf16 =
5264                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5265
5266                let excerpt_start = excerpt_starts.next().unwrap();
5267                let mut offset = excerpt_start.len;
5268                let mut buffer_offset = buffer_range.start;
5269                let mut point = excerpt_start.lines;
5270                let mut buffer_point = buffer_start_point;
5271                let mut point_utf16 = excerpt_start.lines_utf16();
5272                let mut buffer_point_utf16 = buffer_start_point_utf16;
5273                for ch in buffer
5274                    .snapshot()
5275                    .chunks(buffer_range.clone(), false)
5276                    .flat_map(|c| c.text.chars())
5277                {
5278                    for _ in 0..ch.len_utf8() {
5279                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
5280                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
5281                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5282                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5283                        assert_eq!(
5284                            left_offset,
5285                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
5286                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5287                            offset,
5288                            buffer_id,
5289                            buffer_offset,
5290                        );
5291                        assert_eq!(
5292                            right_offset,
5293                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
5294                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5295                            offset,
5296                            buffer_id,
5297                            buffer_offset,
5298                        );
5299
5300                        let left_point = snapshot.clip_point(point, Bias::Left);
5301                        let right_point = snapshot.clip_point(point, Bias::Right);
5302                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5303                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5304                        assert_eq!(
5305                            left_point,
5306                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
5307                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5308                            point,
5309                            buffer_id,
5310                            buffer_point,
5311                        );
5312                        assert_eq!(
5313                            right_point,
5314                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
5315                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5316                            point,
5317                            buffer_id,
5318                            buffer_point,
5319                        );
5320
5321                        assert_eq!(
5322                            snapshot.point_to_offset(left_point),
5323                            left_offset,
5324                            "point_to_offset({:?})",
5325                            left_point,
5326                        );
5327                        assert_eq!(
5328                            snapshot.offset_to_point(left_offset),
5329                            left_point,
5330                            "offset_to_point({:?})",
5331                            left_offset,
5332                        );
5333
5334                        offset += 1;
5335                        buffer_offset += 1;
5336                        if ch == '\n' {
5337                            point += Point::new(1, 0);
5338                            buffer_point += Point::new(1, 0);
5339                        } else {
5340                            point += Point::new(0, 1);
5341                            buffer_point += Point::new(0, 1);
5342                        }
5343                    }
5344
5345                    for _ in 0..ch.len_utf16() {
5346                        let left_point_utf16 =
5347                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5348                        let right_point_utf16 =
5349                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5350                        let buffer_left_point_utf16 =
5351                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5352                        let buffer_right_point_utf16 =
5353                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5354                        assert_eq!(
5355                            left_point_utf16,
5356                            excerpt_start.lines_utf16()
5357                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
5358                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5359                            point_utf16,
5360                            buffer_id,
5361                            buffer_point_utf16,
5362                        );
5363                        assert_eq!(
5364                            right_point_utf16,
5365                            excerpt_start.lines_utf16()
5366                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
5367                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5368                            point_utf16,
5369                            buffer_id,
5370                            buffer_point_utf16,
5371                        );
5372
5373                        if ch == '\n' {
5374                            point_utf16 += PointUtf16::new(1, 0);
5375                            buffer_point_utf16 += PointUtf16::new(1, 0);
5376                        } else {
5377                            point_utf16 += PointUtf16::new(0, 1);
5378                            buffer_point_utf16 += PointUtf16::new(0, 1);
5379                        }
5380                    }
5381                }
5382            }
5383
5384            for (row, line) in expected_text.split('\n').enumerate() {
5385                assert_eq!(
5386                    snapshot.line_len(row as u32),
5387                    line.len() as u32,
5388                    "line_len({}).",
5389                    row
5390                );
5391            }
5392
5393            let text_rope = Rope::from(expected_text.as_str());
5394            for _ in 0..10 {
5395                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5396                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5397
5398                let text_for_range = snapshot
5399                    .text_for_range(start_ix..end_ix)
5400                    .collect::<String>();
5401                assert_eq!(
5402                    text_for_range,
5403                    &expected_text[start_ix..end_ix],
5404                    "incorrect text for range {:?}",
5405                    start_ix..end_ix
5406                );
5407
5408                let excerpted_buffer_ranges = multibuffer
5409                    .read(cx)
5410                    .range_to_buffer_ranges(start_ix..end_ix, cx);
5411                let excerpted_buffers_text = excerpted_buffer_ranges
5412                    .iter()
5413                    .map(|(buffer, buffer_range, _)| {
5414                        buffer
5415                            .read(cx)
5416                            .text_for_range(buffer_range.clone())
5417                            .collect::<String>()
5418                    })
5419                    .collect::<Vec<_>>()
5420                    .join("\n");
5421                assert_eq!(excerpted_buffers_text, text_for_range);
5422                if !expected_excerpts.is_empty() {
5423                    assert!(!excerpted_buffer_ranges.is_empty());
5424                }
5425
5426                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5427                assert_eq!(
5428                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5429                    expected_summary,
5430                    "incorrect summary for range {:?}",
5431                    start_ix..end_ix
5432                );
5433            }
5434
5435            // Anchor resolution
5436            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5437            assert_eq!(anchors.len(), summaries.len());
5438            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5439                assert!(resolved_offset <= snapshot.len());
5440                assert_eq!(
5441                    snapshot.summary_for_anchor::<usize>(anchor),
5442                    resolved_offset
5443                );
5444            }
5445
5446            for _ in 0..10 {
5447                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5448                assert_eq!(
5449                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
5450                    expected_text[..end_ix].chars().rev().collect::<String>(),
5451                );
5452            }
5453
5454            for _ in 0..10 {
5455                let end_ix = rng.gen_range(0..=text_rope.len());
5456                let start_ix = rng.gen_range(0..=end_ix);
5457                assert_eq!(
5458                    snapshot
5459                        .bytes_in_range(start_ix..end_ix)
5460                        .flatten()
5461                        .copied()
5462                        .collect::<Vec<_>>(),
5463                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5464                    "bytes_in_range({:?})",
5465                    start_ix..end_ix,
5466                );
5467            }
5468        }
5469
5470        let snapshot = multibuffer.read(cx).snapshot(cx);
5471        for (old_snapshot, subscription) in old_versions {
5472            let edits = subscription.consume().into_inner();
5473
5474            log::info!(
5475                "applying subscription edits to old text: {:?}: {:?}",
5476                old_snapshot.text(),
5477                edits,
5478            );
5479
5480            let mut text = old_snapshot.text();
5481            for edit in edits {
5482                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5483                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5484            }
5485            assert_eq!(text.to_string(), snapshot.text());
5486        }
5487    }
5488
5489    #[gpui::test]
5490    fn test_history(cx: &mut AppContext) {
5491        let test_settings = SettingsStore::test(cx);
5492        cx.set_global(test_settings);
5493
5494        let buffer_1 = cx.new_model(|cx| {
5495            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "1234")
5496        });
5497        let buffer_2 = cx.new_model(|cx| {
5498            Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "5678")
5499        });
5500        let multibuffer = cx.new_model(|_| MultiBuffer::new(0, Capability::ReadWrite));
5501        let group_interval = multibuffer.read(cx).history.group_interval;
5502        multibuffer.update(cx, |multibuffer, cx| {
5503            multibuffer.push_excerpts(
5504                buffer_1.clone(),
5505                [ExcerptRange {
5506                    context: 0..buffer_1.read(cx).len(),
5507                    primary: None,
5508                }],
5509                cx,
5510            );
5511            multibuffer.push_excerpts(
5512                buffer_2.clone(),
5513                [ExcerptRange {
5514                    context: 0..buffer_2.read(cx).len(),
5515                    primary: None,
5516                }],
5517                cx,
5518            );
5519        });
5520
5521        let mut now = Instant::now();
5522
5523        multibuffer.update(cx, |multibuffer, cx| {
5524            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5525            multibuffer.edit(
5526                [
5527                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5528                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5529                ],
5530                None,
5531                cx,
5532            );
5533            multibuffer.edit(
5534                [
5535                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5536                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5537                ],
5538                None,
5539                cx,
5540            );
5541            multibuffer.end_transaction_at(now, cx);
5542            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5543
5544            // Edit buffer 1 through the multibuffer
5545            now += 2 * group_interval;
5546            multibuffer.start_transaction_at(now, cx);
5547            multibuffer.edit([(2..2, "C")], None, cx);
5548            multibuffer.end_transaction_at(now, cx);
5549            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5550
5551            // Edit buffer 1 independently
5552            buffer_1.update(cx, |buffer_1, cx| {
5553                buffer_1.start_transaction_at(now);
5554                buffer_1.edit([(3..3, "D")], None, cx);
5555                buffer_1.end_transaction_at(now, cx);
5556
5557                now += 2 * group_interval;
5558                buffer_1.start_transaction_at(now);
5559                buffer_1.edit([(4..4, "E")], None, cx);
5560                buffer_1.end_transaction_at(now, cx);
5561            });
5562            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5563
5564            // An undo in the multibuffer undoes the multibuffer transaction
5565            // and also any individual buffer edits that have occurred since
5566            // that transaction.
5567            multibuffer.undo(cx);
5568            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5569
5570            multibuffer.undo(cx);
5571            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5572
5573            multibuffer.redo(cx);
5574            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5575
5576            multibuffer.redo(cx);
5577            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5578
5579            // Undo buffer 2 independently.
5580            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5581            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5582
5583            // An undo in the multibuffer undoes the components of the
5584            // the last multibuffer transaction that are not already undone.
5585            multibuffer.undo(cx);
5586            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5587
5588            multibuffer.undo(cx);
5589            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5590
5591            multibuffer.redo(cx);
5592            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5593
5594            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5595            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5596
5597            // Redo stack gets cleared after an edit.
5598            now += 2 * group_interval;
5599            multibuffer.start_transaction_at(now, cx);
5600            multibuffer.edit([(0..0, "X")], None, cx);
5601            multibuffer.end_transaction_at(now, cx);
5602            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5603            multibuffer.redo(cx);
5604            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5605            multibuffer.undo(cx);
5606            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5607            multibuffer.undo(cx);
5608            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5609
5610            // Transactions can be grouped manually.
5611            multibuffer.redo(cx);
5612            multibuffer.redo(cx);
5613            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5614            multibuffer.group_until_transaction(transaction_1, cx);
5615            multibuffer.undo(cx);
5616            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5617            multibuffer.redo(cx);
5618            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5619        });
5620    }
5621}