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