multi_buffer.rs

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