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