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