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