multi_buffer.rs

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