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