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