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