multi_buffer.rs

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