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