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