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