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