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