multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt};
   4use anyhow::Result;
   5use clock::ReplicaId;
   6use collections::{Bound, HashMap, HashSet};
   7use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
   8pub use language::Completion;
   9use language::{
  10    Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Outline,
  11    OutlineItem, Selection, ToOffset as _, ToPoint as _, ToPointUtf16 as _, TransactionId,
  12};
  13use std::{
  14    cell::{Ref, RefCell},
  15    cmp, fmt, io,
  16    iter::{self, FromIterator},
  17    ops::{Range, RangeBounds, Sub},
  18    str,
  19    sync::Arc,
  20    time::{Duration, Instant},
  21};
  22use sum_tree::{Bias, Cursor, SumTree};
  23use text::{
  24    locator::Locator,
  25    rope::TextDimension,
  26    subscription::{Subscription, Topic},
  27    AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary,
  28};
  29use theme::SyntaxTheme;
  30
  31const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
  32
  33pub type ExcerptId = Locator;
  34
  35pub struct MultiBuffer {
  36    snapshot: RefCell<MultiBufferSnapshot>,
  37    buffers: RefCell<HashMap<usize, BufferState>>,
  38    subscriptions: Topic,
  39    singleton: bool,
  40    replica_id: ReplicaId,
  41    history: History,
  42}
  43
  44struct History {
  45    next_transaction_id: TransactionId,
  46    undo_stack: Vec<Transaction>,
  47    redo_stack: Vec<Transaction>,
  48    transaction_depth: usize,
  49    group_interval: Duration,
  50}
  51
  52#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
  53pub enum CharKind {
  54    Newline,
  55    Punctuation,
  56    Whitespace,
  57    Word,
  58}
  59
  60struct Transaction {
  61    id: TransactionId,
  62    buffer_transactions: HashSet<(usize, text::TransactionId)>,
  63    first_edit_at: Instant,
  64    last_edit_at: Instant,
  65}
  66
  67pub trait ToOffset: 'static + fmt::Debug {
  68    fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
  69}
  70
  71pub trait ToPoint: 'static + fmt::Debug {
  72    fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
  73}
  74
  75pub trait ToPointUtf16: 'static + fmt::Debug {
  76    fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
  77}
  78
  79struct BufferState {
  80    buffer: ModelHandle<Buffer>,
  81    last_version: clock::Global,
  82    last_parse_count: usize,
  83    last_selections_update_count: usize,
  84    last_diagnostics_update_count: usize,
  85    last_file_update_count: usize,
  86    excerpts: Vec<ExcerptId>,
  87    _subscriptions: [gpui::Subscription; 2],
  88}
  89
  90#[derive(Clone, Default)]
  91pub struct MultiBufferSnapshot {
  92    singleton: bool,
  93    excerpts: SumTree<Excerpt>,
  94    parse_count: usize,
  95    diagnostics_update_count: usize,
  96    excerpt_update_count: usize,
  97    is_dirty: bool,
  98    has_conflict: bool,
  99}
 100
 101pub struct ExcerptProperties<'a, T> {
 102    pub buffer: &'a ModelHandle<Buffer>,
 103    pub range: Range<T>,
 104}
 105
 106pub struct ExcerptBoundary {
 107    pub row: u32,
 108    pub buffer: BufferSnapshot,
 109    pub range: Range<text::Anchor>,
 110    pub starts_new_buffer: bool,
 111}
 112
 113#[derive(Clone)]
 114struct Excerpt {
 115    id: ExcerptId,
 116    buffer_id: usize,
 117    buffer: BufferSnapshot,
 118    range: Range<text::Anchor>,
 119    max_buffer_row: u32,
 120    text_summary: TextSummary,
 121    has_trailing_newline: bool,
 122}
 123
 124#[derive(Clone, Debug, Default)]
 125struct ExcerptSummary {
 126    excerpt_id: ExcerptId,
 127    max_buffer_row: u32,
 128    text: TextSummary,
 129}
 130
 131pub struct MultiBufferRows<'a> {
 132    buffer_row_range: Range<u32>,
 133    excerpts: Cursor<'a, Excerpt, Point>,
 134}
 135
 136pub struct MultiBufferChunks<'a> {
 137    range: Range<usize>,
 138    excerpts: Cursor<'a, Excerpt, usize>,
 139    excerpt_chunks: Option<ExcerptChunks<'a>>,
 140    language_aware: bool,
 141}
 142
 143pub struct MultiBufferBytes<'a> {
 144    range: Range<usize>,
 145    excerpts: Cursor<'a, Excerpt, usize>,
 146    excerpt_bytes: Option<ExcerptBytes<'a>>,
 147    chunk: &'a [u8],
 148}
 149
 150struct ExcerptChunks<'a> {
 151    content_chunks: BufferChunks<'a>,
 152    footer_height: usize,
 153}
 154
 155struct ExcerptBytes<'a> {
 156    content_bytes: language::rope::Bytes<'a>,
 157    footer_height: usize,
 158}
 159
 160impl MultiBuffer {
 161    pub fn new(replica_id: ReplicaId) -> Self {
 162        Self {
 163            snapshot: Default::default(),
 164            buffers: Default::default(),
 165            subscriptions: Default::default(),
 166            singleton: false,
 167            replica_id,
 168            history: History {
 169                next_transaction_id: Default::default(),
 170                undo_stack: Default::default(),
 171                redo_stack: Default::default(),
 172                transaction_depth: 0,
 173                group_interval: Duration::from_millis(300),
 174            },
 175        }
 176    }
 177
 178    pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
 179        let mut this = Self::new(buffer.read(cx).replica_id());
 180        this.singleton = true;
 181        this.push_excerpt(
 182            ExcerptProperties {
 183                buffer: &buffer,
 184                range: text::Anchor::min()..text::Anchor::max(),
 185            },
 186            cx,
 187        );
 188        this.snapshot.borrow_mut().singleton = true;
 189        this
 190    }
 191
 192    #[cfg(any(test, feature = "test-support"))]
 193    pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
 194        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 195        cx.add_model(|cx| Self::singleton(buffer, cx))
 196    }
 197
 198    #[cfg(any(test, feature = "test-support"))]
 199    pub fn build_random(
 200        rng: &mut impl rand::Rng,
 201        cx: &mut gpui::MutableAppContext,
 202    ) -> ModelHandle<Self> {
 203        cx.add_model(|cx| {
 204            let mut multibuffer = MultiBuffer::new(0);
 205            let mutation_count = rng.gen_range(1..=5);
 206            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
 207            multibuffer
 208        })
 209    }
 210
 211    pub fn replica_id(&self) -> ReplicaId {
 212        self.replica_id
 213    }
 214
 215    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
 216        self.sync(cx);
 217        self.snapshot.borrow().clone()
 218    }
 219
 220    pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
 221        self.sync(cx);
 222        self.snapshot.borrow()
 223    }
 224
 225    pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
 226        if self.singleton {
 227            return Some(
 228                self.buffers
 229                    .borrow()
 230                    .values()
 231                    .next()
 232                    .unwrap()
 233                    .buffer
 234                    .clone(),
 235            );
 236        } else {
 237            None
 238        }
 239    }
 240
 241    pub fn subscribe(&mut self) -> Subscription {
 242        self.subscriptions.subscribe()
 243    }
 244
 245    pub fn edit<I, S, T>(&mut self, ranges: I, new_text: T, cx: &mut ModelContext<Self>)
 246    where
 247        I: IntoIterator<Item = Range<S>>,
 248        S: ToOffset,
 249        T: Into<String>,
 250    {
 251        self.edit_internal(ranges, new_text, false, cx)
 252    }
 253
 254    pub fn edit_with_autoindent<I, S, T>(
 255        &mut self,
 256        ranges: I,
 257        new_text: T,
 258        cx: &mut ModelContext<Self>,
 259    ) where
 260        I: IntoIterator<Item = Range<S>>,
 261        S: ToOffset,
 262        T: Into<String>,
 263    {
 264        self.edit_internal(ranges, new_text, true, cx)
 265    }
 266
 267    pub fn edit_internal<I, S, T>(
 268        &mut self,
 269        ranges_iter: I,
 270        new_text: T,
 271        autoindent: bool,
 272        cx: &mut ModelContext<Self>,
 273    ) where
 274        I: IntoIterator<Item = Range<S>>,
 275        S: ToOffset,
 276        T: Into<String>,
 277    {
 278        if self.buffers.borrow().is_empty() {
 279            return;
 280        }
 281
 282        if let Some(buffer) = self.as_singleton() {
 283            let snapshot = self.read(cx);
 284            let ranges = ranges_iter
 285                .into_iter()
 286                .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot));
 287            return buffer.update(cx, |buffer, cx| {
 288                if autoindent {
 289                    buffer.edit_with_autoindent(ranges, new_text, cx);
 290                } else {
 291                    buffer.edit(ranges, new_text, cx);
 292                }
 293            });
 294        }
 295
 296        let snapshot = self.read(cx);
 297        let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, bool)>> = Default::default();
 298        let mut cursor = snapshot.excerpts.cursor::<usize>();
 299        for range in ranges_iter {
 300            let start = range.start.to_offset(&snapshot);
 301            let end = range.end.to_offset(&snapshot);
 302            cursor.seek(&start, Bias::Right, &());
 303            if cursor.item().is_none() && start == *cursor.start() {
 304                cursor.prev(&());
 305            }
 306            let start_excerpt = cursor.item().expect("start offset out of bounds");
 307            let start_overshoot = start - cursor.start();
 308            let buffer_start =
 309                start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot;
 310
 311            cursor.seek(&end, Bias::Right, &());
 312            if cursor.item().is_none() && end == *cursor.start() {
 313                cursor.prev(&());
 314            }
 315            let end_excerpt = cursor.item().expect("end offset out of bounds");
 316            let end_overshoot = end - cursor.start();
 317            let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot;
 318
 319            if start_excerpt.id == end_excerpt.id {
 320                buffer_edits
 321                    .entry(start_excerpt.buffer_id)
 322                    .or_insert(Vec::new())
 323                    .push((buffer_start..buffer_end, true));
 324            } else {
 325                let start_excerpt_range =
 326                    buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
 327                let end_excerpt_range =
 328                    end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end;
 329                buffer_edits
 330                    .entry(start_excerpt.buffer_id)
 331                    .or_insert(Vec::new())
 332                    .push((start_excerpt_range, true));
 333                buffer_edits
 334                    .entry(end_excerpt.buffer_id)
 335                    .or_insert(Vec::new())
 336                    .push((end_excerpt_range, false));
 337
 338                cursor.seek(&start, Bias::Right, &());
 339                cursor.next(&());
 340                while let Some(excerpt) = cursor.item() {
 341                    if excerpt.id == end_excerpt.id {
 342                        break;
 343                    }
 344                    buffer_edits
 345                        .entry(excerpt.buffer_id)
 346                        .or_insert(Vec::new())
 347                        .push((excerpt.range.to_offset(&excerpt.buffer), false));
 348                    cursor.next(&());
 349                }
 350            }
 351        }
 352
 353        let new_text = new_text.into();
 354        for (buffer_id, mut edits) in buffer_edits {
 355            edits.sort_unstable_by_key(|(range, _)| range.start);
 356            self.buffers.borrow()[&buffer_id]
 357                .buffer
 358                .update(cx, |buffer, cx| {
 359                    let mut edits = edits.into_iter().peekable();
 360                    let mut insertions = Vec::new();
 361                    let mut deletions = Vec::new();
 362                    while let Some((mut range, mut is_insertion)) = edits.next() {
 363                        while let Some((next_range, next_is_insertion)) = edits.peek() {
 364                            if range.end >= next_range.start {
 365                                range.end = cmp::max(next_range.end, range.end);
 366                                is_insertion |= *next_is_insertion;
 367                                edits.next();
 368                            } else {
 369                                break;
 370                            }
 371                        }
 372
 373                        if is_insertion {
 374                            insertions.push(
 375                                buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 376                            );
 377                        } else if !range.is_empty() {
 378                            deletions.push(
 379                                buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 380                            );
 381                        }
 382                    }
 383
 384                    if autoindent {
 385                        buffer.edit_with_autoindent(deletions, "", cx);
 386                        buffer.edit_with_autoindent(insertions, new_text.clone(), cx);
 387                    } else {
 388                        buffer.edit(deletions, "", cx);
 389                        buffer.edit(insertions, new_text.clone(), cx);
 390                    }
 391                })
 392        }
 393    }
 394
 395    pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 396        self.start_transaction_at(Instant::now(), cx)
 397    }
 398
 399    pub(crate) fn start_transaction_at(
 400        &mut self,
 401        now: Instant,
 402        cx: &mut ModelContext<Self>,
 403    ) -> Option<TransactionId> {
 404        if let Some(buffer) = self.as_singleton() {
 405            return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 406        }
 407
 408        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 409            buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 410        }
 411        self.history.start_transaction(now)
 412    }
 413
 414    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 415        self.end_transaction_at(Instant::now(), cx)
 416    }
 417
 418    pub(crate) fn end_transaction_at(
 419        &mut self,
 420        now: Instant,
 421        cx: &mut ModelContext<Self>,
 422    ) -> Option<TransactionId> {
 423        if let Some(buffer) = self.as_singleton() {
 424            return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
 425        }
 426
 427        let mut buffer_transactions = HashSet::default();
 428        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 429            if let Some(transaction_id) =
 430                buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 431            {
 432                buffer_transactions.insert((buffer.id(), transaction_id));
 433            }
 434        }
 435
 436        if self.history.end_transaction(now, buffer_transactions) {
 437            let transaction_id = self.history.group().unwrap();
 438            Some(transaction_id)
 439        } else {
 440            None
 441        }
 442    }
 443
 444    pub fn finalize_last_transaction(&mut self, cx: &mut ModelContext<Self>) {
 445        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 446            buffer.update(cx, |buffer, _| {
 447                buffer.finalize_last_transaction();
 448            });
 449        }
 450    }
 451
 452    pub fn set_active_selections(
 453        &mut self,
 454        selections: &[Selection<Anchor>],
 455        cx: &mut ModelContext<Self>,
 456    ) {
 457        let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
 458            Default::default();
 459        let snapshot = self.read(cx);
 460        let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
 461        for selection in selections {
 462            cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &());
 463            while let Some(excerpt) = cursor.item() {
 464                if excerpt.id > selection.end.excerpt_id {
 465                    break;
 466                }
 467
 468                let mut start = excerpt.range.start.clone();
 469                let mut end = excerpt.range.end.clone();
 470                if excerpt.id == selection.start.excerpt_id {
 471                    start = selection.start.text_anchor.clone();
 472                }
 473                if excerpt.id == selection.end.excerpt_id {
 474                    end = selection.end.text_anchor.clone();
 475                }
 476                selections_by_buffer
 477                    .entry(excerpt.buffer_id)
 478                    .or_default()
 479                    .push(Selection {
 480                        id: selection.id,
 481                        start,
 482                        end,
 483                        reversed: selection.reversed,
 484                        goal: selection.goal,
 485                    });
 486
 487                cursor.next(&());
 488            }
 489        }
 490
 491        for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
 492            if !selections_by_buffer.contains_key(buffer_id) {
 493                buffer_state
 494                    .buffer
 495                    .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 496            }
 497        }
 498
 499        for (buffer_id, mut selections) in selections_by_buffer {
 500            self.buffers.borrow()[&buffer_id]
 501                .buffer
 502                .update(cx, |buffer, cx| {
 503                    selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap());
 504                    let mut selections = selections.into_iter().peekable();
 505                    let merged_selections = Arc::from_iter(iter::from_fn(|| {
 506                        let mut selection = selections.next()?;
 507                        while let Some(next_selection) = selections.peek() {
 508                            if selection
 509                                .end
 510                                .cmp(&next_selection.start, buffer)
 511                                .unwrap()
 512                                .is_ge()
 513                            {
 514                                let next_selection = selections.next().unwrap();
 515                                if next_selection
 516                                    .end
 517                                    .cmp(&selection.end, buffer)
 518                                    .unwrap()
 519                                    .is_ge()
 520                                {
 521                                    selection.end = next_selection.end;
 522                                }
 523                            } else {
 524                                break;
 525                            }
 526                        }
 527                        Some(selection)
 528                    }));
 529                    buffer.set_active_selections(merged_selections, cx);
 530                });
 531        }
 532    }
 533
 534    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 535        for buffer in self.buffers.borrow().values() {
 536            buffer
 537                .buffer
 538                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 539        }
 540    }
 541
 542    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 543        if let Some(buffer) = self.as_singleton() {
 544            return buffer.update(cx, |buffer, cx| buffer.undo(cx));
 545        }
 546
 547        while let Some(transaction) = self.history.pop_undo() {
 548            let mut undone = false;
 549            for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
 550                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
 551                    undone |= buffer.update(cx, |buf, cx| {
 552                        buf.undo_transaction(*buffer_transaction_id, cx)
 553                    });
 554                }
 555            }
 556
 557            if undone {
 558                return Some(transaction.id);
 559            }
 560        }
 561
 562        None
 563    }
 564
 565    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 566        if let Some(buffer) = self.as_singleton() {
 567            return buffer.update(cx, |buffer, cx| buffer.redo(cx));
 568        }
 569
 570        while let Some(transaction) = self.history.pop_redo() {
 571            let mut redone = false;
 572            for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
 573                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
 574                    redone |= buffer.update(cx, |buf, cx| {
 575                        buf.redo_transaction(*buffer_transaction_id, cx)
 576                    });
 577                }
 578            }
 579
 580            if redone {
 581                return Some(transaction.id);
 582            }
 583        }
 584
 585        None
 586    }
 587
 588    pub fn push_excerpt<O>(
 589        &mut self,
 590        props: ExcerptProperties<O>,
 591        cx: &mut ModelContext<Self>,
 592    ) -> ExcerptId
 593    where
 594        O: text::ToOffset,
 595    {
 596        self.insert_excerpt_after(&ExcerptId::max(), props, cx)
 597    }
 598
 599    pub fn insert_excerpt_after<O>(
 600        &mut self,
 601        prev_excerpt_id: &ExcerptId,
 602        props: ExcerptProperties<O>,
 603        cx: &mut ModelContext<Self>,
 604    ) -> ExcerptId
 605    where
 606        O: text::ToOffset,
 607    {
 608        assert_eq!(self.history.transaction_depth, 0);
 609        self.sync(cx);
 610
 611        let buffer_snapshot = props.buffer.read(cx).snapshot();
 612        let range = buffer_snapshot.anchor_before(&props.range.start)
 613            ..buffer_snapshot.anchor_after(&props.range.end);
 614        let mut snapshot = self.snapshot.borrow_mut();
 615        let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
 616        let mut new_excerpts = cursor.slice(&Some(prev_excerpt_id), Bias::Right, &());
 617
 618        let mut prev_id = ExcerptId::min();
 619        let edit_start = new_excerpts.summary().text.bytes;
 620        new_excerpts.update_last(
 621            |excerpt| {
 622                excerpt.has_trailing_newline = true;
 623                prev_id = excerpt.id.clone();
 624            },
 625            &(),
 626        );
 627
 628        let mut next_id = ExcerptId::max();
 629        if let Some(next_excerpt) = cursor.item() {
 630            next_id = next_excerpt.id.clone();
 631        }
 632
 633        let id = ExcerptId::between(&prev_id, &next_id);
 634
 635        let mut buffers = self.buffers.borrow_mut();
 636        let buffer_state = buffers
 637            .entry(props.buffer.id())
 638            .or_insert_with(|| BufferState {
 639                last_version: buffer_snapshot.version().clone(),
 640                last_parse_count: buffer_snapshot.parse_count(),
 641                last_selections_update_count: buffer_snapshot.selections_update_count(),
 642                last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
 643                last_file_update_count: buffer_snapshot.file_update_count(),
 644                excerpts: Default::default(),
 645                _subscriptions: [
 646                    cx.observe(&props.buffer, |_, _, cx| cx.notify()),
 647                    cx.subscribe(&props.buffer, Self::on_buffer_event),
 648                ],
 649                buffer: props.buffer.clone(),
 650            });
 651        if let Err(ix) = buffer_state.excerpts.binary_search(&id) {
 652            buffer_state.excerpts.insert(ix, id.clone());
 653        }
 654
 655        let excerpt = Excerpt::new(
 656            id.clone(),
 657            props.buffer.id(),
 658            buffer_snapshot,
 659            range,
 660            cursor.item().is_some(),
 661        );
 662        new_excerpts.push(excerpt, &());
 663        let edit_end = new_excerpts.summary().text.bytes;
 664
 665        new_excerpts.push_tree(cursor.suffix(&()), &());
 666        drop(cursor);
 667        snapshot.excerpts = new_excerpts;
 668        snapshot.excerpt_update_count += 1;
 669
 670        self.subscriptions.publish_mut([Edit {
 671            old: edit_start..edit_start,
 672            new: edit_start..edit_end,
 673        }]);
 674
 675        cx.notify();
 676        id
 677    }
 678
 679    pub fn excerpt_ids_for_buffer(&self, buffer: &ModelHandle<Buffer>) -> Vec<ExcerptId> {
 680        self.buffers
 681            .borrow()
 682            .get(&buffer.id())
 683            .map_or(Vec::new(), |state| state.excerpts.clone())
 684    }
 685
 686    pub fn excerpted_buffers<'a, T: ToOffset>(
 687        &'a self,
 688        range: Range<T>,
 689        cx: &AppContext,
 690    ) -> Vec<(ModelHandle<Buffer>, Range<usize>)> {
 691        let snapshot = self.snapshot(cx);
 692        let start = range.start.to_offset(&snapshot);
 693        let end = range.end.to_offset(&snapshot);
 694
 695        let mut result = Vec::new();
 696        let mut cursor = snapshot.excerpts.cursor::<usize>();
 697        cursor.seek(&start, Bias::Right, &());
 698        while let Some(excerpt) = cursor.item() {
 699            if *cursor.start() > end {
 700                break;
 701            }
 702
 703            let mut end_before_newline = cursor.end(&());
 704            if excerpt.has_trailing_newline {
 705                end_before_newline -= 1;
 706            }
 707            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 708            let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
 709            let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
 710            let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
 711            result.push((buffer, start..end));
 712            cursor.next(&());
 713        }
 714
 715        result
 716    }
 717
 718    pub fn remove_excerpts<'a>(
 719        &mut self,
 720        excerpt_ids: impl IntoIterator<Item = &'a ExcerptId>,
 721        cx: &mut ModelContext<Self>,
 722    ) {
 723        let mut buffers = self.buffers.borrow_mut();
 724        let mut snapshot = self.snapshot.borrow_mut();
 725        let mut new_excerpts = SumTree::new();
 726        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 727        let mut edits = Vec::new();
 728        let mut excerpt_ids = excerpt_ids.into_iter().peekable();
 729
 730        while let Some(mut excerpt_id) = excerpt_ids.next() {
 731            // Seek to the next excerpt to remove, preserving any preceding excerpts.
 732            new_excerpts.push_tree(cursor.slice(&Some(excerpt_id), Bias::Left, &()), &());
 733            if let Some(mut excerpt) = cursor.item() {
 734                if excerpt.id != *excerpt_id {
 735                    continue;
 736                }
 737                let mut old_start = cursor.start().1;
 738
 739                // Skip over the removed excerpt.
 740                loop {
 741                    if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
 742                        buffer_state.excerpts.retain(|id| id != excerpt_id);
 743                        if buffer_state.excerpts.is_empty() {
 744                            buffers.remove(&excerpt.buffer_id);
 745                        }
 746                    }
 747                    cursor.next(&());
 748
 749                    // Skip over any subsequent excerpts that are also removed.
 750                    if let Some(&next_excerpt_id) = excerpt_ids.peek() {
 751                        if let Some(next_excerpt) = cursor.item() {
 752                            if next_excerpt.id == *next_excerpt_id {
 753                                excerpt = next_excerpt;
 754                                excerpt_id = excerpt_ids.next().unwrap();
 755                                continue;
 756                            }
 757                        }
 758                    }
 759
 760                    break;
 761                }
 762
 763                // When removing the last excerpt, remove the trailing newline from
 764                // the previous excerpt.
 765                if cursor.item().is_none() && old_start > 0 {
 766                    old_start -= 1;
 767                    new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
 768                }
 769
 770                // Push an edit for the removal of this run of excerpts.
 771                let old_end = cursor.start().1;
 772                let new_start = new_excerpts.summary().text.bytes;
 773                edits.push(Edit {
 774                    old: old_start..old_end,
 775                    new: new_start..new_start,
 776                });
 777            }
 778        }
 779        new_excerpts.push_tree(cursor.suffix(&()), &());
 780        drop(cursor);
 781        snapshot.excerpts = new_excerpts;
 782        snapshot.excerpt_update_count += 1;
 783        self.subscriptions.publish_mut(edits);
 784        cx.notify();
 785    }
 786
 787    pub fn text_anchor_for_position<'a, T: ToOffset>(
 788        &'a self,
 789        position: T,
 790        cx: &AppContext,
 791    ) -> (ModelHandle<Buffer>, language::Anchor) {
 792        let snapshot = self.read(cx);
 793        let anchor = snapshot.anchor_before(position);
 794        (
 795            self.buffers.borrow()[&anchor.buffer_id].buffer.clone(),
 796            anchor.text_anchor,
 797        )
 798    }
 799
 800    fn on_buffer_event(
 801        &mut self,
 802        _: ModelHandle<Buffer>,
 803        event: &Event,
 804        cx: &mut ModelContext<Self>,
 805    ) {
 806        cx.emit(event.clone());
 807    }
 808
 809    pub fn format(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 810        let mut format_tasks = Vec::new();
 811        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 812            format_tasks.push(buffer.update(cx, |buffer, cx| buffer.format(cx)));
 813        }
 814
 815        cx.spawn(|_, _| async move {
 816            for format in format_tasks {
 817                format.await?;
 818            }
 819            Ok(())
 820        })
 821    }
 822
 823    pub fn save(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 824        let mut save_tasks = Vec::new();
 825        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 826            save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx)));
 827        }
 828
 829        cx.spawn(|_, _| async move {
 830            for save in save_tasks {
 831                save.await?;
 832            }
 833            Ok(())
 834        })
 835    }
 836
 837    pub fn is_completion_trigger<T>(&self, position: T, text: &str, cx: &AppContext) -> bool
 838    where
 839        T: ToOffset,
 840    {
 841        let mut chars = text.chars();
 842        let char = if let Some(char) = chars.next() {
 843            char
 844        } else {
 845            return false;
 846        };
 847        if chars.next().is_some() {
 848            return false;
 849        }
 850
 851        if char.is_alphanumeric() || char == '_' {
 852            return true;
 853        }
 854
 855        let snapshot = self.snapshot(cx);
 856        let anchor = snapshot.anchor_before(position);
 857        let buffer = self.buffers.borrow()[&anchor.buffer_id].buffer.clone();
 858        buffer
 859            .read(cx)
 860            .completion_triggers()
 861            .iter()
 862            .any(|string| string == text)
 863    }
 864
 865    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 866        self.buffers
 867            .borrow()
 868            .values()
 869            .next()
 870            .and_then(|state| state.buffer.read(cx).language())
 871    }
 872
 873    pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
 874        self.as_singleton()?.read(cx).file()
 875    }
 876
 877    #[cfg(test)]
 878    pub fn is_parsing(&self, cx: &AppContext) -> bool {
 879        self.as_singleton().unwrap().read(cx).is_parsing()
 880    }
 881
 882    fn sync(&self, cx: &AppContext) {
 883        let mut snapshot = self.snapshot.borrow_mut();
 884        let mut excerpts_to_edit = Vec::new();
 885        let mut reparsed = false;
 886        let mut diagnostics_updated = false;
 887        let mut is_dirty = false;
 888        let mut has_conflict = false;
 889        let mut buffers = self.buffers.borrow_mut();
 890        for buffer_state in buffers.values_mut() {
 891            let buffer = buffer_state.buffer.read(cx);
 892            let version = buffer.version();
 893            let parse_count = buffer.parse_count();
 894            let selections_update_count = buffer.selections_update_count();
 895            let diagnostics_update_count = buffer.diagnostics_update_count();
 896            let file_update_count = buffer.file_update_count();
 897
 898            let buffer_edited = version.changed_since(&buffer_state.last_version);
 899            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
 900            let buffer_selections_updated =
 901                selections_update_count > buffer_state.last_selections_update_count;
 902            let buffer_diagnostics_updated =
 903                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
 904            let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
 905            if buffer_edited
 906                || buffer_reparsed
 907                || buffer_selections_updated
 908                || buffer_diagnostics_updated
 909                || buffer_file_updated
 910            {
 911                buffer_state.last_version = version;
 912                buffer_state.last_parse_count = parse_count;
 913                buffer_state.last_selections_update_count = selections_update_count;
 914                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
 915                buffer_state.last_file_update_count = file_update_count;
 916                excerpts_to_edit.extend(
 917                    buffer_state
 918                        .excerpts
 919                        .iter()
 920                        .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
 921                );
 922            }
 923
 924            reparsed |= buffer_reparsed;
 925            diagnostics_updated |= buffer_diagnostics_updated;
 926            is_dirty |= buffer.is_dirty();
 927            has_conflict |= buffer.has_conflict();
 928        }
 929        if reparsed {
 930            snapshot.parse_count += 1;
 931        }
 932        if diagnostics_updated {
 933            snapshot.diagnostics_update_count += 1;
 934        }
 935        snapshot.is_dirty = is_dirty;
 936        snapshot.has_conflict = has_conflict;
 937
 938        excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
 939
 940        let mut edits = Vec::new();
 941        let mut new_excerpts = SumTree::new();
 942        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 943
 944        for (id, buffer, buffer_edited) in excerpts_to_edit {
 945            new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
 946            let old_excerpt = cursor.item().unwrap();
 947            let buffer_id = buffer.id();
 948            let buffer = buffer.read(cx);
 949
 950            let mut new_excerpt;
 951            if buffer_edited {
 952                edits.extend(
 953                    buffer
 954                        .edits_since_in_range::<usize>(
 955                            old_excerpt.buffer.version(),
 956                            old_excerpt.range.clone(),
 957                        )
 958                        .map(|mut edit| {
 959                            let excerpt_old_start = cursor.start().1;
 960                            let excerpt_new_start = new_excerpts.summary().text.bytes;
 961                            edit.old.start += excerpt_old_start;
 962                            edit.old.end += excerpt_old_start;
 963                            edit.new.start += excerpt_new_start;
 964                            edit.new.end += excerpt_new_start;
 965                            edit
 966                        }),
 967                );
 968
 969                new_excerpt = Excerpt::new(
 970                    id.clone(),
 971                    buffer_id,
 972                    buffer.snapshot(),
 973                    old_excerpt.range.clone(),
 974                    old_excerpt.has_trailing_newline,
 975                );
 976            } else {
 977                new_excerpt = old_excerpt.clone();
 978                new_excerpt.buffer = buffer.snapshot();
 979            }
 980
 981            new_excerpts.push(new_excerpt, &());
 982            cursor.next(&());
 983        }
 984        new_excerpts.push_tree(cursor.suffix(&()), &());
 985
 986        drop(cursor);
 987        snapshot.excerpts = new_excerpts;
 988
 989        self.subscriptions.publish(edits);
 990    }
 991}
 992
 993#[cfg(any(test, feature = "test-support"))]
 994impl MultiBuffer {
 995    pub fn randomly_edit(
 996        &mut self,
 997        rng: &mut impl rand::Rng,
 998        count: usize,
 999        cx: &mut ModelContext<Self>,
1000    ) {
1001        use text::RandomCharIter;
1002
1003        let snapshot = self.read(cx);
1004        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1005        for _ in 0..count {
1006            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1007            if last_end > snapshot.len() {
1008                break;
1009            }
1010            let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
1011            let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1012            old_ranges.push(start_ix..end_ix);
1013        }
1014        let new_text_len = rng.gen_range(0..10);
1015        let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1016        log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
1017        drop(snapshot);
1018
1019        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1020    }
1021
1022    pub fn randomly_edit_excerpts(
1023        &mut self,
1024        rng: &mut impl rand::Rng,
1025        mutation_count: usize,
1026        cx: &mut ModelContext<Self>,
1027    ) {
1028        use rand::prelude::*;
1029        use std::env;
1030        use text::RandomCharIter;
1031
1032        let max_excerpts = env::var("MAX_EXCERPTS")
1033            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1034            .unwrap_or(5);
1035
1036        let mut buffers = Vec::new();
1037        for _ in 0..mutation_count {
1038            let excerpt_ids = self
1039                .buffers
1040                .borrow()
1041                .values()
1042                .flat_map(|b| &b.excerpts)
1043                .cloned()
1044                .collect::<Vec<_>>();
1045            if excerpt_ids.len() == 0 || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1046                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1047                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1048                    buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1049                    let buffer = buffers.last().unwrap();
1050                    log::info!(
1051                        "Creating new buffer {} with text: {:?}",
1052                        buffer.id(),
1053                        buffer.read(cx).text()
1054                    );
1055                    buffers.last().unwrap().clone()
1056                } else {
1057                    self.buffers
1058                        .borrow()
1059                        .values()
1060                        .choose(rng)
1061                        .unwrap()
1062                        .buffer
1063                        .clone()
1064                };
1065
1066                let buffer = buffer_handle.read(cx);
1067                let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1068                let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1069                log::info!(
1070                    "Inserting excerpt from buffer {} and range {:?}: {:?}",
1071                    buffer_handle.id(),
1072                    start_ix..end_ix,
1073                    &buffer.text()[start_ix..end_ix]
1074                );
1075
1076                let excerpt_id = self.push_excerpt(
1077                    ExcerptProperties {
1078                        buffer: &buffer_handle,
1079                        range: start_ix..end_ix,
1080                    },
1081                    cx,
1082                );
1083                log::info!("Inserted with id: {:?}", excerpt_id);
1084            } else {
1085                let remove_count = rng.gen_range(1..=excerpt_ids.len());
1086                let mut excerpts_to_remove = excerpt_ids
1087                    .choose_multiple(rng, remove_count)
1088                    .cloned()
1089                    .collect::<Vec<_>>();
1090                excerpts_to_remove.sort();
1091                log::info!("Removing excerpts {:?}", excerpts_to_remove);
1092                self.remove_excerpts(&excerpts_to_remove, cx);
1093            }
1094        }
1095    }
1096
1097    pub fn randomly_mutate(
1098        &mut self,
1099        rng: &mut impl rand::Rng,
1100        mutation_count: usize,
1101        cx: &mut ModelContext<Self>,
1102    ) {
1103        if rng.gen_bool(0.7) || self.singleton {
1104            self.randomly_edit(rng, mutation_count, cx);
1105        } else {
1106            self.randomly_edit_excerpts(rng, mutation_count, cx);
1107        }
1108    }
1109}
1110
1111impl Entity for MultiBuffer {
1112    type Event = language::Event;
1113}
1114
1115impl MultiBufferSnapshot {
1116    pub fn text(&self) -> String {
1117        self.chunks(0..self.len(), false)
1118            .map(|chunk| chunk.text)
1119            .collect()
1120    }
1121
1122    pub fn reversed_chars_at<'a, T: ToOffset>(
1123        &'a self,
1124        position: T,
1125    ) -> impl Iterator<Item = char> + 'a {
1126        let mut offset = position.to_offset(self);
1127        let mut cursor = self.excerpts.cursor::<usize>();
1128        cursor.seek(&offset, Bias::Left, &());
1129        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1130            let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
1131            let start = excerpt.range.start.to_offset(&excerpt.buffer);
1132            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1133            excerpt.buffer.reversed_chunks_in_range(start..end)
1134        });
1135        iter::from_fn(move || {
1136            if offset == *cursor.start() {
1137                cursor.prev(&());
1138                let excerpt = cursor.item()?;
1139                excerpt_chunks = Some(
1140                    excerpt
1141                        .buffer
1142                        .reversed_chunks_in_range(excerpt.range.clone()),
1143                );
1144            }
1145
1146            let excerpt = cursor.item().unwrap();
1147            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1148                offset -= 1;
1149                Some("\n")
1150            } else {
1151                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1152                offset -= chunk.len();
1153                Some(chunk)
1154            }
1155        })
1156        .flat_map(|c| c.chars().rev())
1157    }
1158
1159    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1160        let offset = position.to_offset(self);
1161        self.text_for_range(offset..self.len())
1162            .flat_map(|chunk| chunk.chars())
1163    }
1164
1165    pub fn text_for_range<'a, T: ToOffset>(
1166        &'a self,
1167        range: Range<T>,
1168    ) -> impl Iterator<Item = &'a str> {
1169        self.chunks(range, false).map(|chunk| chunk.text)
1170    }
1171
1172    pub fn is_line_blank(&self, row: u32) -> bool {
1173        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1174            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1175    }
1176
1177    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1178    where
1179        T: ToOffset,
1180    {
1181        let position = position.to_offset(self);
1182        position == self.clip_offset(position, Bias::Left)
1183            && self
1184                .bytes_in_range(position..self.len())
1185                .flatten()
1186                .copied()
1187                .take(needle.len())
1188                .eq(needle.bytes())
1189    }
1190
1191    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1192        let mut start = start.to_offset(self);
1193        let mut end = start;
1194        let mut next_chars = self.chars_at(start).peekable();
1195        let mut prev_chars = self.reversed_chars_at(start).peekable();
1196        let word_kind = cmp::max(
1197            prev_chars.peek().copied().map(char_kind),
1198            next_chars.peek().copied().map(char_kind),
1199        );
1200
1201        for ch in prev_chars {
1202            if Some(char_kind(ch)) == word_kind {
1203                start -= ch.len_utf8();
1204            } else {
1205                break;
1206            }
1207        }
1208
1209        for ch in next_chars {
1210            if Some(char_kind(ch)) == word_kind {
1211                end += ch.len_utf8();
1212            } else {
1213                break;
1214            }
1215        }
1216
1217        (start..end, word_kind)
1218    }
1219
1220    fn as_singleton(&self) -> Option<&Excerpt> {
1221        if self.singleton {
1222            self.excerpts.iter().next()
1223        } else {
1224            None
1225        }
1226    }
1227
1228    pub fn len(&self) -> usize {
1229        self.excerpts.summary().text.bytes
1230    }
1231
1232    pub fn max_buffer_row(&self) -> u32 {
1233        self.excerpts.summary().max_buffer_row
1234    }
1235
1236    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1237        if let Some(excerpt) = self.as_singleton() {
1238            return excerpt.buffer.clip_offset(offset, bias);
1239        }
1240
1241        let mut cursor = self.excerpts.cursor::<usize>();
1242        cursor.seek(&offset, Bias::Right, &());
1243        let overshoot = if let Some(excerpt) = cursor.item() {
1244            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1245            let buffer_offset = excerpt
1246                .buffer
1247                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1248            buffer_offset.saturating_sub(excerpt_start)
1249        } else {
1250            0
1251        };
1252        cursor.start() + overshoot
1253    }
1254
1255    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1256        if let Some(excerpt) = self.as_singleton() {
1257            return excerpt.buffer.clip_point(point, bias);
1258        }
1259
1260        let mut cursor = self.excerpts.cursor::<Point>();
1261        cursor.seek(&point, Bias::Right, &());
1262        let overshoot = if let Some(excerpt) = cursor.item() {
1263            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1264            let buffer_point = excerpt
1265                .buffer
1266                .clip_point(excerpt_start + (point - cursor.start()), bias);
1267            buffer_point.saturating_sub(excerpt_start)
1268        } else {
1269            Point::zero()
1270        };
1271        *cursor.start() + overshoot
1272    }
1273
1274    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1275        if let Some(excerpt) = self.as_singleton() {
1276            return excerpt.buffer.clip_point_utf16(point, bias);
1277        }
1278
1279        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1280        cursor.seek(&point, Bias::Right, &());
1281        let overshoot = if let Some(excerpt) = cursor.item() {
1282            let excerpt_start = excerpt
1283                .buffer
1284                .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1285            let buffer_point = excerpt
1286                .buffer
1287                .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1288            buffer_point.saturating_sub(excerpt_start)
1289        } else {
1290            PointUtf16::zero()
1291        };
1292        *cursor.start() + overshoot
1293    }
1294
1295    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1296        let range = range.start.to_offset(self)..range.end.to_offset(self);
1297        let mut excerpts = self.excerpts.cursor::<usize>();
1298        excerpts.seek(&range.start, Bias::Right, &());
1299
1300        let mut chunk = &[][..];
1301        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1302            let mut excerpt_bytes = excerpt
1303                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1304            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1305            Some(excerpt_bytes)
1306        } else {
1307            None
1308        };
1309
1310        MultiBufferBytes {
1311            range,
1312            excerpts,
1313            excerpt_bytes,
1314            chunk,
1315        }
1316    }
1317
1318    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1319        let mut result = MultiBufferRows {
1320            buffer_row_range: 0..0,
1321            excerpts: self.excerpts.cursor(),
1322        };
1323        result.seek(start_row);
1324        result
1325    }
1326
1327    pub fn chunks<'a, T: ToOffset>(
1328        &'a self,
1329        range: Range<T>,
1330        language_aware: bool,
1331    ) -> MultiBufferChunks<'a> {
1332        let range = range.start.to_offset(self)..range.end.to_offset(self);
1333        let mut chunks = MultiBufferChunks {
1334            range: range.clone(),
1335            excerpts: self.excerpts.cursor(),
1336            excerpt_chunks: None,
1337            language_aware,
1338        };
1339        chunks.seek(range.start);
1340        chunks
1341    }
1342
1343    pub fn offset_to_point(&self, offset: usize) -> Point {
1344        if let Some(excerpt) = self.as_singleton() {
1345            return excerpt.buffer.offset_to_point(offset);
1346        }
1347
1348        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1349        cursor.seek(&offset, Bias::Right, &());
1350        if let Some(excerpt) = cursor.item() {
1351            let (start_offset, start_point) = cursor.start();
1352            let overshoot = offset - start_offset;
1353            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1354            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1355            let buffer_point = excerpt
1356                .buffer
1357                .offset_to_point(excerpt_start_offset + overshoot);
1358            *start_point + (buffer_point - excerpt_start_point)
1359        } else {
1360            self.excerpts.summary().text.lines
1361        }
1362    }
1363
1364    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1365        if let Some(excerpt) = self.as_singleton() {
1366            return excerpt.buffer.offset_to_point_utf16(offset);
1367        }
1368
1369        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1370        cursor.seek(&offset, Bias::Right, &());
1371        if let Some(excerpt) = cursor.item() {
1372            let (start_offset, start_point) = cursor.start();
1373            let overshoot = offset - start_offset;
1374            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1375            let excerpt_start_point = excerpt.range.start.to_point_utf16(&excerpt.buffer);
1376            let buffer_point = excerpt
1377                .buffer
1378                .offset_to_point_utf16(excerpt_start_offset + overshoot);
1379            *start_point + (buffer_point - excerpt_start_point)
1380        } else {
1381            self.excerpts.summary().text.lines_utf16
1382        }
1383    }
1384
1385    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1386        if let Some(excerpt) = self.as_singleton() {
1387            return excerpt.buffer.point_to_point_utf16(point);
1388        }
1389
1390        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1391        cursor.seek(&point, Bias::Right, &());
1392        if let Some(excerpt) = cursor.item() {
1393            let (start_offset, start_point) = cursor.start();
1394            let overshoot = point - start_offset;
1395            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1396            let excerpt_start_point_utf16 = excerpt.range.start.to_point_utf16(&excerpt.buffer);
1397            let buffer_point = excerpt
1398                .buffer
1399                .point_to_point_utf16(excerpt_start_point + overshoot);
1400            *start_point + (buffer_point - excerpt_start_point_utf16)
1401        } else {
1402            self.excerpts.summary().text.lines_utf16
1403        }
1404    }
1405
1406    pub fn point_to_offset(&self, point: Point) -> usize {
1407        if let Some(excerpt) = self.as_singleton() {
1408            return excerpt.buffer.point_to_offset(point);
1409        }
1410
1411        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1412        cursor.seek(&point, Bias::Right, &());
1413        if let Some(excerpt) = cursor.item() {
1414            let (start_point, start_offset) = cursor.start();
1415            let overshoot = point - start_point;
1416            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1417            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1418            let buffer_offset = excerpt
1419                .buffer
1420                .point_to_offset(excerpt_start_point + overshoot);
1421            *start_offset + buffer_offset - excerpt_start_offset
1422        } else {
1423            self.excerpts.summary().text.bytes
1424        }
1425    }
1426
1427    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1428        if let Some(excerpt) = self.as_singleton() {
1429            return excerpt.buffer.point_utf16_to_offset(point);
1430        }
1431
1432        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1433        cursor.seek(&point, Bias::Right, &());
1434        if let Some(excerpt) = cursor.item() {
1435            let (start_point, start_offset) = cursor.start();
1436            let overshoot = point - start_point;
1437            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1438            let excerpt_start_point = excerpt
1439                .buffer
1440                .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1441            let buffer_offset = excerpt
1442                .buffer
1443                .point_utf16_to_offset(excerpt_start_point + overshoot);
1444            *start_offset + (buffer_offset - excerpt_start_offset)
1445        } else {
1446            self.excerpts.summary().text.bytes
1447        }
1448    }
1449
1450    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1451        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1452            buffer
1453                .indent_column_for_line(range.start.row)
1454                .min(range.end.column)
1455                .saturating_sub(range.start.column)
1456        } else {
1457            0
1458        }
1459    }
1460
1461    pub fn line_len(&self, row: u32) -> u32 {
1462        if let Some((_, range)) = self.buffer_line_for_row(row) {
1463            range.end.column - range.start.column
1464        } else {
1465            0
1466        }
1467    }
1468
1469    fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1470        let mut cursor = self.excerpts.cursor::<Point>();
1471        cursor.seek(&Point::new(row, 0), Bias::Right, &());
1472        if let Some(excerpt) = cursor.item() {
1473            let overshoot = row - cursor.start().row;
1474            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1475            let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1476            let buffer_row = excerpt_start.row + overshoot;
1477            let line_start = Point::new(buffer_row, 0);
1478            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1479            return Some((
1480                &excerpt.buffer,
1481                line_start.max(excerpt_start)..line_end.min(excerpt_end),
1482            ));
1483        }
1484        None
1485    }
1486
1487    pub fn max_point(&self) -> Point {
1488        self.text_summary().lines
1489    }
1490
1491    pub fn text_summary(&self) -> TextSummary {
1492        self.excerpts.summary().text
1493    }
1494
1495    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1496    where
1497        D: TextDimension,
1498        O: ToOffset,
1499    {
1500        let mut summary = D::default();
1501        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1502        let mut cursor = self.excerpts.cursor::<usize>();
1503        cursor.seek(&range.start, Bias::Right, &());
1504        if let Some(excerpt) = cursor.item() {
1505            let mut end_before_newline = cursor.end(&());
1506            if excerpt.has_trailing_newline {
1507                end_before_newline -= 1;
1508            }
1509
1510            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1511            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1512            let end_in_excerpt =
1513                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1514            summary.add_assign(
1515                &excerpt
1516                    .buffer
1517                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1518            );
1519
1520            if range.end > end_before_newline {
1521                summary.add_assign(&D::from_text_summary(&TextSummary {
1522                    bytes: 1,
1523                    lines: Point::new(1 as u32, 0),
1524                    lines_utf16: PointUtf16::new(1 as u32, 0),
1525                    first_line_chars: 0,
1526                    last_line_chars: 0,
1527                    longest_row: 0,
1528                    longest_row_chars: 0,
1529                }));
1530            }
1531
1532            cursor.next(&());
1533        }
1534
1535        if range.end > *cursor.start() {
1536            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1537                &range.end,
1538                Bias::Right,
1539                &(),
1540            )));
1541            if let Some(excerpt) = cursor.item() {
1542                range.end = cmp::max(*cursor.start(), range.end);
1543
1544                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1545                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1546                summary.add_assign(
1547                    &excerpt
1548                        .buffer
1549                        .text_summary_for_range(excerpt_start..end_in_excerpt),
1550                );
1551            }
1552        }
1553
1554        summary
1555    }
1556
1557    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1558    where
1559        D: TextDimension + Ord + Sub<D, Output = D>,
1560    {
1561        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1562        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1563        if cursor.item().is_none() {
1564            cursor.next(&());
1565        }
1566
1567        let mut position = D::from_text_summary(&cursor.start().text);
1568        if let Some(excerpt) = cursor.item() {
1569            if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id {
1570                let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1571                let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1572                let buffer_position = cmp::min(
1573                    excerpt_buffer_end,
1574                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
1575                );
1576                if buffer_position > excerpt_buffer_start {
1577                    position.add_assign(&(buffer_position - excerpt_buffer_start));
1578                }
1579            }
1580        }
1581        position
1582    }
1583
1584    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1585    where
1586        D: TextDimension + Ord + Sub<D, Output = D>,
1587        I: 'a + IntoIterator<Item = &'a Anchor>,
1588    {
1589        if let Some(excerpt) = self.as_singleton() {
1590            return excerpt
1591                .buffer
1592                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
1593                .collect();
1594        }
1595
1596        let mut anchors = anchors.into_iter().peekable();
1597        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1598        let mut summaries = Vec::new();
1599        while let Some(anchor) = anchors.peek() {
1600            let excerpt_id = &anchor.excerpt_id;
1601            let buffer_id = anchor.buffer_id;
1602            let excerpt_anchors = iter::from_fn(|| {
1603                let anchor = anchors.peek()?;
1604                if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1605                    Some(&anchors.next().unwrap().text_anchor)
1606                } else {
1607                    None
1608                }
1609            });
1610
1611            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1612            if cursor.item().is_none() {
1613                cursor.next(&());
1614            }
1615
1616            let position = D::from_text_summary(&cursor.start().text);
1617            if let Some(excerpt) = cursor.item() {
1618                if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1619                    let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1620                    let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1621                    summaries.extend(
1622                        excerpt
1623                            .buffer
1624                            .summaries_for_anchors::<D, _>(excerpt_anchors)
1625                            .map(move |summary| {
1626                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
1627                                let mut position = position.clone();
1628                                let excerpt_buffer_start = excerpt_buffer_start.clone();
1629                                if summary > excerpt_buffer_start {
1630                                    position.add_assign(&(summary - excerpt_buffer_start));
1631                                }
1632                                position
1633                            }),
1634                    );
1635                    continue;
1636                }
1637            }
1638
1639            summaries.extend(excerpt_anchors.map(|_| position.clone()));
1640        }
1641
1642        summaries
1643    }
1644
1645    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1646    where
1647        I: 'a + IntoIterator<Item = &'a Anchor>,
1648    {
1649        let mut anchors = anchors.into_iter().enumerate().peekable();
1650        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1651        let mut result = Vec::new();
1652        while let Some((_, anchor)) = anchors.peek() {
1653            let old_excerpt_id = &anchor.excerpt_id;
1654
1655            // Find the location where this anchor's excerpt should be.
1656            cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1657            if cursor.item().is_none() {
1658                cursor.next(&());
1659            }
1660
1661            let next_excerpt = cursor.item();
1662            let prev_excerpt = cursor.prev_item();
1663
1664            // Process all of the anchors for this excerpt.
1665            while let Some((_, anchor)) = anchors.peek() {
1666                if anchor.excerpt_id != *old_excerpt_id {
1667                    break;
1668                }
1669                let mut kept_position = false;
1670                let (anchor_ix, anchor) = anchors.next().unwrap();
1671                let mut anchor = anchor.clone();
1672
1673                // Leave min and max anchors unchanged.
1674                if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1675                    kept_position = true;
1676                }
1677                // If the old excerpt still exists at this location, then leave
1678                // the anchor unchanged.
1679                else if next_excerpt.map_or(false, |excerpt| {
1680                    excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
1681                }) {
1682                    kept_position = true;
1683                }
1684                // If the old excerpt no longer exists at this location, then attempt to
1685                // find an equivalent position for this anchor in an adjacent excerpt.
1686                else {
1687                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1688                        if excerpt.contains(&anchor) {
1689                            anchor.excerpt_id = excerpt.id.clone();
1690                            kept_position = true;
1691                            break;
1692                        }
1693                    }
1694                }
1695                // If there's no adjacent excerpt that contains the anchor's position,
1696                // then report that the anchor has lost its position.
1697                if !kept_position {
1698                    anchor = if let Some(excerpt) = next_excerpt {
1699                        let mut text_anchor = excerpt
1700                            .range
1701                            .start
1702                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
1703                        if text_anchor
1704                            .cmp(&excerpt.range.end, &excerpt.buffer)
1705                            .unwrap()
1706                            .is_gt()
1707                        {
1708                            text_anchor = excerpt.range.end.clone();
1709                        }
1710                        Anchor {
1711                            buffer_id: excerpt.buffer_id,
1712                            excerpt_id: excerpt.id.clone(),
1713                            text_anchor,
1714                        }
1715                    } else if let Some(excerpt) = prev_excerpt {
1716                        let mut text_anchor = excerpt
1717                            .range
1718                            .end
1719                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
1720                        if text_anchor
1721                            .cmp(&excerpt.range.start, &excerpt.buffer)
1722                            .unwrap()
1723                            .is_lt()
1724                        {
1725                            text_anchor = excerpt.range.start.clone();
1726                        }
1727                        Anchor {
1728                            buffer_id: excerpt.buffer_id,
1729                            excerpt_id: excerpt.id.clone(),
1730                            text_anchor,
1731                        }
1732                    } else if anchor.text_anchor.bias == Bias::Left {
1733                        Anchor::min()
1734                    } else {
1735                        Anchor::max()
1736                    };
1737                }
1738
1739                result.push((anchor_ix, anchor, kept_position));
1740            }
1741        }
1742        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1743        result
1744    }
1745
1746    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1747        self.anchor_at(position, Bias::Left)
1748    }
1749
1750    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1751        self.anchor_at(position, Bias::Right)
1752    }
1753
1754    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1755        let offset = position.to_offset(self);
1756        if let Some(excerpt) = self.as_singleton() {
1757            return Anchor {
1758                buffer_id: excerpt.buffer_id,
1759                excerpt_id: excerpt.id.clone(),
1760                text_anchor: excerpt.buffer.anchor_at(offset, bias),
1761            };
1762        }
1763
1764        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1765        cursor.seek(&offset, Bias::Right, &());
1766        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1767            cursor.prev(&());
1768        }
1769        if let Some(excerpt) = cursor.item() {
1770            let mut overshoot = offset.saturating_sub(cursor.start().0);
1771            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1772                overshoot -= 1;
1773                bias = Bias::Right;
1774            }
1775
1776            let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1777            let text_anchor =
1778                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1779            Anchor {
1780                buffer_id: excerpt.buffer_id,
1781                excerpt_id: excerpt.id.clone(),
1782                text_anchor,
1783            }
1784        } else if offset == 0 && bias == Bias::Left {
1785            Anchor::min()
1786        } else {
1787            Anchor::max()
1788        }
1789    }
1790
1791    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1792        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1793        cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1794        if let Some(excerpt) = cursor.item() {
1795            if excerpt.id == excerpt_id {
1796                let text_anchor = excerpt.clip_anchor(text_anchor);
1797                drop(cursor);
1798                return Anchor {
1799                    buffer_id: excerpt.buffer_id,
1800                    excerpt_id,
1801                    text_anchor,
1802                };
1803            }
1804        }
1805        panic!("excerpt not found");
1806    }
1807
1808    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1809        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1810            true
1811        } else if let Some((buffer_id, buffer_snapshot)) =
1812            self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1813        {
1814            anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1815        } else {
1816            false
1817        }
1818    }
1819
1820    pub fn excerpt_boundaries_in_range<'a, R, T>(
1821        &'a self,
1822        range: R,
1823    ) -> impl Iterator<Item = ExcerptBoundary> + 'a
1824    where
1825        R: RangeBounds<T>,
1826        T: ToOffset,
1827    {
1828        let start_offset;
1829        let start = match range.start_bound() {
1830            Bound::Included(start) => {
1831                start_offset = start.to_offset(self);
1832                Bound::Included(start_offset)
1833            }
1834            Bound::Excluded(start) => {
1835                start_offset = start.to_offset(self);
1836                Bound::Excluded(start_offset)
1837            }
1838            Bound::Unbounded => {
1839                start_offset = 0;
1840                Bound::Unbounded
1841            }
1842        };
1843        let end = match range.end_bound() {
1844            Bound::Included(end) => Bound::Included(end.to_offset(self)),
1845            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
1846            Bound::Unbounded => Bound::Unbounded,
1847        };
1848        let bounds = (start, end);
1849
1850        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1851        cursor.seek(&start_offset, Bias::Right, &());
1852        if cursor.item().is_none() {
1853            cursor.prev(&());
1854        }
1855        if !bounds.contains(&cursor.start().0) {
1856            cursor.next(&());
1857        }
1858
1859        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
1860        std::iter::from_fn(move || {
1861            if self.singleton {
1862                None
1863            } else if bounds.contains(&cursor.start().0) {
1864                let excerpt = cursor.item()?;
1865                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
1866                let boundary = ExcerptBoundary {
1867                    row: cursor.start().1.row,
1868                    buffer: excerpt.buffer.clone(),
1869                    range: excerpt.range.clone(),
1870                    starts_new_buffer,
1871                };
1872
1873                prev_buffer_id = Some(excerpt.buffer_id);
1874                cursor.next(&());
1875                Some(boundary)
1876            } else {
1877                None
1878            }
1879        })
1880    }
1881
1882    pub fn parse_count(&self) -> usize {
1883        self.parse_count
1884    }
1885
1886    pub fn enclosing_bracket_ranges<T: ToOffset>(
1887        &self,
1888        range: Range<T>,
1889    ) -> Option<(Range<usize>, Range<usize>)> {
1890        let range = range.start.to_offset(self)..range.end.to_offset(self);
1891
1892        let mut cursor = self.excerpts.cursor::<usize>();
1893        cursor.seek(&range.start, Bias::Right, &());
1894        let start_excerpt = cursor.item();
1895
1896        cursor.seek(&range.end, Bias::Right, &());
1897        let end_excerpt = cursor.item();
1898
1899        start_excerpt
1900            .zip(end_excerpt)
1901            .and_then(|(start_excerpt, end_excerpt)| {
1902                if start_excerpt.id != end_excerpt.id {
1903                    return None;
1904                }
1905
1906                let excerpt_buffer_start =
1907                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1908                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1909
1910                let start_in_buffer =
1911                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1912                let end_in_buffer =
1913                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1914                let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1915                    .buffer
1916                    .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1917
1918                if start_bracket_range.start >= excerpt_buffer_start
1919                    && end_bracket_range.end < excerpt_buffer_end
1920                {
1921                    start_bracket_range.start =
1922                        cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1923                    start_bracket_range.end =
1924                        cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1925                    end_bracket_range.start =
1926                        cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1927                    end_bracket_range.end =
1928                        cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1929                    Some((start_bracket_range, end_bracket_range))
1930                } else {
1931                    None
1932                }
1933            })
1934    }
1935
1936    pub fn diagnostics_update_count(&self) -> usize {
1937        self.diagnostics_update_count
1938    }
1939
1940    pub fn excerpt_update_count(&self) -> usize {
1941        self.excerpt_update_count
1942    }
1943
1944    pub fn language(&self) -> Option<&Arc<Language>> {
1945        self.excerpts
1946            .iter()
1947            .next()
1948            .and_then(|excerpt| excerpt.buffer.language())
1949    }
1950
1951    pub fn is_dirty(&self) -> bool {
1952        self.is_dirty
1953    }
1954
1955    pub fn has_conflict(&self) -> bool {
1956        self.has_conflict
1957    }
1958
1959    pub fn diagnostic_group<'a, O>(
1960        &'a self,
1961        group_id: usize,
1962    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1963    where
1964        O: text::FromAnchor + 'a,
1965    {
1966        self.as_singleton()
1967            .into_iter()
1968            .flat_map(move |excerpt| excerpt.buffer.diagnostic_group(group_id))
1969    }
1970
1971    pub fn diagnostics_in_range<'a, T, O>(
1972        &'a self,
1973        range: Range<T>,
1974    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1975    where
1976        T: 'a + ToOffset,
1977        O: 'a + text::FromAnchor,
1978    {
1979        self.as_singleton().into_iter().flat_map(move |excerpt| {
1980            excerpt
1981                .buffer
1982                .diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1983        })
1984    }
1985
1986    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1987        let range = range.start.to_offset(self)..range.end.to_offset(self);
1988
1989        let mut cursor = self.excerpts.cursor::<usize>();
1990        cursor.seek(&range.start, Bias::Right, &());
1991        let start_excerpt = cursor.item();
1992
1993        cursor.seek(&range.end, Bias::Right, &());
1994        let end_excerpt = cursor.item();
1995
1996        start_excerpt
1997            .zip(end_excerpt)
1998            .and_then(|(start_excerpt, end_excerpt)| {
1999                if start_excerpt.id != end_excerpt.id {
2000                    return None;
2001                }
2002
2003                let excerpt_buffer_start =
2004                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
2005                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
2006
2007                let start_in_buffer =
2008                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2009                let end_in_buffer =
2010                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2011                let mut ancestor_buffer_range = start_excerpt
2012                    .buffer
2013                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2014                ancestor_buffer_range.start =
2015                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2016                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2017
2018                let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
2019                let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
2020                Some(start..end)
2021            })
2022    }
2023
2024    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2025        let excerpt = self.as_singleton()?;
2026        let outline = excerpt.buffer.outline(theme)?;
2027        Some(Outline::new(
2028            outline
2029                .items
2030                .into_iter()
2031                .map(|item| OutlineItem {
2032                    depth: item.depth,
2033                    range: self.anchor_in_excerpt(excerpt.id.clone(), item.range.start)
2034                        ..self.anchor_in_excerpt(excerpt.id.clone(), item.range.end),
2035                    text: item.text,
2036                    highlight_ranges: item.highlight_ranges,
2037                    name_ranges: item.name_ranges,
2038                })
2039                .collect(),
2040        ))
2041    }
2042
2043    fn buffer_snapshot_for_excerpt<'a>(
2044        &'a self,
2045        excerpt_id: &'a ExcerptId,
2046    ) -> Option<(usize, &'a BufferSnapshot)> {
2047        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2048        cursor.seek(&Some(excerpt_id), Bias::Left, &());
2049        if let Some(excerpt) = cursor.item() {
2050            if excerpt.id == *excerpt_id {
2051                return Some((excerpt.buffer_id, &excerpt.buffer));
2052            }
2053        }
2054        None
2055    }
2056
2057    pub fn remote_selections_in_range<'a>(
2058        &'a self,
2059        range: &'a Range<Anchor>,
2060    ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
2061        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2062        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
2063        cursor
2064            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
2065            .flat_map(move |excerpt| {
2066                let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
2067                if excerpt.id == range.start.excerpt_id {
2068                    query_range.start = range.start.text_anchor.clone();
2069                }
2070                if excerpt.id == range.end.excerpt_id {
2071                    query_range.end = range.end.text_anchor.clone();
2072                }
2073
2074                excerpt
2075                    .buffer
2076                    .remote_selections_in_range(query_range)
2077                    .flat_map(move |(replica_id, selections)| {
2078                        selections.map(move |selection| {
2079                            let mut start = Anchor {
2080                                buffer_id: excerpt.buffer_id,
2081                                excerpt_id: excerpt.id.clone(),
2082                                text_anchor: selection.start.clone(),
2083                            };
2084                            let mut end = Anchor {
2085                                buffer_id: excerpt.buffer_id,
2086                                excerpt_id: excerpt.id.clone(),
2087                                text_anchor: selection.end.clone(),
2088                            };
2089                            if range.start.cmp(&start, self).unwrap().is_gt() {
2090                                start = range.start.clone();
2091                            }
2092                            if range.end.cmp(&end, self).unwrap().is_lt() {
2093                                end = range.end.clone();
2094                            }
2095
2096                            (
2097                                replica_id,
2098                                Selection {
2099                                    id: selection.id,
2100                                    start,
2101                                    end,
2102                                    reversed: selection.reversed,
2103                                    goal: selection.goal,
2104                                },
2105                            )
2106                        })
2107                    })
2108            })
2109    }
2110}
2111
2112impl History {
2113    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2114        self.transaction_depth += 1;
2115        if self.transaction_depth == 1 {
2116            let id = self.next_transaction_id.tick();
2117            self.undo_stack.push(Transaction {
2118                id,
2119                buffer_transactions: Default::default(),
2120                first_edit_at: now,
2121                last_edit_at: now,
2122            });
2123            Some(id)
2124        } else {
2125            None
2126        }
2127    }
2128
2129    fn end_transaction(
2130        &mut self,
2131        now: Instant,
2132        buffer_transactions: HashSet<(usize, TransactionId)>,
2133    ) -> bool {
2134        assert_ne!(self.transaction_depth, 0);
2135        self.transaction_depth -= 1;
2136        if self.transaction_depth == 0 {
2137            if buffer_transactions.is_empty() {
2138                self.undo_stack.pop();
2139                false
2140            } else {
2141                let transaction = self.undo_stack.last_mut().unwrap();
2142                transaction.last_edit_at = now;
2143                transaction.buffer_transactions.extend(buffer_transactions);
2144                true
2145            }
2146        } else {
2147            false
2148        }
2149    }
2150
2151    fn pop_undo(&mut self) -> Option<&Transaction> {
2152        assert_eq!(self.transaction_depth, 0);
2153        if let Some(transaction) = self.undo_stack.pop() {
2154            self.redo_stack.push(transaction);
2155            self.redo_stack.last()
2156        } else {
2157            None
2158        }
2159    }
2160
2161    fn pop_redo(&mut self) -> Option<&Transaction> {
2162        assert_eq!(self.transaction_depth, 0);
2163        if let Some(transaction) = self.redo_stack.pop() {
2164            self.undo_stack.push(transaction);
2165            self.undo_stack.last()
2166        } else {
2167            None
2168        }
2169    }
2170
2171    fn group(&mut self) -> Option<TransactionId> {
2172        let mut new_len = self.undo_stack.len();
2173        let mut transactions = self.undo_stack.iter_mut();
2174
2175        if let Some(mut transaction) = transactions.next_back() {
2176            while let Some(prev_transaction) = transactions.next_back() {
2177                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
2178                {
2179                    transaction = prev_transaction;
2180                    new_len -= 1;
2181                } else {
2182                    break;
2183                }
2184            }
2185        }
2186
2187        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2188        if let Some(last_transaction) = transactions_to_keep.last_mut() {
2189            if let Some(transaction) = transactions_to_merge.last() {
2190                last_transaction.last_edit_at = transaction.last_edit_at;
2191            }
2192        }
2193
2194        self.undo_stack.truncate(new_len);
2195        self.undo_stack.last().map(|t| t.id)
2196    }
2197}
2198
2199impl Excerpt {
2200    fn new(
2201        id: ExcerptId,
2202        buffer_id: usize,
2203        buffer: BufferSnapshot,
2204        range: Range<text::Anchor>,
2205        has_trailing_newline: bool,
2206    ) -> Self {
2207        Excerpt {
2208            id,
2209            max_buffer_row: range.end.to_point(&buffer).row,
2210            text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
2211            buffer_id,
2212            buffer,
2213            range,
2214            has_trailing_newline,
2215        }
2216    }
2217
2218    fn chunks_in_range<'a>(
2219        &'a self,
2220        range: Range<usize>,
2221        language_aware: bool,
2222    ) -> ExcerptChunks<'a> {
2223        let content_start = self.range.start.to_offset(&self.buffer);
2224        let chunks_start = content_start + range.start;
2225        let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2226
2227        let footer_height = if self.has_trailing_newline
2228            && range.start <= self.text_summary.bytes
2229            && range.end > self.text_summary.bytes
2230        {
2231            1
2232        } else {
2233            0
2234        };
2235
2236        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2237
2238        ExcerptChunks {
2239            content_chunks,
2240            footer_height,
2241        }
2242    }
2243
2244    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2245        let content_start = self.range.start.to_offset(&self.buffer);
2246        let bytes_start = content_start + range.start;
2247        let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2248        let footer_height = if self.has_trailing_newline
2249            && range.start <= self.text_summary.bytes
2250            && range.end > self.text_summary.bytes
2251        {
2252            1
2253        } else {
2254            0
2255        };
2256        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2257
2258        ExcerptBytes {
2259            content_bytes,
2260            footer_height,
2261        }
2262    }
2263
2264    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2265        if text_anchor
2266            .cmp(&self.range.start, &self.buffer)
2267            .unwrap()
2268            .is_lt()
2269        {
2270            self.range.start.clone()
2271        } else if text_anchor
2272            .cmp(&self.range.end, &self.buffer)
2273            .unwrap()
2274            .is_gt()
2275        {
2276            self.range.end.clone()
2277        } else {
2278            text_anchor
2279        }
2280    }
2281
2282    fn contains(&self, anchor: &Anchor) -> bool {
2283        self.buffer_id == anchor.buffer_id
2284            && self
2285                .range
2286                .start
2287                .cmp(&anchor.text_anchor, &self.buffer)
2288                .unwrap()
2289                .is_le()
2290            && self
2291                .range
2292                .end
2293                .cmp(&anchor.text_anchor, &self.buffer)
2294                .unwrap()
2295                .is_ge()
2296    }
2297}
2298
2299impl fmt::Debug for Excerpt {
2300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2301        f.debug_struct("Excerpt")
2302            .field("id", &self.id)
2303            .field("buffer_id", &self.buffer_id)
2304            .field("range", &self.range)
2305            .field("text_summary", &self.text_summary)
2306            .field("has_trailing_newline", &self.has_trailing_newline)
2307            .finish()
2308    }
2309}
2310
2311impl sum_tree::Item for Excerpt {
2312    type Summary = ExcerptSummary;
2313
2314    fn summary(&self) -> Self::Summary {
2315        let mut text = self.text_summary.clone();
2316        if self.has_trailing_newline {
2317            text += TextSummary::from("\n");
2318        }
2319        ExcerptSummary {
2320            excerpt_id: self.id.clone(),
2321            max_buffer_row: self.max_buffer_row,
2322            text,
2323        }
2324    }
2325}
2326
2327impl sum_tree::Summary for ExcerptSummary {
2328    type Context = ();
2329
2330    fn add_summary(&mut self, summary: &Self, _: &()) {
2331        debug_assert!(summary.excerpt_id > self.excerpt_id);
2332        self.excerpt_id = summary.excerpt_id.clone();
2333        self.text.add_summary(&summary.text, &());
2334        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2335    }
2336}
2337
2338impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2339    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2340        *self += &summary.text;
2341    }
2342}
2343
2344impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2345    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2346        *self += summary.text.bytes;
2347    }
2348}
2349
2350impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2351    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2352        Ord::cmp(self, &cursor_location.text.bytes)
2353    }
2354}
2355
2356impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2357    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2358        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2359    }
2360}
2361
2362impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2363    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2364        *self += summary.text.lines;
2365    }
2366}
2367
2368impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2369    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2370        *self += summary.text.lines_utf16
2371    }
2372}
2373
2374impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2375    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2376        *self = Some(&summary.excerpt_id);
2377    }
2378}
2379
2380impl<'a> MultiBufferRows<'a> {
2381    pub fn seek(&mut self, row: u32) {
2382        self.buffer_row_range = 0..0;
2383
2384        self.excerpts
2385            .seek_forward(&Point::new(row, 0), Bias::Right, &());
2386        if self.excerpts.item().is_none() {
2387            self.excerpts.prev(&());
2388
2389            if self.excerpts.item().is_none() && row == 0 {
2390                self.buffer_row_range = 0..1;
2391                return;
2392            }
2393        }
2394
2395        if let Some(excerpt) = self.excerpts.item() {
2396            let overshoot = row - self.excerpts.start().row;
2397            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2398            self.buffer_row_range.start = excerpt_start + overshoot;
2399            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2400        }
2401    }
2402}
2403
2404impl<'a> Iterator for MultiBufferRows<'a> {
2405    type Item = Option<u32>;
2406
2407    fn next(&mut self) -> Option<Self::Item> {
2408        loop {
2409            if !self.buffer_row_range.is_empty() {
2410                let row = Some(self.buffer_row_range.start);
2411                self.buffer_row_range.start += 1;
2412                return Some(row);
2413            }
2414            self.excerpts.item()?;
2415            self.excerpts.next(&());
2416            let excerpt = self.excerpts.item()?;
2417            self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2418            self.buffer_row_range.end =
2419                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2420        }
2421    }
2422}
2423
2424impl<'a> MultiBufferChunks<'a> {
2425    pub fn offset(&self) -> usize {
2426        self.range.start
2427    }
2428
2429    pub fn seek(&mut self, offset: usize) {
2430        self.range.start = offset;
2431        self.excerpts.seek(&offset, Bias::Right, &());
2432        if let Some(excerpt) = self.excerpts.item() {
2433            self.excerpt_chunks = Some(excerpt.chunks_in_range(
2434                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2435                self.language_aware,
2436            ));
2437        } else {
2438            self.excerpt_chunks = None;
2439        }
2440    }
2441}
2442
2443impl<'a> Iterator for MultiBufferChunks<'a> {
2444    type Item = Chunk<'a>;
2445
2446    fn next(&mut self) -> Option<Self::Item> {
2447        if self.range.is_empty() {
2448            None
2449        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2450            self.range.start += chunk.text.len();
2451            Some(chunk)
2452        } else {
2453            self.excerpts.next(&());
2454            let excerpt = self.excerpts.item()?;
2455            self.excerpt_chunks = Some(excerpt.chunks_in_range(
2456                0..self.range.end - self.excerpts.start(),
2457                self.language_aware,
2458            ));
2459            self.next()
2460        }
2461    }
2462}
2463
2464impl<'a> MultiBufferBytes<'a> {
2465    fn consume(&mut self, len: usize) {
2466        self.range.start += len;
2467        self.chunk = &self.chunk[len..];
2468
2469        if !self.range.is_empty() && self.chunk.is_empty() {
2470            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2471                self.chunk = chunk;
2472            } else {
2473                self.excerpts.next(&());
2474                if let Some(excerpt) = self.excerpts.item() {
2475                    let mut excerpt_bytes =
2476                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2477                    self.chunk = excerpt_bytes.next().unwrap();
2478                    self.excerpt_bytes = Some(excerpt_bytes);
2479                }
2480            }
2481        }
2482    }
2483}
2484
2485impl<'a> Iterator for MultiBufferBytes<'a> {
2486    type Item = &'a [u8];
2487
2488    fn next(&mut self) -> Option<Self::Item> {
2489        let chunk = self.chunk;
2490        if chunk.is_empty() {
2491            None
2492        } else {
2493            self.consume(chunk.len());
2494            Some(chunk)
2495        }
2496    }
2497}
2498
2499impl<'a> io::Read for MultiBufferBytes<'a> {
2500    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2501        let len = cmp::min(buf.len(), self.chunk.len());
2502        buf[..len].copy_from_slice(&self.chunk[..len]);
2503        if len > 0 {
2504            self.consume(len);
2505        }
2506        Ok(len)
2507    }
2508}
2509
2510impl<'a> Iterator for ExcerptBytes<'a> {
2511    type Item = &'a [u8];
2512
2513    fn next(&mut self) -> Option<Self::Item> {
2514        if let Some(chunk) = self.content_bytes.next() {
2515            if !chunk.is_empty() {
2516                return Some(chunk);
2517            }
2518        }
2519
2520        if self.footer_height > 0 {
2521            let result = &NEWLINES[..self.footer_height];
2522            self.footer_height = 0;
2523            return Some(result);
2524        }
2525
2526        None
2527    }
2528}
2529
2530impl<'a> Iterator for ExcerptChunks<'a> {
2531    type Item = Chunk<'a>;
2532
2533    fn next(&mut self) -> Option<Self::Item> {
2534        if let Some(chunk) = self.content_chunks.next() {
2535            return Some(chunk);
2536        }
2537
2538        if self.footer_height > 0 {
2539            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2540            self.footer_height = 0;
2541            return Some(Chunk {
2542                text,
2543                ..Default::default()
2544            });
2545        }
2546
2547        None
2548    }
2549}
2550
2551impl ToOffset for Point {
2552    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2553        snapshot.point_to_offset(*self)
2554    }
2555}
2556
2557impl ToOffset for PointUtf16 {
2558    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2559        snapshot.point_utf16_to_offset(*self)
2560    }
2561}
2562
2563impl ToOffset for usize {
2564    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2565        assert!(*self <= snapshot.len(), "offset is out of range");
2566        *self
2567    }
2568}
2569
2570impl ToPoint for usize {
2571    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2572        snapshot.offset_to_point(*self)
2573    }
2574}
2575
2576impl ToPoint for Point {
2577    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2578        *self
2579    }
2580}
2581
2582impl ToPointUtf16 for usize {
2583    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
2584        snapshot.offset_to_point_utf16(*self)
2585    }
2586}
2587
2588impl ToPointUtf16 for Point {
2589    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
2590        snapshot.point_to_point_utf16(*self)
2591    }
2592}
2593
2594impl ToPointUtf16 for PointUtf16 {
2595    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
2596        *self
2597    }
2598}
2599
2600pub fn char_kind(c: char) -> CharKind {
2601    if c == '\n' {
2602        CharKind::Newline
2603    } else if c.is_whitespace() {
2604        CharKind::Whitespace
2605    } else if c.is_alphanumeric() || c == '_' {
2606        CharKind::Word
2607    } else {
2608        CharKind::Punctuation
2609    }
2610}
2611
2612#[cfg(test)]
2613mod tests {
2614    use super::*;
2615    use gpui::MutableAppContext;
2616    use language::{Buffer, Rope};
2617    use rand::prelude::*;
2618    use std::env;
2619    use text::{Point, RandomCharIter};
2620    use util::test::sample_text;
2621
2622    #[gpui::test]
2623    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2624        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2625        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2626
2627        let snapshot = multibuffer.read(cx).snapshot(cx);
2628        assert_eq!(snapshot.text(), buffer.read(cx).text());
2629
2630        assert_eq!(
2631            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2632            (0..buffer.read(cx).row_count())
2633                .map(Some)
2634                .collect::<Vec<_>>()
2635        );
2636
2637        buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2638        let snapshot = multibuffer.read(cx).snapshot(cx);
2639
2640        assert_eq!(snapshot.text(), buffer.read(cx).text());
2641        assert_eq!(
2642            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2643            (0..buffer.read(cx).row_count())
2644                .map(Some)
2645                .collect::<Vec<_>>()
2646        );
2647    }
2648
2649    #[gpui::test]
2650    fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2651        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2652        let guest_buffer = cx.add_model(|cx| {
2653            let message = host_buffer.read(cx).to_proto();
2654            Buffer::from_proto(1, message, None, cx).unwrap()
2655        });
2656        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2657        let snapshot = multibuffer.read(cx).snapshot(cx);
2658        assert_eq!(snapshot.text(), "a");
2659
2660        guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2661        let snapshot = multibuffer.read(cx).snapshot(cx);
2662        assert_eq!(snapshot.text(), "ab");
2663
2664        guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2665        let snapshot = multibuffer.read(cx).snapshot(cx);
2666        assert_eq!(snapshot.text(), "abc");
2667    }
2668
2669    #[gpui::test]
2670    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2671        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2672        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2673        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2674
2675        let subscription = multibuffer.update(cx, |multibuffer, cx| {
2676            let subscription = multibuffer.subscribe();
2677            multibuffer.push_excerpt(
2678                ExcerptProperties {
2679                    buffer: &buffer_1,
2680                    range: Point::new(1, 2)..Point::new(2, 5),
2681                },
2682                cx,
2683            );
2684            assert_eq!(
2685                subscription.consume().into_inner(),
2686                [Edit {
2687                    old: 0..0,
2688                    new: 0..10
2689                }]
2690            );
2691
2692            multibuffer.push_excerpt(
2693                ExcerptProperties {
2694                    buffer: &buffer_1,
2695                    range: Point::new(3, 3)..Point::new(4, 4),
2696                },
2697                cx,
2698            );
2699            multibuffer.push_excerpt(
2700                ExcerptProperties {
2701                    buffer: &buffer_2,
2702                    range: Point::new(3, 1)..Point::new(3, 3),
2703                },
2704                cx,
2705            );
2706            assert_eq!(
2707                subscription.consume().into_inner(),
2708                [Edit {
2709                    old: 10..10,
2710                    new: 10..22
2711                }]
2712            );
2713
2714            subscription
2715        });
2716
2717        let snapshot = multibuffer.read(cx).snapshot(cx);
2718        assert_eq!(
2719            snapshot.text(),
2720            concat!(
2721                "bbbb\n",  // Preserve newlines
2722                "ccccc\n", //
2723                "ddd\n",   //
2724                "eeee\n",  //
2725                "jj"       //
2726            )
2727        );
2728        assert_eq!(
2729            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2730            [Some(1), Some(2), Some(3), Some(4), Some(3)]
2731        );
2732        assert_eq!(
2733            snapshot.buffer_rows(2).collect::<Vec<_>>(),
2734            [Some(3), Some(4), Some(3)]
2735        );
2736        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2737        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2738
2739        assert_eq!(
2740            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
2741            &[
2742                (0, "bbbb\nccccc".to_string(), true),
2743                (2, "ddd\neeee".to_string(), false),
2744                (4, "jj".to_string(), true),
2745            ]
2746        );
2747        assert_eq!(
2748            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
2749            &[(0, "bbbb\nccccc".to_string(), true)]
2750        );
2751        assert_eq!(
2752            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
2753            &[]
2754        );
2755        assert_eq!(
2756            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
2757            &[]
2758        );
2759        assert_eq!(
2760            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
2761            &[(2, "ddd\neeee".to_string(), false)]
2762        );
2763        assert_eq!(
2764            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
2765            &[(2, "ddd\neeee".to_string(), false)]
2766        );
2767        assert_eq!(
2768            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
2769            &[(2, "ddd\neeee".to_string(), false)]
2770        );
2771        assert_eq!(
2772            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
2773            &[(4, "jj".to_string(), true)]
2774        );
2775        assert_eq!(
2776            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
2777            &[]
2778        );
2779
2780        buffer_1.update(cx, |buffer, cx| {
2781            buffer.edit(
2782                [
2783                    Point::new(0, 0)..Point::new(0, 0),
2784                    Point::new(2, 1)..Point::new(2, 3),
2785                ],
2786                "\n",
2787                cx,
2788            );
2789        });
2790
2791        let snapshot = multibuffer.read(cx).snapshot(cx);
2792        assert_eq!(
2793            snapshot.text(),
2794            concat!(
2795                "bbbb\n", // Preserve newlines
2796                "c\n",    //
2797                "cc\n",   //
2798                "ddd\n",  //
2799                "eeee\n", //
2800                "jj"      //
2801            )
2802        );
2803
2804        assert_eq!(
2805            subscription.consume().into_inner(),
2806            [Edit {
2807                old: 6..8,
2808                new: 6..7
2809            }]
2810        );
2811
2812        let snapshot = multibuffer.read(cx).snapshot(cx);
2813        assert_eq!(
2814            snapshot.clip_point(Point::new(0, 5), Bias::Left),
2815            Point::new(0, 4)
2816        );
2817        assert_eq!(
2818            snapshot.clip_point(Point::new(0, 5), Bias::Right),
2819            Point::new(0, 4)
2820        );
2821        assert_eq!(
2822            snapshot.clip_point(Point::new(5, 1), Bias::Right),
2823            Point::new(5, 1)
2824        );
2825        assert_eq!(
2826            snapshot.clip_point(Point::new(5, 2), Bias::Right),
2827            Point::new(5, 2)
2828        );
2829        assert_eq!(
2830            snapshot.clip_point(Point::new(5, 3), Bias::Right),
2831            Point::new(5, 2)
2832        );
2833
2834        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2835            let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2836            multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2837            multibuffer.snapshot(cx)
2838        });
2839
2840        assert_eq!(
2841            snapshot.text(),
2842            concat!(
2843                "bbbb\n", // Preserve newlines
2844                "c\n",    //
2845                "cc\n",   //
2846                "ddd\n",  //
2847                "eeee",   //
2848            )
2849        );
2850
2851        fn boundaries_in_range(
2852            range: Range<Point>,
2853            snapshot: &MultiBufferSnapshot,
2854        ) -> Vec<(u32, String, bool)> {
2855            snapshot
2856                .excerpt_boundaries_in_range(range)
2857                .map(|boundary| {
2858                    (
2859                        boundary.row,
2860                        boundary
2861                            .buffer
2862                            .text_for_range(boundary.range)
2863                            .collect::<String>(),
2864                        boundary.starts_new_buffer,
2865                    )
2866                })
2867                .collect::<Vec<_>>()
2868        }
2869    }
2870
2871    #[gpui::test]
2872    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2873        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2874
2875        let snapshot = multibuffer.read(cx).snapshot(cx);
2876        assert_eq!(snapshot.text(), "");
2877        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2878        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2879    }
2880
2881    #[gpui::test]
2882    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2883        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2884        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2885        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2886        buffer.update(cx, |buffer, cx| {
2887            buffer.edit([0..0], "X", cx);
2888            buffer.edit([5..5], "Y", cx);
2889        });
2890        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2891
2892        assert_eq!(old_snapshot.text(), "abcd");
2893        assert_eq!(new_snapshot.text(), "XabcdY");
2894
2895        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2896        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2897        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2898        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2899    }
2900
2901    #[gpui::test]
2902    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2903        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2904        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2905        let multibuffer = cx.add_model(|cx| {
2906            let mut multibuffer = MultiBuffer::new(0);
2907            multibuffer.push_excerpt(
2908                ExcerptProperties {
2909                    buffer: &buffer_1,
2910                    range: 0..4,
2911                },
2912                cx,
2913            );
2914            multibuffer.push_excerpt(
2915                ExcerptProperties {
2916                    buffer: &buffer_2,
2917                    range: 0..5,
2918                },
2919                cx,
2920            );
2921            multibuffer
2922        });
2923        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2924
2925        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2926        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2927        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2928        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2929        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2930        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2931
2932        buffer_1.update(cx, |buffer, cx| {
2933            buffer.edit([0..0], "W", cx);
2934            buffer.edit([5..5], "X", cx);
2935        });
2936        buffer_2.update(cx, |buffer, cx| {
2937            buffer.edit([0..0], "Y", cx);
2938            buffer.edit([6..0], "Z", cx);
2939        });
2940        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2941
2942        assert_eq!(old_snapshot.text(), "abcd\nefghi");
2943        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2944
2945        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2946        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2947        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2948        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2949        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2950        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2951        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2952        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2953        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2954        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2955    }
2956
2957    #[gpui::test]
2958    fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
2959        cx: &mut MutableAppContext,
2960    ) {
2961        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2962        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
2963        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2964
2965        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
2966        // Add an excerpt from buffer 1 that spans this new insertion.
2967        buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
2968        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
2969            multibuffer.push_excerpt(
2970                ExcerptProperties {
2971                    buffer: &buffer_1,
2972                    range: 0..7,
2973                },
2974                cx,
2975            )
2976        });
2977
2978        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
2979        assert_eq!(snapshot_1.text(), "abcd123");
2980
2981        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
2982        let (excerpt_id_2, excerpt_id_3, _) = multibuffer.update(cx, |multibuffer, cx| {
2983            multibuffer.remove_excerpts([&excerpt_id_1], cx);
2984            (
2985                multibuffer.push_excerpt(
2986                    ExcerptProperties {
2987                        buffer: &buffer_2,
2988                        range: 0..4,
2989                    },
2990                    cx,
2991                ),
2992                multibuffer.push_excerpt(
2993                    ExcerptProperties {
2994                        buffer: &buffer_2,
2995                        range: 6..10,
2996                    },
2997                    cx,
2998                ),
2999                multibuffer.push_excerpt(
3000                    ExcerptProperties {
3001                        buffer: &buffer_2,
3002                        range: 12..16,
3003                    },
3004                    cx,
3005                ),
3006            )
3007        });
3008        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
3009        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
3010
3011        // The old excerpt id has been reused.
3012        assert_eq!(excerpt_id_2, excerpt_id_1);
3013
3014        // Resolve some anchors from the previous snapshot in the new snapshot.
3015        // Although there is still an excerpt with the same id, it is for
3016        // a different buffer, so we don't attempt to resolve the old text
3017        // anchor in the new buffer.
3018        assert_eq!(
3019            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
3020            0
3021        );
3022        assert_eq!(
3023            snapshot_2.summaries_for_anchors::<usize, _>(&[
3024                snapshot_1.anchor_before(2),
3025                snapshot_1.anchor_after(3)
3026            ]),
3027            vec![0, 0]
3028        );
3029        let refresh =
3030            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
3031        assert_eq!(
3032            refresh,
3033            &[
3034                (0, snapshot_2.anchor_before(0), false),
3035                (1, snapshot_2.anchor_after(0), false),
3036            ]
3037        );
3038
3039        // Replace the middle excerpt with a smaller excerpt in buffer 2,
3040        // that intersects the old excerpt.
3041        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
3042            multibuffer.remove_excerpts([&excerpt_id_3], cx);
3043            multibuffer.insert_excerpt_after(
3044                &excerpt_id_3,
3045                ExcerptProperties {
3046                    buffer: &buffer_2,
3047                    range: 5..8,
3048                },
3049                cx,
3050            )
3051        });
3052
3053        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
3054        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
3055        assert_ne!(excerpt_id_5, excerpt_id_3);
3056
3057        // Resolve some anchors from the previous snapshot in the new snapshot.
3058        // The anchor in the middle excerpt snaps to the beginning of the
3059        // excerpt, since it is not
3060        let anchors = [
3061            snapshot_2.anchor_before(0),
3062            snapshot_2.anchor_after(2),
3063            snapshot_2.anchor_after(6),
3064            snapshot_2.anchor_after(14),
3065        ];
3066        assert_eq!(
3067            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
3068            &[0, 2, 9, 13]
3069        );
3070
3071        let new_anchors = snapshot_3.refresh_anchors(&anchors);
3072        assert_eq!(
3073            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
3074            &[(0, true), (1, true), (2, true), (3, true)]
3075        );
3076        assert_eq!(
3077            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
3078            &[0, 2, 7, 13]
3079        );
3080    }
3081
3082    #[gpui::test(iterations = 100)]
3083    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
3084        let operations = env::var("OPERATIONS")
3085            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3086            .unwrap_or(10);
3087
3088        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
3089        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3090        let mut excerpt_ids = Vec::new();
3091        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
3092        let mut anchors = Vec::new();
3093        let mut old_versions = Vec::new();
3094
3095        for _ in 0..operations {
3096            match rng.gen_range(0..100) {
3097                0..=19 if !buffers.is_empty() => {
3098                    let buffer = buffers.choose(&mut rng).unwrap();
3099                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
3100                }
3101                20..=29 if !expected_excerpts.is_empty() => {
3102                    let mut ids_to_remove = vec![];
3103                    for _ in 0..rng.gen_range(1..=3) {
3104                        if expected_excerpts.is_empty() {
3105                            break;
3106                        }
3107
3108                        let ix = rng.gen_range(0..expected_excerpts.len());
3109                        ids_to_remove.push(excerpt_ids.remove(ix));
3110                        let (buffer, range) = expected_excerpts.remove(ix);
3111                        let buffer = buffer.read(cx);
3112                        log::info!(
3113                            "Removing excerpt {}: {:?}",
3114                            ix,
3115                            buffer
3116                                .text_for_range(range.to_offset(&buffer))
3117                                .collect::<String>(),
3118                        );
3119                    }
3120                    ids_to_remove.sort_unstable();
3121                    multibuffer.update(cx, |multibuffer, cx| {
3122                        multibuffer.remove_excerpts(&ids_to_remove, cx)
3123                    });
3124                }
3125                30..=39 if !expected_excerpts.is_empty() => {
3126                    let multibuffer = multibuffer.read(cx).read(cx);
3127                    let offset =
3128                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
3129                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
3130                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
3131                    anchors.push(multibuffer.anchor_at(offset, bias));
3132                    anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
3133                }
3134                40..=44 if !anchors.is_empty() => {
3135                    let multibuffer = multibuffer.read(cx).read(cx);
3136
3137                    anchors = multibuffer
3138                        .refresh_anchors(&anchors)
3139                        .into_iter()
3140                        .map(|a| a.1)
3141                        .collect();
3142
3143                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
3144                    // overshoot its boundaries.
3145                    let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
3146                    for anchor in &anchors {
3147                        if anchor.excerpt_id == ExcerptId::min()
3148                            || anchor.excerpt_id == ExcerptId::max()
3149                        {
3150                            continue;
3151                        }
3152
3153                        cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
3154                        let excerpt = cursor.item().unwrap();
3155                        assert_eq!(excerpt.id, anchor.excerpt_id);
3156                        assert!(excerpt.contains(anchor));
3157                    }
3158                }
3159                _ => {
3160                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
3161                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
3162                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
3163                        buffers.last().unwrap()
3164                    } else {
3165                        buffers.choose(&mut rng).unwrap()
3166                    };
3167
3168                    let buffer = buffer_handle.read(cx);
3169                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3170                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3171                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3172                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3173                    let prev_excerpt_id = excerpt_ids
3174                        .get(prev_excerpt_ix)
3175                        .cloned()
3176                        .unwrap_or(ExcerptId::max());
3177                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3178
3179                    log::info!(
3180                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3181                        excerpt_ix,
3182                        expected_excerpts.len(),
3183                        buffer_handle.id(),
3184                        buffer.text(),
3185                        start_ix..end_ix,
3186                        &buffer.text()[start_ix..end_ix]
3187                    );
3188
3189                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3190                        multibuffer.insert_excerpt_after(
3191                            &prev_excerpt_id,
3192                            ExcerptProperties {
3193                                buffer: &buffer_handle,
3194                                range: start_ix..end_ix,
3195                            },
3196                            cx,
3197                        )
3198                    });
3199
3200                    excerpt_ids.insert(excerpt_ix, excerpt_id);
3201                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3202                }
3203            }
3204
3205            if rng.gen_bool(0.3) {
3206                multibuffer.update(cx, |multibuffer, cx| {
3207                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3208                })
3209            }
3210
3211            let snapshot = multibuffer.read(cx).snapshot(cx);
3212
3213            let mut excerpt_starts = Vec::new();
3214            let mut expected_text = String::new();
3215            let mut expected_buffer_rows = Vec::new();
3216            for (buffer, range) in &expected_excerpts {
3217                let buffer = buffer.read(cx);
3218                let buffer_range = range.to_offset(buffer);
3219
3220                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3221                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3222                expected_text.push('\n');
3223
3224                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3225                    ..=buffer.offset_to_point(buffer_range.end).row;
3226                for row in buffer_row_range {
3227                    expected_buffer_rows.push(Some(row));
3228                }
3229            }
3230            // Remove final trailing newline.
3231            if !expected_excerpts.is_empty() {
3232                expected_text.pop();
3233            }
3234
3235            // Always report one buffer row
3236            if expected_buffer_rows.is_empty() {
3237                expected_buffer_rows.push(Some(0));
3238            }
3239
3240            assert_eq!(snapshot.text(), expected_text);
3241            log::info!("MultiBuffer text: {:?}", expected_text);
3242
3243            assert_eq!(
3244                snapshot.buffer_rows(0).collect::<Vec<_>>(),
3245                expected_buffer_rows,
3246            );
3247
3248            for _ in 0..5 {
3249                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3250                assert_eq!(
3251                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3252                    &expected_buffer_rows[start_row..],
3253                    "buffer_rows({})",
3254                    start_row
3255                );
3256            }
3257
3258            assert_eq!(
3259                snapshot.max_buffer_row(),
3260                expected_buffer_rows
3261                    .into_iter()
3262                    .filter_map(|r| r)
3263                    .max()
3264                    .unwrap()
3265            );
3266
3267            let mut excerpt_starts = excerpt_starts.into_iter();
3268            for (buffer, range) in &expected_excerpts {
3269                let buffer_id = buffer.id();
3270                let buffer = buffer.read(cx);
3271                let buffer_range = range.to_offset(buffer);
3272                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3273                let buffer_start_point_utf16 =
3274                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3275
3276                let excerpt_start = excerpt_starts.next().unwrap();
3277                let mut offset = excerpt_start.bytes;
3278                let mut buffer_offset = buffer_range.start;
3279                let mut point = excerpt_start.lines;
3280                let mut buffer_point = buffer_start_point;
3281                let mut point_utf16 = excerpt_start.lines_utf16;
3282                let mut buffer_point_utf16 = buffer_start_point_utf16;
3283                for ch in buffer
3284                    .snapshot()
3285                    .chunks(buffer_range.clone(), false)
3286                    .flat_map(|c| c.text.chars())
3287                {
3288                    for _ in 0..ch.len_utf8() {
3289                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
3290                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
3291                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3292                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3293                        assert_eq!(
3294                            left_offset,
3295                            excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
3296                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3297                            offset,
3298                            buffer_id,
3299                            buffer_offset,
3300                        );
3301                        assert_eq!(
3302                            right_offset,
3303                            excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
3304                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3305                            offset,
3306                            buffer_id,
3307                            buffer_offset,
3308                        );
3309
3310                        let left_point = snapshot.clip_point(point, Bias::Left);
3311                        let right_point = snapshot.clip_point(point, Bias::Right);
3312                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3313                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3314                        assert_eq!(
3315                            left_point,
3316                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
3317                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3318                            point,
3319                            buffer_id,
3320                            buffer_point,
3321                        );
3322                        assert_eq!(
3323                            right_point,
3324                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
3325                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3326                            point,
3327                            buffer_id,
3328                            buffer_point,
3329                        );
3330
3331                        assert_eq!(
3332                            snapshot.point_to_offset(left_point),
3333                            left_offset,
3334                            "point_to_offset({:?})",
3335                            left_point,
3336                        );
3337                        assert_eq!(
3338                            snapshot.offset_to_point(left_offset),
3339                            left_point,
3340                            "offset_to_point({:?})",
3341                            left_offset,
3342                        );
3343
3344                        offset += 1;
3345                        buffer_offset += 1;
3346                        if ch == '\n' {
3347                            point += Point::new(1, 0);
3348                            buffer_point += Point::new(1, 0);
3349                        } else {
3350                            point += Point::new(0, 1);
3351                            buffer_point += Point::new(0, 1);
3352                        }
3353                    }
3354
3355                    for _ in 0..ch.len_utf16() {
3356                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
3357                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
3358                        let buffer_left_point_utf16 =
3359                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
3360                        let buffer_right_point_utf16 =
3361                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
3362                        assert_eq!(
3363                            left_point_utf16,
3364                            excerpt_start.lines_utf16
3365                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
3366                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
3367                            point_utf16,
3368                            buffer_id,
3369                            buffer_point_utf16,
3370                        );
3371                        assert_eq!(
3372                            right_point_utf16,
3373                            excerpt_start.lines_utf16
3374                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
3375                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
3376                            point_utf16,
3377                            buffer_id,
3378                            buffer_point_utf16,
3379                        );
3380
3381                        if ch == '\n' {
3382                            point_utf16 += PointUtf16::new(1, 0);
3383                            buffer_point_utf16 += PointUtf16::new(1, 0);
3384                        } else {
3385                            point_utf16 += PointUtf16::new(0, 1);
3386                            buffer_point_utf16 += PointUtf16::new(0, 1);
3387                        }
3388                    }
3389                }
3390            }
3391
3392            for (row, line) in expected_text.split('\n').enumerate() {
3393                assert_eq!(
3394                    snapshot.line_len(row as u32),
3395                    line.len() as u32,
3396                    "line_len({}).",
3397                    row
3398                );
3399            }
3400
3401            let text_rope = Rope::from(expected_text.as_str());
3402            for _ in 0..10 {
3403                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3404                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3405
3406                let text_for_range = snapshot
3407                    .text_for_range(start_ix..end_ix)
3408                    .collect::<String>();
3409                assert_eq!(
3410                    text_for_range,
3411                    &expected_text[start_ix..end_ix],
3412                    "incorrect text for range {:?}",
3413                    start_ix..end_ix
3414                );
3415
3416                let excerpted_buffer_ranges =
3417                    multibuffer.read(cx).excerpted_buffers(start_ix..end_ix, cx);
3418                let excerpted_buffers_text = excerpted_buffer_ranges
3419                    .into_iter()
3420                    .map(|(buffer, buffer_range)| {
3421                        buffer
3422                            .read(cx)
3423                            .text_for_range(buffer_range)
3424                            .collect::<String>()
3425                    })
3426                    .collect::<Vec<_>>()
3427                    .join("\n");
3428                assert_eq!(excerpted_buffers_text, text_for_range);
3429
3430                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3431                assert_eq!(
3432                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3433                    expected_summary,
3434                    "incorrect summary for range {:?}",
3435                    start_ix..end_ix
3436                );
3437            }
3438
3439            // Anchor resolution
3440            for (anchor, resolved_offset) in anchors
3441                .iter()
3442                .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3443            {
3444                assert!(resolved_offset <= snapshot.len());
3445                assert_eq!(
3446                    snapshot.summary_for_anchor::<usize>(anchor),
3447                    resolved_offset
3448                );
3449            }
3450
3451            for _ in 0..10 {
3452                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3453                assert_eq!(
3454                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
3455                    expected_text[..end_ix].chars().rev().collect::<String>(),
3456                );
3457            }
3458
3459            for _ in 0..10 {
3460                let end_ix = rng.gen_range(0..=text_rope.len());
3461                let start_ix = rng.gen_range(0..=end_ix);
3462                assert_eq!(
3463                    snapshot
3464                        .bytes_in_range(start_ix..end_ix)
3465                        .flatten()
3466                        .copied()
3467                        .collect::<Vec<_>>(),
3468                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3469                    "bytes_in_range({:?})",
3470                    start_ix..end_ix,
3471                );
3472            }
3473        }
3474
3475        let snapshot = multibuffer.read(cx).snapshot(cx);
3476        for (old_snapshot, subscription) in old_versions {
3477            let edits = subscription.consume().into_inner();
3478
3479            log::info!(
3480                "applying subscription edits to old text: {:?}: {:?}",
3481                old_snapshot.text(),
3482                edits,
3483            );
3484
3485            let mut text = old_snapshot.text();
3486            for edit in edits {
3487                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3488                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3489            }
3490            assert_eq!(text.to_string(), snapshot.text());
3491        }
3492    }
3493
3494    #[gpui::test]
3495    fn test_history(cx: &mut MutableAppContext) {
3496        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3497        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3498        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3499        let group_interval = multibuffer.read(cx).history.group_interval;
3500        multibuffer.update(cx, |multibuffer, cx| {
3501            multibuffer.push_excerpt(
3502                ExcerptProperties {
3503                    buffer: &buffer_1,
3504                    range: 0..buffer_1.read(cx).len(),
3505                },
3506                cx,
3507            );
3508            multibuffer.push_excerpt(
3509                ExcerptProperties {
3510                    buffer: &buffer_2,
3511                    range: 0..buffer_2.read(cx).len(),
3512                },
3513                cx,
3514            );
3515        });
3516
3517        let mut now = Instant::now();
3518
3519        multibuffer.update(cx, |multibuffer, cx| {
3520            multibuffer.start_transaction_at(now, cx);
3521            multibuffer.edit(
3522                [
3523                    Point::new(0, 0)..Point::new(0, 0),
3524                    Point::new(1, 0)..Point::new(1, 0),
3525                ],
3526                "A",
3527                cx,
3528            );
3529            multibuffer.edit(
3530                [
3531                    Point::new(0, 1)..Point::new(0, 1),
3532                    Point::new(1, 1)..Point::new(1, 1),
3533                ],
3534                "B",
3535                cx,
3536            );
3537            multibuffer.end_transaction_at(now, cx);
3538            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3539
3540            now += 2 * group_interval;
3541            multibuffer.start_transaction_at(now, cx);
3542            multibuffer.edit([2..2], "C", cx);
3543            multibuffer.end_transaction_at(now, cx);
3544            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3545
3546            multibuffer.undo(cx);
3547            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3548
3549            multibuffer.undo(cx);
3550            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3551
3552            multibuffer.redo(cx);
3553            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3554
3555            multibuffer.redo(cx);
3556            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3557
3558            buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3559            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3560
3561            multibuffer.undo(cx);
3562            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3563
3564            multibuffer.redo(cx);
3565            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3566
3567            multibuffer.redo(cx);
3568            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3569
3570            multibuffer.undo(cx);
3571            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3572
3573            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3574            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3575
3576            multibuffer.undo(cx);
3577            assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3578        });
3579    }
3580}