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};
   8pub use language::Completion;
   9use language::{
  10    Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Outline,
  11    OutlineItem, Selection, ToOffset as _, ToPoint as _, ToPointUtf16 as _, TransactionId,
  12};
  13use std::{
  14    cell::{Ref, RefCell},
  15    cmp, fmt, io,
  16    iter::{self, FromIterator},
  17    ops::{Range, 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 completions<T>(
 865        &self,
 866        position: T,
 867        cx: &mut ModelContext<Self>,
 868    ) -> Task<Result<Vec<Completion<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 completions =
 875            buffer.update(cx, |buffer, cx| buffer.completions(anchor.text_anchor, cx));
 876        cx.spawn(|this, cx| async move {
 877            completions.await.map(|completions| {
 878                let snapshot = this.read_with(&cx, |buffer, cx| buffer.snapshot(cx));
 879                completions
 880                    .into_iter()
 881                    .map(|completion| Completion {
 882                        old_range: snapshot.anchor_in_excerpt(
 883                            anchor.excerpt_id.clone(),
 884                            completion.old_range.start,
 885                        )
 886                            ..snapshot.anchor_in_excerpt(
 887                                anchor.excerpt_id.clone(),
 888                                completion.old_range.end,
 889                            ),
 890                        new_text: completion.new_text,
 891                        label: completion.label,
 892                        lsp_completion: completion.lsp_completion,
 893                    })
 894                    .collect()
 895            })
 896        })
 897    }
 898
 899    pub fn is_completion_trigger<T>(&self, position: T, text: &str, cx: &AppContext) -> bool
 900    where
 901        T: ToOffset,
 902    {
 903        let mut chars = text.chars();
 904        let char = if let Some(char) = chars.next() {
 905            char
 906        } else {
 907            return false;
 908        };
 909        if chars.next().is_some() {
 910            return false;
 911        }
 912
 913        if char.is_alphanumeric() || char == '_' {
 914            return true;
 915        }
 916
 917        let snapshot = self.snapshot(cx);
 918        let anchor = snapshot.anchor_before(position);
 919        let buffer = self.buffers.borrow()[&anchor.buffer_id].buffer.clone();
 920        buffer
 921            .read(cx)
 922            .completion_triggers()
 923            .iter()
 924            .any(|string| string == text)
 925    }
 926
 927    pub fn apply_additional_edits_for_completion(
 928        &self,
 929        completion: Completion<Anchor>,
 930        cx: &mut ModelContext<Self>,
 931    ) -> Task<Result<()>> {
 932        let buffer = if let Some(buffer_state) = self
 933            .buffers
 934            .borrow()
 935            .get(&completion.old_range.start.buffer_id)
 936        {
 937            buffer_state.buffer.clone()
 938        } else {
 939            return Task::ready(Ok(()));
 940        };
 941
 942        let apply_edits = buffer.update(cx, |buffer, cx| {
 943            buffer.apply_additional_edits_for_completion(
 944                Completion {
 945                    old_range: completion.old_range.start.text_anchor
 946                        ..completion.old_range.end.text_anchor,
 947                    new_text: completion.new_text,
 948                    label: completion.label,
 949                    lsp_completion: completion.lsp_completion,
 950                },
 951                true,
 952                cx,
 953            )
 954        });
 955        cx.foreground().spawn(async move {
 956            apply_edits.await?;
 957            Ok(())
 958        })
 959    }
 960
 961    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 962        self.buffers
 963            .borrow()
 964            .values()
 965            .next()
 966            .and_then(|state| state.buffer.read(cx).language())
 967    }
 968
 969    pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
 970        self.as_singleton()?.read(cx).file()
 971    }
 972
 973    #[cfg(test)]
 974    pub fn is_parsing(&self, cx: &AppContext) -> bool {
 975        self.as_singleton().unwrap().read(cx).is_parsing()
 976    }
 977
 978    fn sync(&self, cx: &AppContext) {
 979        let mut snapshot = self.snapshot.borrow_mut();
 980        let mut excerpts_to_edit = Vec::new();
 981        let mut reparsed = false;
 982        let mut diagnostics_updated = false;
 983        let mut is_dirty = false;
 984        let mut has_conflict = false;
 985        let mut buffers = self.buffers.borrow_mut();
 986        for buffer_state in buffers.values_mut() {
 987            let buffer = buffer_state.buffer.read(cx);
 988            let version = buffer.version();
 989            let parse_count = buffer.parse_count();
 990            let selections_update_count = buffer.selections_update_count();
 991            let diagnostics_update_count = buffer.diagnostics_update_count();
 992
 993            let buffer_edited = version.changed_since(&buffer_state.last_version);
 994            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
 995            let buffer_selections_updated =
 996                selections_update_count > buffer_state.last_selections_update_count;
 997            let buffer_diagnostics_updated =
 998                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
 999            if buffer_edited
1000                || buffer_reparsed
1001                || buffer_selections_updated
1002                || buffer_diagnostics_updated
1003            {
1004                buffer_state.last_version = version;
1005                buffer_state.last_parse_count = parse_count;
1006                buffer_state.last_selections_update_count = selections_update_count;
1007                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1008                excerpts_to_edit.extend(
1009                    buffer_state
1010                        .excerpts
1011                        .iter()
1012                        .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
1013                );
1014            }
1015
1016            reparsed |= buffer_reparsed;
1017            diagnostics_updated |= buffer_diagnostics_updated;
1018            is_dirty |= buffer.is_dirty();
1019            has_conflict |= buffer.has_conflict();
1020        }
1021        if reparsed {
1022            snapshot.parse_count += 1;
1023        }
1024        if diagnostics_updated {
1025            snapshot.diagnostics_update_count += 1;
1026        }
1027        snapshot.is_dirty = is_dirty;
1028        snapshot.has_conflict = has_conflict;
1029
1030        excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
1031
1032        let mut edits = Vec::new();
1033        let mut new_excerpts = SumTree::new();
1034        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
1035
1036        for (id, buffer, buffer_edited) in excerpts_to_edit {
1037            new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
1038            let old_excerpt = cursor.item().unwrap();
1039            let buffer_id = buffer.id();
1040            let buffer = buffer.read(cx);
1041
1042            let mut new_excerpt;
1043            if buffer_edited {
1044                edits.extend(
1045                    buffer
1046                        .edits_since_in_range::<usize>(
1047                            old_excerpt.buffer.version(),
1048                            old_excerpt.range.clone(),
1049                        )
1050                        .map(|mut edit| {
1051                            let excerpt_old_start = cursor.start().1;
1052                            let excerpt_new_start = new_excerpts.summary().text.bytes;
1053                            edit.old.start += excerpt_old_start;
1054                            edit.old.end += excerpt_old_start;
1055                            edit.new.start += excerpt_new_start;
1056                            edit.new.end += excerpt_new_start;
1057                            edit
1058                        }),
1059                );
1060
1061                new_excerpt = Excerpt::new(
1062                    id.clone(),
1063                    buffer_id,
1064                    buffer.snapshot(),
1065                    old_excerpt.range.clone(),
1066                    old_excerpt.has_trailing_newline,
1067                );
1068            } else {
1069                new_excerpt = old_excerpt.clone();
1070                new_excerpt.buffer = buffer.snapshot();
1071            }
1072
1073            new_excerpts.push(new_excerpt, &());
1074            cursor.next(&());
1075        }
1076        new_excerpts.push_tree(cursor.suffix(&()), &());
1077
1078        drop(cursor);
1079        snapshot.excerpts = new_excerpts;
1080
1081        self.subscriptions.publish(edits);
1082    }
1083}
1084
1085#[cfg(any(test, feature = "test-support"))]
1086impl MultiBuffer {
1087    pub fn randomly_edit(
1088        &mut self,
1089        rng: &mut impl rand::Rng,
1090        count: usize,
1091        cx: &mut ModelContext<Self>,
1092    ) {
1093        use text::RandomCharIter;
1094
1095        let snapshot = self.read(cx);
1096        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1097        for _ in 0..count {
1098            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1099            if last_end > snapshot.len() {
1100                break;
1101            }
1102            let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
1103            let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1104            old_ranges.push(start_ix..end_ix);
1105        }
1106        let new_text_len = rng.gen_range(0..10);
1107        let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1108        log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
1109        drop(snapshot);
1110
1111        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1112    }
1113}
1114
1115impl Entity for MultiBuffer {
1116    type Event = language::Event;
1117}
1118
1119impl MultiBufferSnapshot {
1120    pub fn text(&self) -> String {
1121        self.chunks(0..self.len(), false)
1122            .map(|chunk| chunk.text)
1123            .collect()
1124    }
1125
1126    pub fn reversed_chars_at<'a, T: ToOffset>(
1127        &'a self,
1128        position: T,
1129    ) -> impl Iterator<Item = char> + 'a {
1130        let mut offset = position.to_offset(self);
1131        let mut cursor = self.excerpts.cursor::<usize>();
1132        cursor.seek(&offset, Bias::Left, &());
1133        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1134            let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
1135            let start = excerpt.range.start.to_offset(&excerpt.buffer);
1136            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1137            excerpt.buffer.reversed_chunks_in_range(start..end)
1138        });
1139        iter::from_fn(move || {
1140            if offset == *cursor.start() {
1141                cursor.prev(&());
1142                let excerpt = cursor.item()?;
1143                excerpt_chunks = Some(
1144                    excerpt
1145                        .buffer
1146                        .reversed_chunks_in_range(excerpt.range.clone()),
1147                );
1148            }
1149
1150            let excerpt = cursor.item().unwrap();
1151            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1152                offset -= 1;
1153                Some("\n")
1154            } else {
1155                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1156                offset -= chunk.len();
1157                Some(chunk)
1158            }
1159        })
1160        .flat_map(|c| c.chars().rev())
1161    }
1162
1163    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1164        let offset = position.to_offset(self);
1165        self.text_for_range(offset..self.len())
1166            .flat_map(|chunk| chunk.chars())
1167    }
1168
1169    pub fn text_for_range<'a, T: ToOffset>(
1170        &'a self,
1171        range: Range<T>,
1172    ) -> impl Iterator<Item = &'a str> {
1173        self.chunks(range, false).map(|chunk| chunk.text)
1174    }
1175
1176    pub fn is_line_blank(&self, row: u32) -> bool {
1177        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1178            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1179    }
1180
1181    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1182    where
1183        T: ToOffset,
1184    {
1185        let position = position.to_offset(self);
1186        position == self.clip_offset(position, Bias::Left)
1187            && self
1188                .bytes_in_range(position..self.len())
1189                .flatten()
1190                .copied()
1191                .take(needle.len())
1192                .eq(needle.bytes())
1193    }
1194
1195    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1196        let mut start = start.to_offset(self);
1197        let mut end = start;
1198        let mut next_chars = self.chars_at(start).peekable();
1199        let mut prev_chars = self.reversed_chars_at(start).peekable();
1200        let word_kind = cmp::max(
1201            prev_chars.peek().copied().map(char_kind),
1202            next_chars.peek().copied().map(char_kind),
1203        );
1204
1205        for ch in prev_chars {
1206            if Some(char_kind(ch)) == word_kind {
1207                start -= ch.len_utf8();
1208            } else {
1209                break;
1210            }
1211        }
1212
1213        for ch in next_chars {
1214            if Some(char_kind(ch)) == word_kind {
1215                end += ch.len_utf8();
1216            } else {
1217                break;
1218            }
1219        }
1220
1221        (start..end, word_kind)
1222    }
1223
1224    fn as_singleton(&self) -> Option<&Excerpt> {
1225        if self.singleton {
1226            self.excerpts.iter().next()
1227        } else {
1228            None
1229        }
1230    }
1231
1232    pub fn len(&self) -> usize {
1233        self.excerpts.summary().text.bytes
1234    }
1235
1236    pub fn max_buffer_row(&self) -> u32 {
1237        self.excerpts.summary().max_buffer_row
1238    }
1239
1240    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1241        if let Some(excerpt) = self.as_singleton() {
1242            return excerpt.buffer.clip_offset(offset, bias);
1243        }
1244
1245        let mut cursor = self.excerpts.cursor::<usize>();
1246        cursor.seek(&offset, Bias::Right, &());
1247        let overshoot = if let Some(excerpt) = cursor.item() {
1248            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1249            let buffer_offset = excerpt
1250                .buffer
1251                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1252            buffer_offset.saturating_sub(excerpt_start)
1253        } else {
1254            0
1255        };
1256        cursor.start() + overshoot
1257    }
1258
1259    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1260        if let Some(excerpt) = self.as_singleton() {
1261            return excerpt.buffer.clip_point(point, bias);
1262        }
1263
1264        let mut cursor = self.excerpts.cursor::<Point>();
1265        cursor.seek(&point, Bias::Right, &());
1266        let overshoot = if let Some(excerpt) = cursor.item() {
1267            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1268            let buffer_point = excerpt
1269                .buffer
1270                .clip_point(excerpt_start + (point - cursor.start()), bias);
1271            buffer_point.saturating_sub(excerpt_start)
1272        } else {
1273            Point::zero()
1274        };
1275        *cursor.start() + overshoot
1276    }
1277
1278    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1279        if let Some(excerpt) = self.as_singleton() {
1280            return excerpt.buffer.clip_point_utf16(point, bias);
1281        }
1282
1283        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1284        cursor.seek(&point, Bias::Right, &());
1285        let overshoot = if let Some(excerpt) = cursor.item() {
1286            let excerpt_start = excerpt
1287                .buffer
1288                .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1289            let buffer_point = excerpt
1290                .buffer
1291                .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1292            buffer_point.saturating_sub(excerpt_start)
1293        } else {
1294            PointUtf16::zero()
1295        };
1296        *cursor.start() + overshoot
1297    }
1298
1299    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1300        let range = range.start.to_offset(self)..range.end.to_offset(self);
1301        let mut excerpts = self.excerpts.cursor::<usize>();
1302        excerpts.seek(&range.start, Bias::Right, &());
1303
1304        let mut chunk = &[][..];
1305        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1306            let mut excerpt_bytes = excerpt
1307                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1308            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1309            Some(excerpt_bytes)
1310        } else {
1311            None
1312        };
1313
1314        MultiBufferBytes {
1315            range,
1316            excerpts,
1317            excerpt_bytes,
1318            chunk,
1319        }
1320    }
1321
1322    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1323        let mut result = MultiBufferRows {
1324            buffer_row_range: 0..0,
1325            excerpts: self.excerpts.cursor(),
1326        };
1327        result.seek(start_row);
1328        result
1329    }
1330
1331    pub fn chunks<'a, T: ToOffset>(
1332        &'a self,
1333        range: Range<T>,
1334        language_aware: bool,
1335    ) -> MultiBufferChunks<'a> {
1336        let range = range.start.to_offset(self)..range.end.to_offset(self);
1337        let mut chunks = MultiBufferChunks {
1338            range: range.clone(),
1339            excerpts: self.excerpts.cursor(),
1340            excerpt_chunks: None,
1341            language_aware,
1342        };
1343        chunks.seek(range.start);
1344        chunks
1345    }
1346
1347    pub fn offset_to_point(&self, offset: usize) -> Point {
1348        if let Some(excerpt) = self.as_singleton() {
1349            return excerpt.buffer.offset_to_point(offset);
1350        }
1351
1352        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1353        cursor.seek(&offset, Bias::Right, &());
1354        if let Some(excerpt) = cursor.item() {
1355            let (start_offset, start_point) = cursor.start();
1356            let overshoot = offset - start_offset;
1357            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1358            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1359            let buffer_point = excerpt
1360                .buffer
1361                .offset_to_point(excerpt_start_offset + overshoot);
1362            *start_point + (buffer_point - excerpt_start_point)
1363        } else {
1364            self.excerpts.summary().text.lines
1365        }
1366    }
1367
1368    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1369        if let Some(excerpt) = self.as_singleton() {
1370            return excerpt.buffer.offset_to_point_utf16(offset);
1371        }
1372
1373        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1374        cursor.seek(&offset, Bias::Right, &());
1375        if let Some(excerpt) = cursor.item() {
1376            let (start_offset, start_point) = cursor.start();
1377            let overshoot = offset - start_offset;
1378            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1379            let excerpt_start_point = excerpt.range.start.to_point_utf16(&excerpt.buffer);
1380            let buffer_point = excerpt
1381                .buffer
1382                .offset_to_point_utf16(excerpt_start_offset + overshoot);
1383            *start_point + (buffer_point - excerpt_start_point)
1384        } else {
1385            self.excerpts.summary().text.lines_utf16
1386        }
1387    }
1388
1389    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1390        if let Some(excerpt) = self.as_singleton() {
1391            return excerpt.buffer.point_to_point_utf16(point);
1392        }
1393
1394        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1395        cursor.seek(&point, Bias::Right, &());
1396        if let Some(excerpt) = cursor.item() {
1397            let (start_offset, start_point) = cursor.start();
1398            let overshoot = point - start_offset;
1399            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1400            let excerpt_start_point_utf16 = excerpt.range.start.to_point_utf16(&excerpt.buffer);
1401            let buffer_point = excerpt
1402                .buffer
1403                .point_to_point_utf16(excerpt_start_point + overshoot);
1404            *start_point + (buffer_point - excerpt_start_point_utf16)
1405        } else {
1406            self.excerpts.summary().text.lines_utf16
1407        }
1408    }
1409
1410    pub fn point_to_offset(&self, point: Point) -> usize {
1411        if let Some(excerpt) = self.as_singleton() {
1412            return excerpt.buffer.point_to_offset(point);
1413        }
1414
1415        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1416        cursor.seek(&point, Bias::Right, &());
1417        if let Some(excerpt) = cursor.item() {
1418            let (start_point, start_offset) = cursor.start();
1419            let overshoot = point - start_point;
1420            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1421            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1422            let buffer_offset = excerpt
1423                .buffer
1424                .point_to_offset(excerpt_start_point + overshoot);
1425            *start_offset + buffer_offset - excerpt_start_offset
1426        } else {
1427            self.excerpts.summary().text.bytes
1428        }
1429    }
1430
1431    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1432        if let Some(excerpt) = self.as_singleton() {
1433            return excerpt.buffer.point_utf16_to_offset(point);
1434        }
1435
1436        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1437        cursor.seek(&point, Bias::Right, &());
1438        if let Some(excerpt) = cursor.item() {
1439            let (start_point, start_offset) = cursor.start();
1440            let overshoot = point - start_point;
1441            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1442            let excerpt_start_point = excerpt
1443                .buffer
1444                .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1445            let buffer_offset = excerpt
1446                .buffer
1447                .point_utf16_to_offset(excerpt_start_point + overshoot);
1448            *start_offset + (buffer_offset - excerpt_start_offset)
1449        } else {
1450            self.excerpts.summary().text.bytes
1451        }
1452    }
1453
1454    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1455        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1456            buffer
1457                .indent_column_for_line(range.start.row)
1458                .min(range.end.column)
1459                .saturating_sub(range.start.column)
1460        } else {
1461            0
1462        }
1463    }
1464
1465    pub fn line_len(&self, row: u32) -> u32 {
1466        if let Some((_, range)) = self.buffer_line_for_row(row) {
1467            range.end.column - range.start.column
1468        } else {
1469            0
1470        }
1471    }
1472
1473    fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1474        let mut cursor = self.excerpts.cursor::<Point>();
1475        cursor.seek(&Point::new(row, 0), Bias::Right, &());
1476        if let Some(excerpt) = cursor.item() {
1477            let overshoot = row - cursor.start().row;
1478            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1479            let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1480            let buffer_row = excerpt_start.row + overshoot;
1481            let line_start = Point::new(buffer_row, 0);
1482            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1483            return Some((
1484                &excerpt.buffer,
1485                line_start.max(excerpt_start)..line_end.min(excerpt_end),
1486            ));
1487        }
1488        None
1489    }
1490
1491    pub fn max_point(&self) -> Point {
1492        self.text_summary().lines
1493    }
1494
1495    pub fn text_summary(&self) -> TextSummary {
1496        self.excerpts.summary().text
1497    }
1498
1499    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1500    where
1501        D: TextDimension,
1502        O: ToOffset,
1503    {
1504        let mut summary = D::default();
1505        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1506        let mut cursor = self.excerpts.cursor::<usize>();
1507        cursor.seek(&range.start, Bias::Right, &());
1508        if let Some(excerpt) = cursor.item() {
1509            let mut end_before_newline = cursor.end(&());
1510            if excerpt.has_trailing_newline {
1511                end_before_newline -= 1;
1512            }
1513
1514            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1515            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1516            let end_in_excerpt =
1517                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1518            summary.add_assign(
1519                &excerpt
1520                    .buffer
1521                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1522            );
1523
1524            if range.end > end_before_newline {
1525                summary.add_assign(&D::from_text_summary(&TextSummary {
1526                    bytes: 1,
1527                    lines: Point::new(1 as u32, 0),
1528                    lines_utf16: PointUtf16::new(1 as u32, 0),
1529                    first_line_chars: 0,
1530                    last_line_chars: 0,
1531                    longest_row: 0,
1532                    longest_row_chars: 0,
1533                }));
1534            }
1535
1536            cursor.next(&());
1537        }
1538
1539        if range.end > *cursor.start() {
1540            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1541                &range.end,
1542                Bias::Right,
1543                &(),
1544            )));
1545            if let Some(excerpt) = cursor.item() {
1546                range.end = cmp::max(*cursor.start(), range.end);
1547
1548                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1549                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1550                summary.add_assign(
1551                    &excerpt
1552                        .buffer
1553                        .text_summary_for_range(excerpt_start..end_in_excerpt),
1554                );
1555            }
1556        }
1557
1558        summary
1559    }
1560
1561    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1562    where
1563        D: TextDimension + Ord + Sub<D, Output = D>,
1564    {
1565        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1566        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1567        if cursor.item().is_none() {
1568            cursor.next(&());
1569        }
1570
1571        let mut position = D::from_text_summary(&cursor.start().text);
1572        if let Some(excerpt) = cursor.item() {
1573            if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id {
1574                let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1575                let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1576                let buffer_position = cmp::min(
1577                    excerpt_buffer_end,
1578                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
1579                );
1580                if buffer_position > excerpt_buffer_start {
1581                    position.add_assign(&(buffer_position - excerpt_buffer_start));
1582                }
1583            }
1584        }
1585        position
1586    }
1587
1588    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1589    where
1590        D: TextDimension + Ord + Sub<D, Output = D>,
1591        I: 'a + IntoIterator<Item = &'a Anchor>,
1592    {
1593        if let Some(excerpt) = self.as_singleton() {
1594            return excerpt
1595                .buffer
1596                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
1597                .collect();
1598        }
1599
1600        let mut anchors = anchors.into_iter().peekable();
1601        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1602        let mut summaries = Vec::new();
1603        while let Some(anchor) = anchors.peek() {
1604            let excerpt_id = &anchor.excerpt_id;
1605            let buffer_id = anchor.buffer_id;
1606            let excerpt_anchors = iter::from_fn(|| {
1607                let anchor = anchors.peek()?;
1608                if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1609                    Some(&anchors.next().unwrap().text_anchor)
1610                } else {
1611                    None
1612                }
1613            });
1614
1615            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1616            if cursor.item().is_none() {
1617                cursor.next(&());
1618            }
1619
1620            let position = D::from_text_summary(&cursor.start().text);
1621            if let Some(excerpt) = cursor.item() {
1622                if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1623                    let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1624                    let excerpt_buffer_end = excerpt.range.end.summary::<D>(&excerpt.buffer);
1625                    summaries.extend(
1626                        excerpt
1627                            .buffer
1628                            .summaries_for_anchors::<D, _>(excerpt_anchors)
1629                            .map(move |summary| {
1630                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
1631                                let mut position = position.clone();
1632                                let excerpt_buffer_start = excerpt_buffer_start.clone();
1633                                if summary > excerpt_buffer_start {
1634                                    position.add_assign(&(summary - excerpt_buffer_start));
1635                                }
1636                                position
1637                            }),
1638                    );
1639                    continue;
1640                }
1641            }
1642
1643            summaries.extend(excerpt_anchors.map(|_| position.clone()));
1644        }
1645
1646        summaries
1647    }
1648
1649    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1650    where
1651        I: 'a + IntoIterator<Item = &'a Anchor>,
1652    {
1653        let mut anchors = anchors.into_iter().enumerate().peekable();
1654        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1655        let mut result = Vec::new();
1656        while let Some((_, anchor)) = anchors.peek() {
1657            let old_excerpt_id = &anchor.excerpt_id;
1658
1659            // Find the location where this anchor's excerpt should be.
1660            cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1661            if cursor.item().is_none() {
1662                cursor.next(&());
1663            }
1664
1665            let next_excerpt = cursor.item();
1666            let prev_excerpt = cursor.prev_item();
1667
1668            // Process all of the anchors for this excerpt.
1669            while let Some((_, anchor)) = anchors.peek() {
1670                if anchor.excerpt_id != *old_excerpt_id {
1671                    break;
1672                }
1673                let mut kept_position = false;
1674                let (anchor_ix, anchor) = anchors.next().unwrap();
1675                let mut anchor = anchor.clone();
1676
1677                // Leave min and max anchors unchanged.
1678                if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1679                    kept_position = true;
1680                }
1681                // If the old excerpt still exists at this location, then leave
1682                // the anchor unchanged.
1683                else if next_excerpt.map_or(false, |excerpt| {
1684                    excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
1685                }) {
1686                    kept_position = true;
1687                }
1688                // If the old excerpt no longer exists at this location, then attempt to
1689                // find an equivalent position for this anchor in an adjacent excerpt.
1690                else {
1691                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1692                        if excerpt.contains(&anchor) {
1693                            anchor.excerpt_id = excerpt.id.clone();
1694                            kept_position = true;
1695                            break;
1696                        }
1697                    }
1698                }
1699                // If there's no adjacent excerpt that contains the anchor's position,
1700                // then report that the anchor has lost its position.
1701                if !kept_position {
1702                    anchor = if let Some(excerpt) = next_excerpt {
1703                        let mut text_anchor = excerpt
1704                            .range
1705                            .start
1706                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
1707                        if text_anchor
1708                            .cmp(&excerpt.range.end, &excerpt.buffer)
1709                            .unwrap()
1710                            .is_gt()
1711                        {
1712                            text_anchor = excerpt.range.end.clone();
1713                        }
1714                        Anchor {
1715                            buffer_id: excerpt.buffer_id,
1716                            excerpt_id: excerpt.id.clone(),
1717                            text_anchor,
1718                        }
1719                    } else if let Some(excerpt) = prev_excerpt {
1720                        let mut text_anchor = excerpt
1721                            .range
1722                            .end
1723                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
1724                        if text_anchor
1725                            .cmp(&excerpt.range.start, &excerpt.buffer)
1726                            .unwrap()
1727                            .is_lt()
1728                        {
1729                            text_anchor = excerpt.range.start.clone();
1730                        }
1731                        Anchor {
1732                            buffer_id: excerpt.buffer_id,
1733                            excerpt_id: excerpt.id.clone(),
1734                            text_anchor,
1735                        }
1736                    } else if anchor.text_anchor.bias == Bias::Left {
1737                        Anchor::min()
1738                    } else {
1739                        Anchor::max()
1740                    };
1741                }
1742
1743                result.push((anchor_ix, anchor, kept_position));
1744            }
1745        }
1746        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1747        result
1748    }
1749
1750    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1751        self.anchor_at(position, Bias::Left)
1752    }
1753
1754    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1755        self.anchor_at(position, Bias::Right)
1756    }
1757
1758    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1759        let offset = position.to_offset(self);
1760        if let Some(excerpt) = self.as_singleton() {
1761            return Anchor {
1762                buffer_id: excerpt.buffer_id,
1763                excerpt_id: excerpt.id.clone(),
1764                text_anchor: excerpt.buffer.anchor_at(offset, bias),
1765            };
1766        }
1767
1768        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1769        cursor.seek(&offset, Bias::Right, &());
1770        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1771            cursor.prev(&());
1772        }
1773        if let Some(excerpt) = cursor.item() {
1774            let mut overshoot = offset.saturating_sub(cursor.start().0);
1775            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1776                overshoot -= 1;
1777                bias = Bias::Right;
1778            }
1779
1780            let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1781            let text_anchor =
1782                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1783            Anchor {
1784                buffer_id: excerpt.buffer_id,
1785                excerpt_id: excerpt.id.clone(),
1786                text_anchor,
1787            }
1788        } else if offset == 0 && bias == Bias::Left {
1789            Anchor::min()
1790        } else {
1791            Anchor::max()
1792        }
1793    }
1794
1795    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1796        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1797        cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1798        if let Some(excerpt) = cursor.item() {
1799            if excerpt.id == excerpt_id {
1800                let text_anchor = excerpt.clip_anchor(text_anchor);
1801                drop(cursor);
1802                return Anchor {
1803                    buffer_id: excerpt.buffer_id,
1804                    excerpt_id,
1805                    text_anchor,
1806                };
1807            }
1808        }
1809        panic!("excerpt not found");
1810    }
1811
1812    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1813        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1814            true
1815        } else if let Some((buffer_id, buffer_snapshot)) =
1816            self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1817        {
1818            anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1819        } else {
1820            false
1821        }
1822    }
1823
1824    pub fn range_contains_excerpt_boundary<T: ToOffset>(&self, range: Range<T>) -> bool {
1825        let start = range.start.to_offset(self);
1826        let end = range.end.to_offset(self);
1827        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1828        cursor.seek(&start, Bias::Right, &());
1829        let start_id = cursor
1830            .item()
1831            .or_else(|| cursor.prev_item())
1832            .map(|excerpt| &excerpt.id);
1833        cursor.seek_forward(&end, Bias::Right, &());
1834        let end_id = cursor
1835            .item()
1836            .or_else(|| cursor.prev_item())
1837            .map(|excerpt| &excerpt.id);
1838        start_id != end_id
1839    }
1840
1841    pub fn parse_count(&self) -> usize {
1842        self.parse_count
1843    }
1844
1845    pub fn enclosing_bracket_ranges<T: ToOffset>(
1846        &self,
1847        range: Range<T>,
1848    ) -> Option<(Range<usize>, Range<usize>)> {
1849        let range = range.start.to_offset(self)..range.end.to_offset(self);
1850
1851        let mut cursor = self.excerpts.cursor::<usize>();
1852        cursor.seek(&range.start, Bias::Right, &());
1853        let start_excerpt = cursor.item();
1854
1855        cursor.seek(&range.end, Bias::Right, &());
1856        let end_excerpt = cursor.item();
1857
1858        start_excerpt
1859            .zip(end_excerpt)
1860            .and_then(|(start_excerpt, end_excerpt)| {
1861                if start_excerpt.id != end_excerpt.id {
1862                    return None;
1863                }
1864
1865                let excerpt_buffer_start =
1866                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1867                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1868
1869                let start_in_buffer =
1870                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1871                let end_in_buffer =
1872                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1873                let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1874                    .buffer
1875                    .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1876
1877                if start_bracket_range.start >= excerpt_buffer_start
1878                    && end_bracket_range.end < excerpt_buffer_end
1879                {
1880                    start_bracket_range.start =
1881                        cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1882                    start_bracket_range.end =
1883                        cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1884                    end_bracket_range.start =
1885                        cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1886                    end_bracket_range.end =
1887                        cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1888                    Some((start_bracket_range, end_bracket_range))
1889                } else {
1890                    None
1891                }
1892            })
1893    }
1894
1895    pub fn diagnostics_update_count(&self) -> usize {
1896        self.diagnostics_update_count
1897    }
1898
1899    pub fn language(&self) -> Option<&Arc<Language>> {
1900        self.excerpts
1901            .iter()
1902            .next()
1903            .and_then(|excerpt| excerpt.buffer.language())
1904    }
1905
1906    pub fn is_dirty(&self) -> bool {
1907        self.is_dirty
1908    }
1909
1910    pub fn has_conflict(&self) -> bool {
1911        self.has_conflict
1912    }
1913
1914    pub fn diagnostic_group<'a, O>(
1915        &'a self,
1916        group_id: usize,
1917    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1918    where
1919        O: text::FromAnchor + 'a,
1920    {
1921        self.as_singleton()
1922            .into_iter()
1923            .flat_map(move |excerpt| excerpt.buffer.diagnostic_group(group_id))
1924    }
1925
1926    pub fn diagnostics_in_range<'a, T, O>(
1927        &'a self,
1928        range: Range<T>,
1929    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1930    where
1931        T: 'a + ToOffset,
1932        O: 'a + text::FromAnchor,
1933    {
1934        self.as_singleton().into_iter().flat_map(move |excerpt| {
1935            excerpt
1936                .buffer
1937                .diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1938        })
1939    }
1940
1941    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1942        let range = range.start.to_offset(self)..range.end.to_offset(self);
1943
1944        let mut cursor = self.excerpts.cursor::<usize>();
1945        cursor.seek(&range.start, Bias::Right, &());
1946        let start_excerpt = cursor.item();
1947
1948        cursor.seek(&range.end, Bias::Right, &());
1949        let end_excerpt = cursor.item();
1950
1951        start_excerpt
1952            .zip(end_excerpt)
1953            .and_then(|(start_excerpt, end_excerpt)| {
1954                if start_excerpt.id != end_excerpt.id {
1955                    return None;
1956                }
1957
1958                let excerpt_buffer_start =
1959                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1960                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1961
1962                let start_in_buffer =
1963                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1964                let end_in_buffer =
1965                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1966                let mut ancestor_buffer_range = start_excerpt
1967                    .buffer
1968                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1969                ancestor_buffer_range.start =
1970                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1971                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1972
1973                let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1974                let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1975                Some(start..end)
1976            })
1977    }
1978
1979    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1980        let excerpt = self.as_singleton()?;
1981        let outline = excerpt.buffer.outline(theme)?;
1982        Some(Outline::new(
1983            outline
1984                .items
1985                .into_iter()
1986                .map(|item| OutlineItem {
1987                    depth: item.depth,
1988                    range: self.anchor_in_excerpt(excerpt.id.clone(), item.range.start)
1989                        ..self.anchor_in_excerpt(excerpt.id.clone(), item.range.end),
1990                    text: item.text,
1991                    highlight_ranges: item.highlight_ranges,
1992                    name_ranges: item.name_ranges,
1993                })
1994                .collect(),
1995        ))
1996    }
1997
1998    fn buffer_snapshot_for_excerpt<'a>(
1999        &'a self,
2000        excerpt_id: &'a ExcerptId,
2001    ) -> Option<(usize, &'a BufferSnapshot)> {
2002        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2003        cursor.seek(&Some(excerpt_id), Bias::Left, &());
2004        if let Some(excerpt) = cursor.item() {
2005            if excerpt.id == *excerpt_id {
2006                return Some((excerpt.buffer_id, &excerpt.buffer));
2007            }
2008        }
2009        None
2010    }
2011
2012    pub fn remote_selections_in_range<'a>(
2013        &'a self,
2014        range: &'a Range<Anchor>,
2015    ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
2016        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2017        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
2018        cursor
2019            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
2020            .flat_map(move |excerpt| {
2021                let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
2022                if excerpt.id == range.start.excerpt_id {
2023                    query_range.start = range.start.text_anchor.clone();
2024                }
2025                if excerpt.id == range.end.excerpt_id {
2026                    query_range.end = range.end.text_anchor.clone();
2027                }
2028
2029                excerpt
2030                    .buffer
2031                    .remote_selections_in_range(query_range)
2032                    .flat_map(move |(replica_id, selections)| {
2033                        selections.map(move |selection| {
2034                            let mut start = Anchor {
2035                                buffer_id: excerpt.buffer_id,
2036                                excerpt_id: excerpt.id.clone(),
2037                                text_anchor: selection.start.clone(),
2038                            };
2039                            let mut end = Anchor {
2040                                buffer_id: excerpt.buffer_id,
2041                                excerpt_id: excerpt.id.clone(),
2042                                text_anchor: selection.end.clone(),
2043                            };
2044                            if range.start.cmp(&start, self).unwrap().is_gt() {
2045                                start = range.start.clone();
2046                            }
2047                            if range.end.cmp(&end, self).unwrap().is_lt() {
2048                                end = range.end.clone();
2049                            }
2050
2051                            (
2052                                replica_id,
2053                                Selection {
2054                                    id: selection.id,
2055                                    start,
2056                                    end,
2057                                    reversed: selection.reversed,
2058                                    goal: selection.goal,
2059                                },
2060                            )
2061                        })
2062                    })
2063            })
2064    }
2065}
2066
2067impl History {
2068    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2069        self.transaction_depth += 1;
2070        if self.transaction_depth == 1 {
2071            let id = self.next_transaction_id.tick();
2072            self.undo_stack.push(Transaction {
2073                id,
2074                buffer_transactions: Default::default(),
2075                first_edit_at: now,
2076                last_edit_at: now,
2077            });
2078            Some(id)
2079        } else {
2080            None
2081        }
2082    }
2083
2084    fn end_transaction(
2085        &mut self,
2086        now: Instant,
2087        buffer_transactions: HashSet<(usize, TransactionId)>,
2088    ) -> bool {
2089        assert_ne!(self.transaction_depth, 0);
2090        self.transaction_depth -= 1;
2091        if self.transaction_depth == 0 {
2092            if buffer_transactions.is_empty() {
2093                self.undo_stack.pop();
2094                false
2095            } else {
2096                let transaction = self.undo_stack.last_mut().unwrap();
2097                transaction.last_edit_at = now;
2098                transaction.buffer_transactions.extend(buffer_transactions);
2099                true
2100            }
2101        } else {
2102            false
2103        }
2104    }
2105
2106    fn pop_undo(&mut self) -> Option<&Transaction> {
2107        assert_eq!(self.transaction_depth, 0);
2108        if let Some(transaction) = self.undo_stack.pop() {
2109            self.redo_stack.push(transaction);
2110            self.redo_stack.last()
2111        } else {
2112            None
2113        }
2114    }
2115
2116    fn pop_redo(&mut self) -> Option<&Transaction> {
2117        assert_eq!(self.transaction_depth, 0);
2118        if let Some(transaction) = self.redo_stack.pop() {
2119            self.undo_stack.push(transaction);
2120            self.undo_stack.last()
2121        } else {
2122            None
2123        }
2124    }
2125
2126    fn group(&mut self) -> Option<TransactionId> {
2127        let mut new_len = self.undo_stack.len();
2128        let mut transactions = self.undo_stack.iter_mut();
2129
2130        if let Some(mut transaction) = transactions.next_back() {
2131            while let Some(prev_transaction) = transactions.next_back() {
2132                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
2133                {
2134                    transaction = prev_transaction;
2135                    new_len -= 1;
2136                } else {
2137                    break;
2138                }
2139            }
2140        }
2141
2142        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2143        if let Some(last_transaction) = transactions_to_keep.last_mut() {
2144            if let Some(transaction) = transactions_to_merge.last() {
2145                last_transaction.last_edit_at = transaction.last_edit_at;
2146            }
2147        }
2148
2149        self.undo_stack.truncate(new_len);
2150        self.undo_stack.last().map(|t| t.id)
2151    }
2152}
2153
2154impl Excerpt {
2155    fn new(
2156        id: ExcerptId,
2157        buffer_id: usize,
2158        buffer: BufferSnapshot,
2159        range: Range<text::Anchor>,
2160        has_trailing_newline: bool,
2161    ) -> Self {
2162        Excerpt {
2163            id,
2164            max_buffer_row: range.end.to_point(&buffer).row,
2165            text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
2166            buffer_id,
2167            buffer,
2168            range,
2169            has_trailing_newline,
2170        }
2171    }
2172
2173    fn chunks_in_range<'a>(
2174        &'a self,
2175        range: Range<usize>,
2176        language_aware: bool,
2177    ) -> ExcerptChunks<'a> {
2178        let content_start = self.range.start.to_offset(&self.buffer);
2179        let chunks_start = content_start + range.start;
2180        let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2181
2182        let footer_height = if self.has_trailing_newline
2183            && range.start <= self.text_summary.bytes
2184            && range.end > self.text_summary.bytes
2185        {
2186            1
2187        } else {
2188            0
2189        };
2190
2191        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2192
2193        ExcerptChunks {
2194            content_chunks,
2195            footer_height,
2196        }
2197    }
2198
2199    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2200        let content_start = self.range.start.to_offset(&self.buffer);
2201        let bytes_start = content_start + range.start;
2202        let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
2203        let footer_height = if self.has_trailing_newline
2204            && range.start <= self.text_summary.bytes
2205            && range.end > self.text_summary.bytes
2206        {
2207            1
2208        } else {
2209            0
2210        };
2211        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2212
2213        ExcerptBytes {
2214            content_bytes,
2215            footer_height,
2216        }
2217    }
2218
2219    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2220        if text_anchor
2221            .cmp(&self.range.start, &self.buffer)
2222            .unwrap()
2223            .is_lt()
2224        {
2225            self.range.start.clone()
2226        } else if text_anchor
2227            .cmp(&self.range.end, &self.buffer)
2228            .unwrap()
2229            .is_gt()
2230        {
2231            self.range.end.clone()
2232        } else {
2233            text_anchor
2234        }
2235    }
2236
2237    fn contains(&self, anchor: &Anchor) -> bool {
2238        self.buffer_id == anchor.buffer_id
2239            && self
2240                .range
2241                .start
2242                .cmp(&anchor.text_anchor, &self.buffer)
2243                .unwrap()
2244                .is_le()
2245            && self
2246                .range
2247                .end
2248                .cmp(&anchor.text_anchor, &self.buffer)
2249                .unwrap()
2250                .is_ge()
2251    }
2252}
2253
2254impl fmt::Debug for Excerpt {
2255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2256        f.debug_struct("Excerpt")
2257            .field("id", &self.id)
2258            .field("buffer_id", &self.buffer_id)
2259            .field("range", &self.range)
2260            .field("text_summary", &self.text_summary)
2261            .field("has_trailing_newline", &self.has_trailing_newline)
2262            .finish()
2263    }
2264}
2265
2266impl sum_tree::Item for Excerpt {
2267    type Summary = ExcerptSummary;
2268
2269    fn summary(&self) -> Self::Summary {
2270        let mut text = self.text_summary.clone();
2271        if self.has_trailing_newline {
2272            text += TextSummary::from("\n");
2273        }
2274        ExcerptSummary {
2275            excerpt_id: self.id.clone(),
2276            max_buffer_row: self.max_buffer_row,
2277            text,
2278        }
2279    }
2280}
2281
2282impl sum_tree::Summary for ExcerptSummary {
2283    type Context = ();
2284
2285    fn add_summary(&mut self, summary: &Self, _: &()) {
2286        debug_assert!(summary.excerpt_id > self.excerpt_id);
2287        self.excerpt_id = summary.excerpt_id.clone();
2288        self.text.add_summary(&summary.text, &());
2289        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2290    }
2291}
2292
2293impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2294    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2295        *self += &summary.text;
2296    }
2297}
2298
2299impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2300    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2301        *self += summary.text.bytes;
2302    }
2303}
2304
2305impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2306    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2307        Ord::cmp(self, &cursor_location.text.bytes)
2308    }
2309}
2310
2311impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2312    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2313        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2314    }
2315}
2316
2317impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2318    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2319        *self += summary.text.lines;
2320    }
2321}
2322
2323impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2324    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2325        *self += summary.text.lines_utf16
2326    }
2327}
2328
2329impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2330    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2331        *self = Some(&summary.excerpt_id);
2332    }
2333}
2334
2335impl<'a> MultiBufferRows<'a> {
2336    pub fn seek(&mut self, row: u32) {
2337        self.buffer_row_range = 0..0;
2338
2339        self.excerpts
2340            .seek_forward(&Point::new(row, 0), Bias::Right, &());
2341        if self.excerpts.item().is_none() {
2342            self.excerpts.prev(&());
2343
2344            if self.excerpts.item().is_none() && row == 0 {
2345                self.buffer_row_range = 0..1;
2346                return;
2347            }
2348        }
2349
2350        if let Some(excerpt) = self.excerpts.item() {
2351            let overshoot = row - self.excerpts.start().row;
2352            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2353            self.buffer_row_range.start = excerpt_start + overshoot;
2354            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2355        }
2356    }
2357}
2358
2359impl<'a> Iterator for MultiBufferRows<'a> {
2360    type Item = Option<u32>;
2361
2362    fn next(&mut self) -> Option<Self::Item> {
2363        loop {
2364            if !self.buffer_row_range.is_empty() {
2365                let row = Some(self.buffer_row_range.start);
2366                self.buffer_row_range.start += 1;
2367                return Some(row);
2368            }
2369            self.excerpts.item()?;
2370            self.excerpts.next(&());
2371            let excerpt = self.excerpts.item()?;
2372            self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2373            self.buffer_row_range.end =
2374                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2375        }
2376    }
2377}
2378
2379impl<'a> MultiBufferChunks<'a> {
2380    pub fn offset(&self) -> usize {
2381        self.range.start
2382    }
2383
2384    pub fn seek(&mut self, offset: usize) {
2385        self.range.start = offset;
2386        self.excerpts.seek(&offset, Bias::Right, &());
2387        if let Some(excerpt) = self.excerpts.item() {
2388            self.excerpt_chunks = Some(excerpt.chunks_in_range(
2389                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2390                self.language_aware,
2391            ));
2392        } else {
2393            self.excerpt_chunks = None;
2394        }
2395    }
2396}
2397
2398impl<'a> Iterator for MultiBufferChunks<'a> {
2399    type Item = Chunk<'a>;
2400
2401    fn next(&mut self) -> Option<Self::Item> {
2402        if self.range.is_empty() {
2403            None
2404        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2405            self.range.start += chunk.text.len();
2406            Some(chunk)
2407        } else {
2408            self.excerpts.next(&());
2409            let excerpt = self.excerpts.item()?;
2410            self.excerpt_chunks = Some(excerpt.chunks_in_range(
2411                0..self.range.end - self.excerpts.start(),
2412                self.language_aware,
2413            ));
2414            self.next()
2415        }
2416    }
2417}
2418
2419impl<'a> MultiBufferBytes<'a> {
2420    fn consume(&mut self, len: usize) {
2421        self.range.start += len;
2422        self.chunk = &self.chunk[len..];
2423
2424        if !self.range.is_empty() && self.chunk.is_empty() {
2425            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2426                self.chunk = chunk;
2427            } else {
2428                self.excerpts.next(&());
2429                if let Some(excerpt) = self.excerpts.item() {
2430                    let mut excerpt_bytes =
2431                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2432                    self.chunk = excerpt_bytes.next().unwrap();
2433                    self.excerpt_bytes = Some(excerpt_bytes);
2434                }
2435            }
2436        }
2437    }
2438}
2439
2440impl<'a> Iterator for MultiBufferBytes<'a> {
2441    type Item = &'a [u8];
2442
2443    fn next(&mut self) -> Option<Self::Item> {
2444        let chunk = self.chunk;
2445        if chunk.is_empty() {
2446            None
2447        } else {
2448            self.consume(chunk.len());
2449            Some(chunk)
2450        }
2451    }
2452}
2453
2454impl<'a> io::Read for MultiBufferBytes<'a> {
2455    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2456        let len = cmp::min(buf.len(), self.chunk.len());
2457        buf[..len].copy_from_slice(&self.chunk[..len]);
2458        if len > 0 {
2459            self.consume(len);
2460        }
2461        Ok(len)
2462    }
2463}
2464
2465impl<'a> Iterator for ExcerptBytes<'a> {
2466    type Item = &'a [u8];
2467
2468    fn next(&mut self) -> Option<Self::Item> {
2469        if let Some(chunk) = self.content_bytes.next() {
2470            if !chunk.is_empty() {
2471                return Some(chunk);
2472            }
2473        }
2474
2475        if self.footer_height > 0 {
2476            let result = &NEWLINES[..self.footer_height];
2477            self.footer_height = 0;
2478            return Some(result);
2479        }
2480
2481        None
2482    }
2483}
2484
2485impl<'a> Iterator for ExcerptChunks<'a> {
2486    type Item = Chunk<'a>;
2487
2488    fn next(&mut self) -> Option<Self::Item> {
2489        if let Some(chunk) = self.content_chunks.next() {
2490            return Some(chunk);
2491        }
2492
2493        if self.footer_height > 0 {
2494            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2495            self.footer_height = 0;
2496            return Some(Chunk {
2497                text,
2498                ..Default::default()
2499            });
2500        }
2501
2502        None
2503    }
2504}
2505
2506impl ToOffset for Point {
2507    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2508        snapshot.point_to_offset(*self)
2509    }
2510}
2511
2512impl ToOffset for PointUtf16 {
2513    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2514        snapshot.point_utf16_to_offset(*self)
2515    }
2516}
2517
2518impl ToOffset for usize {
2519    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2520        assert!(*self <= snapshot.len(), "offset is out of range");
2521        *self
2522    }
2523}
2524
2525impl ToPoint for usize {
2526    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2527        snapshot.offset_to_point(*self)
2528    }
2529}
2530
2531impl ToPoint for Point {
2532    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2533        *self
2534    }
2535}
2536
2537impl ToPointUtf16 for usize {
2538    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
2539        snapshot.offset_to_point_utf16(*self)
2540    }
2541}
2542
2543impl ToPointUtf16 for Point {
2544    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
2545        snapshot.point_to_point_utf16(*self)
2546    }
2547}
2548
2549impl ToPointUtf16 for PointUtf16 {
2550    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
2551        *self
2552    }
2553}
2554
2555pub fn char_kind(c: char) -> CharKind {
2556    if c == '\n' {
2557        CharKind::Newline
2558    } else if c.is_whitespace() {
2559        CharKind::Whitespace
2560    } else if c.is_alphanumeric() || c == '_' {
2561        CharKind::Word
2562    } else {
2563        CharKind::Punctuation
2564    }
2565}
2566
2567#[cfg(test)]
2568mod tests {
2569    use super::*;
2570    use gpui::MutableAppContext;
2571    use language::{Buffer, Rope};
2572    use rand::prelude::*;
2573    use std::env;
2574    use text::{Point, RandomCharIter};
2575    use util::test::sample_text;
2576
2577    #[gpui::test]
2578    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2579        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2580        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2581
2582        let snapshot = multibuffer.read(cx).snapshot(cx);
2583        assert_eq!(snapshot.text(), buffer.read(cx).text());
2584
2585        assert_eq!(
2586            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2587            (0..buffer.read(cx).row_count())
2588                .map(Some)
2589                .collect::<Vec<_>>()
2590        );
2591
2592        buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2593        let snapshot = multibuffer.read(cx).snapshot(cx);
2594
2595        assert_eq!(snapshot.text(), buffer.read(cx).text());
2596        assert_eq!(
2597            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2598            (0..buffer.read(cx).row_count())
2599                .map(Some)
2600                .collect::<Vec<_>>()
2601        );
2602    }
2603
2604    #[gpui::test]
2605    fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2606        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2607        let guest_buffer = cx.add_model(|cx| {
2608            let message = host_buffer.read(cx).to_proto();
2609            Buffer::from_proto(1, message, None, cx).unwrap()
2610        });
2611        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2612        let snapshot = multibuffer.read(cx).snapshot(cx);
2613        assert_eq!(snapshot.text(), "a");
2614
2615        guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2616        let snapshot = multibuffer.read(cx).snapshot(cx);
2617        assert_eq!(snapshot.text(), "ab");
2618
2619        guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2620        let snapshot = multibuffer.read(cx).snapshot(cx);
2621        assert_eq!(snapshot.text(), "abc");
2622    }
2623
2624    #[gpui::test]
2625    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2626        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2627        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2628        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2629
2630        let subscription = multibuffer.update(cx, |multibuffer, cx| {
2631            let subscription = multibuffer.subscribe();
2632            multibuffer.push_excerpt(
2633                ExcerptProperties {
2634                    buffer: &buffer_1,
2635                    range: Point::new(1, 2)..Point::new(2, 5),
2636                },
2637                cx,
2638            );
2639            assert_eq!(
2640                subscription.consume().into_inner(),
2641                [Edit {
2642                    old: 0..0,
2643                    new: 0..10
2644                }]
2645            );
2646
2647            multibuffer.push_excerpt(
2648                ExcerptProperties {
2649                    buffer: &buffer_1,
2650                    range: Point::new(3, 3)..Point::new(4, 4),
2651                },
2652                cx,
2653            );
2654            multibuffer.push_excerpt(
2655                ExcerptProperties {
2656                    buffer: &buffer_2,
2657                    range: Point::new(3, 1)..Point::new(3, 3),
2658                },
2659                cx,
2660            );
2661            assert_eq!(
2662                subscription.consume().into_inner(),
2663                [Edit {
2664                    old: 10..10,
2665                    new: 10..22
2666                }]
2667            );
2668
2669            subscription
2670        });
2671
2672        let snapshot = multibuffer.read(cx).snapshot(cx);
2673        assert_eq!(
2674            snapshot.text(),
2675            concat!(
2676                "bbbb\n",  // Preserve newlines
2677                "ccccc\n", //
2678                "ddd\n",   //
2679                "eeee\n",  //
2680                "jj"       //
2681            )
2682        );
2683        assert_eq!(
2684            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2685            [Some(1), Some(2), Some(3), Some(4), Some(3)]
2686        );
2687        assert_eq!(
2688            snapshot.buffer_rows(2).collect::<Vec<_>>(),
2689            [Some(3), Some(4), Some(3)]
2690        );
2691        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2692        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2693        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(1, 5)));
2694        assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(2, 0)));
2695        assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(4, 0)));
2696        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(2, 0)..Point::new(3, 0)));
2697        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 0)..Point::new(4, 2)));
2698        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 2)..Point::new(4, 2)));
2699
2700        buffer_1.update(cx, |buffer, cx| {
2701            buffer.edit(
2702                [
2703                    Point::new(0, 0)..Point::new(0, 0),
2704                    Point::new(2, 1)..Point::new(2, 3),
2705                ],
2706                "\n",
2707                cx,
2708            );
2709        });
2710
2711        let snapshot = multibuffer.read(cx).snapshot(cx);
2712        assert_eq!(
2713            snapshot.text(),
2714            concat!(
2715                "bbbb\n", // Preserve newlines
2716                "c\n",    //
2717                "cc\n",   //
2718                "ddd\n",  //
2719                "eeee\n", //
2720                "jj"      //
2721            )
2722        );
2723
2724        assert_eq!(
2725            subscription.consume().into_inner(),
2726            [Edit {
2727                old: 6..8,
2728                new: 6..7
2729            }]
2730        );
2731
2732        let snapshot = multibuffer.read(cx).snapshot(cx);
2733        assert_eq!(
2734            snapshot.clip_point(Point::new(0, 5), Bias::Left),
2735            Point::new(0, 4)
2736        );
2737        assert_eq!(
2738            snapshot.clip_point(Point::new(0, 5), Bias::Right),
2739            Point::new(0, 4)
2740        );
2741        assert_eq!(
2742            snapshot.clip_point(Point::new(5, 1), Bias::Right),
2743            Point::new(5, 1)
2744        );
2745        assert_eq!(
2746            snapshot.clip_point(Point::new(5, 2), Bias::Right),
2747            Point::new(5, 2)
2748        );
2749        assert_eq!(
2750            snapshot.clip_point(Point::new(5, 3), Bias::Right),
2751            Point::new(5, 2)
2752        );
2753
2754        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2755            let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2756            multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2757            multibuffer.snapshot(cx)
2758        });
2759
2760        assert_eq!(
2761            snapshot.text(),
2762            concat!(
2763                "bbbb\n", // Preserve newlines
2764                "c\n",    //
2765                "cc\n",   //
2766                "ddd\n",  //
2767                "eeee",   //
2768            )
2769        );
2770    }
2771
2772    #[gpui::test]
2773    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2774        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2775
2776        let snapshot = multibuffer.read(cx).snapshot(cx);
2777        assert_eq!(snapshot.text(), "");
2778        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2779        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2780    }
2781
2782    #[gpui::test]
2783    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2784        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2785        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2786        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2787        buffer.update(cx, |buffer, cx| {
2788            buffer.edit([0..0], "X", cx);
2789            buffer.edit([5..5], "Y", cx);
2790        });
2791        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2792
2793        assert_eq!(old_snapshot.text(), "abcd");
2794        assert_eq!(new_snapshot.text(), "XabcdY");
2795
2796        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2797        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2798        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2799        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2800    }
2801
2802    #[gpui::test]
2803    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2804        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2805        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2806        let multibuffer = cx.add_model(|cx| {
2807            let mut multibuffer = MultiBuffer::new(0);
2808            multibuffer.push_excerpt(
2809                ExcerptProperties {
2810                    buffer: &buffer_1,
2811                    range: 0..4,
2812                },
2813                cx,
2814            );
2815            multibuffer.push_excerpt(
2816                ExcerptProperties {
2817                    buffer: &buffer_2,
2818                    range: 0..5,
2819                },
2820                cx,
2821            );
2822            multibuffer
2823        });
2824        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2825
2826        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2827        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2828        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2829        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2830        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2831        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2832
2833        buffer_1.update(cx, |buffer, cx| {
2834            buffer.edit([0..0], "W", cx);
2835            buffer.edit([5..5], "X", cx);
2836        });
2837        buffer_2.update(cx, |buffer, cx| {
2838            buffer.edit([0..0], "Y", cx);
2839            buffer.edit([6..0], "Z", cx);
2840        });
2841        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2842
2843        assert_eq!(old_snapshot.text(), "abcd\nefghi");
2844        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2845
2846        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2847        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2848        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2849        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2850        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2851        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2852        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2853        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2854        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2855        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2856    }
2857
2858    #[gpui::test]
2859    fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
2860        cx: &mut MutableAppContext,
2861    ) {
2862        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2863        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
2864        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2865
2866        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
2867        // Add an excerpt from buffer 1 that spans this new insertion.
2868        buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
2869        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
2870            multibuffer.push_excerpt(
2871                ExcerptProperties {
2872                    buffer: &buffer_1,
2873                    range: 0..7,
2874                },
2875                cx,
2876            )
2877        });
2878
2879        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
2880        assert_eq!(snapshot_1.text(), "abcd123");
2881
2882        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
2883        let (excerpt_id_2, excerpt_id_3, _) = multibuffer.update(cx, |multibuffer, cx| {
2884            multibuffer.remove_excerpts([&excerpt_id_1], cx);
2885            (
2886                multibuffer.push_excerpt(
2887                    ExcerptProperties {
2888                        buffer: &buffer_2,
2889                        range: 0..4,
2890                    },
2891                    cx,
2892                ),
2893                multibuffer.push_excerpt(
2894                    ExcerptProperties {
2895                        buffer: &buffer_2,
2896                        range: 6..10,
2897                    },
2898                    cx,
2899                ),
2900                multibuffer.push_excerpt(
2901                    ExcerptProperties {
2902                        buffer: &buffer_2,
2903                        range: 12..16,
2904                    },
2905                    cx,
2906                ),
2907            )
2908        });
2909        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
2910        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
2911
2912        // The old excerpt id has been reused.
2913        assert_eq!(excerpt_id_2, excerpt_id_1);
2914
2915        // Resolve some anchors from the previous snapshot in the new snapshot.
2916        // Although there is still an excerpt with the same id, it is for
2917        // a different buffer, so we don't attempt to resolve the old text
2918        // anchor in the new buffer.
2919        assert_eq!(
2920            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
2921            0
2922        );
2923        assert_eq!(
2924            snapshot_2.summaries_for_anchors::<usize, _>(&[
2925                snapshot_1.anchor_before(2),
2926                snapshot_1.anchor_after(3)
2927            ]),
2928            vec![0, 0]
2929        );
2930        let refresh =
2931            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
2932        assert_eq!(
2933            refresh,
2934            &[
2935                (0, snapshot_2.anchor_before(0), false),
2936                (1, snapshot_2.anchor_after(0), false),
2937            ]
2938        );
2939
2940        // Replace the middle excerpt with a smaller excerpt in buffer 2,
2941        // that intersects the old excerpt.
2942        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
2943            multibuffer.remove_excerpts([&excerpt_id_3], cx);
2944            multibuffer.insert_excerpt_after(
2945                &excerpt_id_3,
2946                ExcerptProperties {
2947                    buffer: &buffer_2,
2948                    range: 5..8,
2949                },
2950                cx,
2951            )
2952        });
2953
2954        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
2955        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
2956        assert_ne!(excerpt_id_5, excerpt_id_3);
2957
2958        // Resolve some anchors from the previous snapshot in the new snapshot.
2959        // The anchor in the middle excerpt snaps to the beginning of the
2960        // excerpt, since it is not
2961        let anchors = [
2962            snapshot_2.anchor_before(0),
2963            snapshot_2.anchor_after(2),
2964            snapshot_2.anchor_after(6),
2965            snapshot_2.anchor_after(14),
2966        ];
2967        assert_eq!(
2968            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
2969            &[0, 2, 9, 13]
2970        );
2971
2972        let new_anchors = snapshot_3.refresh_anchors(&anchors);
2973        assert_eq!(
2974            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
2975            &[(0, true), (1, true), (2, true), (3, true)]
2976        );
2977        assert_eq!(
2978            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
2979            &[0, 2, 7, 13]
2980        );
2981    }
2982
2983    #[gpui::test(iterations = 100)]
2984    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
2985        let operations = env::var("OPERATIONS")
2986            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2987            .unwrap_or(10);
2988
2989        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2990        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2991        let mut excerpt_ids = Vec::new();
2992        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2993        let mut anchors = Vec::new();
2994        let mut old_versions = Vec::new();
2995
2996        for _ in 0..operations {
2997            match rng.gen_range(0..100) {
2998                0..=19 if !buffers.is_empty() => {
2999                    let buffer = buffers.choose(&mut rng).unwrap();
3000                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
3001                }
3002                20..=29 if !expected_excerpts.is_empty() => {
3003                    let mut ids_to_remove = vec![];
3004                    for _ in 0..rng.gen_range(1..=3) {
3005                        if expected_excerpts.is_empty() {
3006                            break;
3007                        }
3008
3009                        let ix = rng.gen_range(0..expected_excerpts.len());
3010                        ids_to_remove.push(excerpt_ids.remove(ix));
3011                        let (buffer, range) = expected_excerpts.remove(ix);
3012                        let buffer = buffer.read(cx);
3013                        log::info!(
3014                            "Removing excerpt {}: {:?}",
3015                            ix,
3016                            buffer
3017                                .text_for_range(range.to_offset(&buffer))
3018                                .collect::<String>(),
3019                        );
3020                    }
3021                    ids_to_remove.sort_unstable();
3022                    multibuffer.update(cx, |multibuffer, cx| {
3023                        multibuffer.remove_excerpts(&ids_to_remove, cx)
3024                    });
3025                }
3026                30..=39 if !expected_excerpts.is_empty() => {
3027                    let multibuffer = multibuffer.read(cx).read(cx);
3028                    let offset =
3029                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
3030                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
3031                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
3032                    anchors.push(multibuffer.anchor_at(offset, bias));
3033                    anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
3034                }
3035                40..=44 if !anchors.is_empty() => {
3036                    let multibuffer = multibuffer.read(cx).read(cx);
3037
3038                    anchors = multibuffer
3039                        .refresh_anchors(&anchors)
3040                        .into_iter()
3041                        .map(|a| a.1)
3042                        .collect();
3043
3044                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
3045                    // overshoot its boundaries.
3046                    let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
3047                    for anchor in &anchors {
3048                        if anchor.excerpt_id == ExcerptId::min()
3049                            || anchor.excerpt_id == ExcerptId::max()
3050                        {
3051                            continue;
3052                        }
3053
3054                        cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
3055                        let excerpt = cursor.item().unwrap();
3056                        assert_eq!(excerpt.id, anchor.excerpt_id);
3057                        assert!(excerpt.contains(anchor));
3058                    }
3059                }
3060                _ => {
3061                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
3062                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
3063                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
3064                        buffers.last().unwrap()
3065                    } else {
3066                        buffers.choose(&mut rng).unwrap()
3067                    };
3068
3069                    let buffer = buffer_handle.read(cx);
3070                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3071                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3072                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3073                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3074                    let prev_excerpt_id = excerpt_ids
3075                        .get(prev_excerpt_ix)
3076                        .cloned()
3077                        .unwrap_or(ExcerptId::max());
3078                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3079
3080                    log::info!(
3081                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3082                        excerpt_ix,
3083                        expected_excerpts.len(),
3084                        buffer_handle.id(),
3085                        buffer.text(),
3086                        start_ix..end_ix,
3087                        &buffer.text()[start_ix..end_ix]
3088                    );
3089
3090                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3091                        multibuffer.insert_excerpt_after(
3092                            &prev_excerpt_id,
3093                            ExcerptProperties {
3094                                buffer: &buffer_handle,
3095                                range: start_ix..end_ix,
3096                            },
3097                            cx,
3098                        )
3099                    });
3100
3101                    excerpt_ids.insert(excerpt_ix, excerpt_id);
3102                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3103                }
3104            }
3105
3106            if rng.gen_bool(0.3) {
3107                multibuffer.update(cx, |multibuffer, cx| {
3108                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3109                })
3110            }
3111
3112            let snapshot = multibuffer.read(cx).snapshot(cx);
3113
3114            let mut excerpt_starts = Vec::new();
3115            let mut expected_text = String::new();
3116            let mut expected_buffer_rows = Vec::new();
3117            for (buffer, range) in &expected_excerpts {
3118                let buffer = buffer.read(cx);
3119                let buffer_range = range.to_offset(buffer);
3120
3121                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3122                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3123                expected_text.push('\n');
3124
3125                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3126                    ..=buffer.offset_to_point(buffer_range.end).row;
3127                for row in buffer_row_range {
3128                    expected_buffer_rows.push(Some(row));
3129                }
3130            }
3131            // Remove final trailing newline.
3132            if !expected_excerpts.is_empty() {
3133                expected_text.pop();
3134            }
3135
3136            // Always report one buffer row
3137            if expected_buffer_rows.is_empty() {
3138                expected_buffer_rows.push(Some(0));
3139            }
3140
3141            assert_eq!(snapshot.text(), expected_text);
3142            log::info!("MultiBuffer text: {:?}", expected_text);
3143
3144            assert_eq!(
3145                snapshot.buffer_rows(0).collect::<Vec<_>>(),
3146                expected_buffer_rows,
3147            );
3148
3149            for _ in 0..5 {
3150                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3151                assert_eq!(
3152                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3153                    &expected_buffer_rows[start_row..],
3154                    "buffer_rows({})",
3155                    start_row
3156                );
3157            }
3158
3159            assert_eq!(
3160                snapshot.max_buffer_row(),
3161                expected_buffer_rows
3162                    .into_iter()
3163                    .filter_map(|r| r)
3164                    .max()
3165                    .unwrap()
3166            );
3167
3168            let mut excerpt_starts = excerpt_starts.into_iter();
3169            for (buffer, range) in &expected_excerpts {
3170                let buffer_id = buffer.id();
3171                let buffer = buffer.read(cx);
3172                let buffer_range = range.to_offset(buffer);
3173                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3174                let buffer_start_point_utf16 =
3175                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3176
3177                let excerpt_start = excerpt_starts.next().unwrap();
3178                let mut offset = excerpt_start.bytes;
3179                let mut buffer_offset = buffer_range.start;
3180                let mut point = excerpt_start.lines;
3181                let mut buffer_point = buffer_start_point;
3182                let mut point_utf16 = excerpt_start.lines_utf16;
3183                let mut buffer_point_utf16 = buffer_start_point_utf16;
3184                for ch in buffer
3185                    .snapshot()
3186                    .chunks(buffer_range.clone(), false)
3187                    .flat_map(|c| c.text.chars())
3188                {
3189                    for _ in 0..ch.len_utf8() {
3190                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
3191                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
3192                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3193                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3194                        assert_eq!(
3195                            left_offset,
3196                            excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
3197                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3198                            offset,
3199                            buffer_id,
3200                            buffer_offset,
3201                        );
3202                        assert_eq!(
3203                            right_offset,
3204                            excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
3205                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3206                            offset,
3207                            buffer_id,
3208                            buffer_offset,
3209                        );
3210
3211                        let left_point = snapshot.clip_point(point, Bias::Left);
3212                        let right_point = snapshot.clip_point(point, Bias::Right);
3213                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3214                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3215                        assert_eq!(
3216                            left_point,
3217                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
3218                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3219                            point,
3220                            buffer_id,
3221                            buffer_point,
3222                        );
3223                        assert_eq!(
3224                            right_point,
3225                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
3226                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3227                            point,
3228                            buffer_id,
3229                            buffer_point,
3230                        );
3231
3232                        assert_eq!(
3233                            snapshot.point_to_offset(left_point),
3234                            left_offset,
3235                            "point_to_offset({:?})",
3236                            left_point,
3237                        );
3238                        assert_eq!(
3239                            snapshot.offset_to_point(left_offset),
3240                            left_point,
3241                            "offset_to_point({:?})",
3242                            left_offset,
3243                        );
3244
3245                        offset += 1;
3246                        buffer_offset += 1;
3247                        if ch == '\n' {
3248                            point += Point::new(1, 0);
3249                            buffer_point += Point::new(1, 0);
3250                        } else {
3251                            point += Point::new(0, 1);
3252                            buffer_point += Point::new(0, 1);
3253                        }
3254                    }
3255
3256                    for _ in 0..ch.len_utf16() {
3257                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
3258                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
3259                        let buffer_left_point_utf16 =
3260                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
3261                        let buffer_right_point_utf16 =
3262                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
3263                        assert_eq!(
3264                            left_point_utf16,
3265                            excerpt_start.lines_utf16
3266                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
3267                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
3268                            point_utf16,
3269                            buffer_id,
3270                            buffer_point_utf16,
3271                        );
3272                        assert_eq!(
3273                            right_point_utf16,
3274                            excerpt_start.lines_utf16
3275                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
3276                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
3277                            point_utf16,
3278                            buffer_id,
3279                            buffer_point_utf16,
3280                        );
3281
3282                        if ch == '\n' {
3283                            point_utf16 += PointUtf16::new(1, 0);
3284                            buffer_point_utf16 += PointUtf16::new(1, 0);
3285                        } else {
3286                            point_utf16 += PointUtf16::new(0, 1);
3287                            buffer_point_utf16 += PointUtf16::new(0, 1);
3288                        }
3289                    }
3290                }
3291            }
3292
3293            for (row, line) in expected_text.split('\n').enumerate() {
3294                assert_eq!(
3295                    snapshot.line_len(row as u32),
3296                    line.len() as u32,
3297                    "line_len({}).",
3298                    row
3299                );
3300            }
3301
3302            let text_rope = Rope::from(expected_text.as_str());
3303            for _ in 0..10 {
3304                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3305                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3306
3307                let text_for_range = snapshot
3308                    .text_for_range(start_ix..end_ix)
3309                    .collect::<String>();
3310                assert_eq!(
3311                    text_for_range,
3312                    &expected_text[start_ix..end_ix],
3313                    "incorrect text for range {:?}",
3314                    start_ix..end_ix
3315                );
3316
3317                let excerpted_buffer_ranges =
3318                    multibuffer.read(cx).excerpted_buffers(start_ix..end_ix, cx);
3319                let excerpted_buffers_text = excerpted_buffer_ranges
3320                    .into_iter()
3321                    .map(|(buffer, buffer_range)| {
3322                        buffer
3323                            .read(cx)
3324                            .text_for_range(buffer_range)
3325                            .collect::<String>()
3326                    })
3327                    .collect::<Vec<_>>()
3328                    .join("\n");
3329                assert_eq!(excerpted_buffers_text, text_for_range);
3330
3331                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3332                assert_eq!(
3333                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3334                    expected_summary,
3335                    "incorrect summary for range {:?}",
3336                    start_ix..end_ix
3337                );
3338            }
3339
3340            // Anchor resolution
3341            for (anchor, resolved_offset) in anchors
3342                .iter()
3343                .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3344            {
3345                assert!(resolved_offset <= snapshot.len());
3346                assert_eq!(
3347                    snapshot.summary_for_anchor::<usize>(anchor),
3348                    resolved_offset
3349                );
3350            }
3351
3352            for _ in 0..10 {
3353                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3354                assert_eq!(
3355                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
3356                    expected_text[..end_ix].chars().rev().collect::<String>(),
3357                );
3358            }
3359
3360            for _ in 0..10 {
3361                let end_ix = rng.gen_range(0..=text_rope.len());
3362                let start_ix = rng.gen_range(0..=end_ix);
3363                assert_eq!(
3364                    snapshot
3365                        .bytes_in_range(start_ix..end_ix)
3366                        .flatten()
3367                        .copied()
3368                        .collect::<Vec<_>>(),
3369                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3370                    "bytes_in_range({:?})",
3371                    start_ix..end_ix,
3372                );
3373            }
3374        }
3375
3376        let snapshot = multibuffer.read(cx).snapshot(cx);
3377        for (old_snapshot, subscription) in old_versions {
3378            let edits = subscription.consume().into_inner();
3379
3380            log::info!(
3381                "applying subscription edits to old text: {:?}: {:?}",
3382                old_snapshot.text(),
3383                edits,
3384            );
3385
3386            let mut text = old_snapshot.text();
3387            for edit in edits {
3388                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3389                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3390            }
3391            assert_eq!(text.to_string(), snapshot.text());
3392        }
3393    }
3394
3395    #[gpui::test]
3396    fn test_history(cx: &mut MutableAppContext) {
3397        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3398        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3399        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3400        let group_interval = multibuffer.read(cx).history.group_interval;
3401        multibuffer.update(cx, |multibuffer, cx| {
3402            multibuffer.push_excerpt(
3403                ExcerptProperties {
3404                    buffer: &buffer_1,
3405                    range: 0..buffer_1.read(cx).len(),
3406                },
3407                cx,
3408            );
3409            multibuffer.push_excerpt(
3410                ExcerptProperties {
3411                    buffer: &buffer_2,
3412                    range: 0..buffer_2.read(cx).len(),
3413                },
3414                cx,
3415            );
3416        });
3417
3418        let mut now = Instant::now();
3419
3420        multibuffer.update(cx, |multibuffer, cx| {
3421            multibuffer.start_transaction_at(now, cx);
3422            multibuffer.edit(
3423                [
3424                    Point::new(0, 0)..Point::new(0, 0),
3425                    Point::new(1, 0)..Point::new(1, 0),
3426                ],
3427                "A",
3428                cx,
3429            );
3430            multibuffer.edit(
3431                [
3432                    Point::new(0, 1)..Point::new(0, 1),
3433                    Point::new(1, 1)..Point::new(1, 1),
3434                ],
3435                "B",
3436                cx,
3437            );
3438            multibuffer.end_transaction_at(now, cx);
3439            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3440
3441            now += 2 * group_interval;
3442            multibuffer.start_transaction_at(now, cx);
3443            multibuffer.edit([2..2], "C", cx);
3444            multibuffer.end_transaction_at(now, cx);
3445            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3446
3447            multibuffer.undo(cx);
3448            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3449
3450            multibuffer.undo(cx);
3451            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3452
3453            multibuffer.redo(cx);
3454            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3455
3456            multibuffer.redo(cx);
3457            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3458
3459            buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3460            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3461
3462            multibuffer.undo(cx);
3463            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3464
3465            multibuffer.redo(cx);
3466            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3467
3468            multibuffer.redo(cx);
3469            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3470
3471            multibuffer.undo(cx);
3472            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3473
3474            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3475            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3476
3477            multibuffer.undo(cx);
3478            assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3479        });
3480    }
3481}