multi_buffer.rs

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