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