multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt};
   4use clock::ReplicaId;
   5use collections::{BTreeMap, Bound, HashMap, HashSet};
   6use futures::{channel::mpsc, SinkExt};
   7use git::diff::DiffHunk;
   8use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
   9pub use language::Completion;
  10use language::{
  11    char_kind, AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind, Chunk, CursorShape,
  12    DiagnosticEntry, IndentSize, Language, LanguageScope, OffsetRangeExt, OffsetUtf16, Outline,
  13    OutlineItem, Point, PointUtf16, Selection, TextDimension, ToOffset as _, ToOffsetUtf16 as _,
  14    ToPoint as _, ToPointUtf16 as _, TransactionId, Unclipped,
  15};
  16use std::{
  17    borrow::Cow,
  18    cell::{Ref, RefCell},
  19    cmp, fmt, io,
  20    iter::{self, FromIterator},
  21    mem,
  22    ops::{Range, RangeBounds, Sub},
  23    str,
  24    sync::Arc,
  25    time::{Duration, Instant},
  26};
  27use sum_tree::{Bias, Cursor, SumTree};
  28use text::{
  29    locator::Locator,
  30    subscription::{Subscription, Topic},
  31    Edit, TextSummary,
  32};
  33use theme::SyntaxTheme;
  34use util::post_inc;
  35
  36const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
  37
  38#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
  39pub struct ExcerptId(usize);
  40
  41pub struct MultiBuffer {
  42    snapshot: RefCell<MultiBufferSnapshot>,
  43    buffers: RefCell<HashMap<usize, BufferState>>,
  44    next_excerpt_id: usize,
  45    subscriptions: Topic,
  46    singleton: bool,
  47    replica_id: ReplicaId,
  48    history: History,
  49    title: Option<String>,
  50}
  51
  52#[derive(Clone, Debug, PartialEq, Eq)]
  53pub enum Event {
  54    ExcerptsAdded {
  55        buffer: ModelHandle<Buffer>,
  56        predecessor: ExcerptId,
  57        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
  58    },
  59    ExcerptsRemoved {
  60        ids: Vec<ExcerptId>,
  61    },
  62    Edited,
  63    Reloaded,
  64    Reparsed,
  65    Saved,
  66    FileHandleChanged,
  67    Closed,
  68    DirtyChanged,
  69    DiagnosticsUpdated,
  70}
  71
  72#[derive(Clone)]
  73struct History {
  74    next_transaction_id: TransactionId,
  75    undo_stack: Vec<Transaction>,
  76    redo_stack: Vec<Transaction>,
  77    transaction_depth: usize,
  78    group_interval: Duration,
  79}
  80
  81#[derive(Clone)]
  82struct Transaction {
  83    id: TransactionId,
  84    buffer_transactions: HashMap<usize, text::TransactionId>,
  85    first_edit_at: Instant,
  86    last_edit_at: Instant,
  87    suppress_grouping: bool,
  88}
  89
  90pub trait ToOffset: 'static + fmt::Debug {
  91    fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
  92}
  93
  94pub trait ToOffsetUtf16: 'static + fmt::Debug {
  95    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16;
  96}
  97
  98pub trait ToPoint: 'static + fmt::Debug {
  99    fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
 100}
 101
 102pub trait ToPointUtf16: 'static + fmt::Debug {
 103    fn to_point_utf16(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16;
 104}
 105
 106struct BufferState {
 107    buffer: ModelHandle<Buffer>,
 108    last_version: clock::Global,
 109    last_parse_count: usize,
 110    last_selections_update_count: usize,
 111    last_diagnostics_update_count: usize,
 112    last_file_update_count: usize,
 113    last_git_diff_update_count: usize,
 114    excerpts: Vec<Locator>,
 115    _subscriptions: [gpui::Subscription; 2],
 116}
 117
 118#[derive(Clone, Default)]
 119pub struct MultiBufferSnapshot {
 120    singleton: bool,
 121    excerpts: SumTree<Excerpt>,
 122    excerpt_ids: SumTree<ExcerptIdMapping>,
 123    parse_count: usize,
 124    diagnostics_update_count: usize,
 125    trailing_excerpt_update_count: usize,
 126    git_diff_update_count: usize,
 127    edit_count: usize,
 128    is_dirty: bool,
 129    has_conflict: bool,
 130}
 131
 132pub struct ExcerptBoundary {
 133    pub id: ExcerptId,
 134    pub row: u32,
 135    pub buffer: BufferSnapshot,
 136    pub range: ExcerptRange<text::Anchor>,
 137    pub starts_new_buffer: bool,
 138}
 139
 140#[derive(Clone)]
 141struct Excerpt {
 142    id: ExcerptId,
 143    locator: Locator,
 144    buffer_id: usize,
 145    buffer: BufferSnapshot,
 146    range: ExcerptRange<text::Anchor>,
 147    max_buffer_row: u32,
 148    text_summary: TextSummary,
 149    has_trailing_newline: bool,
 150}
 151
 152#[derive(Clone, Debug)]
 153struct ExcerptIdMapping {
 154    id: ExcerptId,
 155    locator: Locator,
 156}
 157
 158#[derive(Clone, Debug, Eq, PartialEq)]
 159pub struct ExcerptRange<T> {
 160    pub context: Range<T>,
 161    pub primary: Option<Range<T>>,
 162}
 163
 164#[derive(Clone, Debug, Default)]
 165struct ExcerptSummary {
 166    excerpt_id: ExcerptId,
 167    excerpt_locator: Locator,
 168    max_buffer_row: u32,
 169    text: TextSummary,
 170}
 171
 172#[derive(Clone)]
 173pub struct MultiBufferRows<'a> {
 174    buffer_row_range: Range<u32>,
 175    excerpts: Cursor<'a, Excerpt, Point>,
 176}
 177
 178pub struct MultiBufferChunks<'a> {
 179    range: Range<usize>,
 180    excerpts: Cursor<'a, Excerpt, usize>,
 181    excerpt_chunks: Option<ExcerptChunks<'a>>,
 182    language_aware: bool,
 183}
 184
 185pub struct MultiBufferBytes<'a> {
 186    range: Range<usize>,
 187    excerpts: Cursor<'a, Excerpt, usize>,
 188    excerpt_bytes: Option<ExcerptBytes<'a>>,
 189    chunk: &'a [u8],
 190}
 191
 192struct ExcerptChunks<'a> {
 193    content_chunks: BufferChunks<'a>,
 194    footer_height: usize,
 195}
 196
 197struct ExcerptBytes<'a> {
 198    content_bytes: text::Bytes<'a>,
 199    footer_height: usize,
 200}
 201
 202impl MultiBuffer {
 203    pub fn new(replica_id: ReplicaId) -> Self {
 204        Self {
 205            snapshot: Default::default(),
 206            buffers: Default::default(),
 207            next_excerpt_id: 1,
 208            subscriptions: Default::default(),
 209            singleton: false,
 210            replica_id,
 211            history: History {
 212                next_transaction_id: Default::default(),
 213                undo_stack: Default::default(),
 214                redo_stack: Default::default(),
 215                transaction_depth: 0,
 216                group_interval: Duration::from_millis(300),
 217            },
 218            title: Default::default(),
 219        }
 220    }
 221
 222    pub fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self {
 223        let mut buffers = HashMap::default();
 224        for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
 225            buffers.insert(
 226                *buffer_id,
 227                BufferState {
 228                    buffer: buffer_state.buffer.clone(),
 229                    last_version: buffer_state.last_version.clone(),
 230                    last_parse_count: buffer_state.last_parse_count,
 231                    last_selections_update_count: buffer_state.last_selections_update_count,
 232                    last_diagnostics_update_count: buffer_state.last_diagnostics_update_count,
 233                    last_file_update_count: buffer_state.last_file_update_count,
 234                    last_git_diff_update_count: buffer_state.last_git_diff_update_count,
 235                    excerpts: buffer_state.excerpts.clone(),
 236                    _subscriptions: [
 237                        new_cx.observe(&buffer_state.buffer, |_, _, cx| cx.notify()),
 238                        new_cx.subscribe(&buffer_state.buffer, Self::on_buffer_event),
 239                    ],
 240                },
 241            );
 242        }
 243        Self {
 244            snapshot: RefCell::new(self.snapshot.borrow().clone()),
 245            buffers: RefCell::new(buffers),
 246            next_excerpt_id: 1,
 247            subscriptions: Default::default(),
 248            singleton: self.singleton,
 249            replica_id: self.replica_id,
 250            history: self.history.clone(),
 251            title: self.title.clone(),
 252        }
 253    }
 254
 255    pub fn with_title(mut self, title: String) -> Self {
 256        self.title = Some(title);
 257        self
 258    }
 259
 260    pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
 261        let mut this = Self::new(buffer.read(cx).replica_id());
 262        this.singleton = true;
 263        this.push_excerpts(
 264            buffer,
 265            [ExcerptRange {
 266                context: text::Anchor::MIN..text::Anchor::MAX,
 267                primary: None,
 268            }],
 269            cx,
 270        );
 271        this.snapshot.borrow_mut().singleton = true;
 272        this
 273    }
 274
 275    pub fn replica_id(&self) -> ReplicaId {
 276        self.replica_id
 277    }
 278
 279    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
 280        self.sync(cx);
 281        self.snapshot.borrow().clone()
 282    }
 283
 284    pub(crate) fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
 285        self.sync(cx);
 286        self.snapshot.borrow()
 287    }
 288
 289    pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
 290        if self.singleton {
 291            return Some(
 292                self.buffers
 293                    .borrow()
 294                    .values()
 295                    .next()
 296                    .unwrap()
 297                    .buffer
 298                    .clone(),
 299            );
 300        } else {
 301            None
 302        }
 303    }
 304
 305    pub fn is_singleton(&self) -> bool {
 306        self.singleton
 307    }
 308
 309    pub fn subscribe(&mut self) -> Subscription {
 310        self.subscriptions.subscribe()
 311    }
 312
 313    pub fn is_dirty(&self, cx: &AppContext) -> bool {
 314        self.read(cx).is_dirty()
 315    }
 316
 317    pub fn has_conflict(&self, cx: &AppContext) -> bool {
 318        self.read(cx).has_conflict()
 319    }
 320
 321    // The `is_empty` signature doesn't match what clippy expects
 322    #[allow(clippy::len_without_is_empty)]
 323    pub fn len(&self, cx: &AppContext) -> usize {
 324        self.read(cx).len()
 325    }
 326
 327    pub fn is_empty(&self, cx: &AppContext) -> bool {
 328        self.len(cx) != 0
 329    }
 330
 331    pub fn symbols_containing<T: ToOffset>(
 332        &self,
 333        offset: T,
 334        theme: Option<&SyntaxTheme>,
 335        cx: &AppContext,
 336    ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
 337        self.read(cx).symbols_containing(offset, theme)
 338    }
 339
 340    pub fn git_diff_recalc(&mut self, cx: &mut ModelContext<Self>) {
 341        let buffers = self.buffers.borrow();
 342        for buffer_state in buffers.values() {
 343            if buffer_state.buffer.read(cx).needs_git_diff_recalc() {
 344                buffer_state
 345                    .buffer
 346                    .update(cx, |buffer, cx| buffer.git_diff_recalc(cx))
 347            }
 348        }
 349    }
 350
 351    pub fn edit<I, S, T>(
 352        &mut self,
 353        edits: I,
 354        mut autoindent_mode: Option<AutoindentMode>,
 355        cx: &mut ModelContext<Self>,
 356    ) where
 357        I: IntoIterator<Item = (Range<S>, T)>,
 358        S: ToOffset,
 359        T: Into<Arc<str>>,
 360    {
 361        if self.buffers.borrow().is_empty() {
 362            return;
 363        }
 364
 365        let snapshot = self.read(cx);
 366        let edits = edits.into_iter().map(|(range, new_text)| {
 367            let mut range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot);
 368            if range.start > range.end {
 369                mem::swap(&mut range.start, &mut range.end);
 370            }
 371            (range, new_text)
 372        });
 373
 374        if let Some(buffer) = self.as_singleton() {
 375            return buffer.update(cx, |buffer, cx| {
 376                buffer.edit(edits, autoindent_mode, cx);
 377            });
 378        }
 379
 380        let original_indent_columns = match &mut autoindent_mode {
 381            Some(AutoindentMode::Block {
 382                original_indent_columns,
 383            }) => mem::take(original_indent_columns),
 384            _ => Default::default(),
 385        };
 386
 387        struct BufferEdit {
 388            range: Range<usize>,
 389            new_text: Arc<str>,
 390            is_insertion: bool,
 391            original_indent_column: u32,
 392        }
 393        let mut buffer_edits: HashMap<usize, Vec<BufferEdit>> = Default::default();
 394        let mut cursor = snapshot.excerpts.cursor::<usize>();
 395        for (ix, (range, new_text)) in edits.enumerate() {
 396            let new_text: Arc<str> = new_text.into();
 397            let original_indent_column = original_indent_columns.get(ix).copied().unwrap_or(0);
 398            cursor.seek(&range.start, Bias::Right, &());
 399            if cursor.item().is_none() && range.start == *cursor.start() {
 400                cursor.prev(&());
 401            }
 402            let start_excerpt = cursor.item().expect("start offset out of bounds");
 403            let start_overshoot = range.start - cursor.start();
 404            let buffer_start = start_excerpt
 405                .range
 406                .context
 407                .start
 408                .to_offset(&start_excerpt.buffer)
 409                + start_overshoot;
 410
 411            cursor.seek(&range.end, Bias::Right, &());
 412            if cursor.item().is_none() && range.end == *cursor.start() {
 413                cursor.prev(&());
 414            }
 415            let end_excerpt = cursor.item().expect("end offset out of bounds");
 416            let end_overshoot = range.end - cursor.start();
 417            let buffer_end = end_excerpt
 418                .range
 419                .context
 420                .start
 421                .to_offset(&end_excerpt.buffer)
 422                + end_overshoot;
 423
 424            if start_excerpt.id == end_excerpt.id {
 425                buffer_edits
 426                    .entry(start_excerpt.buffer_id)
 427                    .or_insert(Vec::new())
 428                    .push(BufferEdit {
 429                        range: buffer_start..buffer_end,
 430                        new_text,
 431                        is_insertion: true,
 432                        original_indent_column,
 433                    });
 434            } else {
 435                let start_excerpt_range = buffer_start
 436                    ..start_excerpt
 437                        .range
 438                        .context
 439                        .end
 440                        .to_offset(&start_excerpt.buffer);
 441                let end_excerpt_range = end_excerpt
 442                    .range
 443                    .context
 444                    .start
 445                    .to_offset(&end_excerpt.buffer)
 446                    ..buffer_end;
 447                buffer_edits
 448                    .entry(start_excerpt.buffer_id)
 449                    .or_insert(Vec::new())
 450                    .push(BufferEdit {
 451                        range: start_excerpt_range,
 452                        new_text: new_text.clone(),
 453                        is_insertion: true,
 454                        original_indent_column,
 455                    });
 456                buffer_edits
 457                    .entry(end_excerpt.buffer_id)
 458                    .or_insert(Vec::new())
 459                    .push(BufferEdit {
 460                        range: end_excerpt_range,
 461                        new_text: new_text.clone(),
 462                        is_insertion: false,
 463                        original_indent_column,
 464                    });
 465
 466                cursor.seek(&range.start, Bias::Right, &());
 467                cursor.next(&());
 468                while let Some(excerpt) = cursor.item() {
 469                    if excerpt.id == end_excerpt.id {
 470                        break;
 471                    }
 472                    buffer_edits
 473                        .entry(excerpt.buffer_id)
 474                        .or_insert(Vec::new())
 475                        .push(BufferEdit {
 476                            range: excerpt.range.context.to_offset(&excerpt.buffer),
 477                            new_text: new_text.clone(),
 478                            is_insertion: false,
 479                            original_indent_column,
 480                        });
 481                    cursor.next(&());
 482                }
 483            }
 484        }
 485
 486        for (buffer_id, mut edits) in buffer_edits {
 487            edits.sort_unstable_by_key(|edit| edit.range.start);
 488            self.buffers.borrow()[&buffer_id]
 489                .buffer
 490                .update(cx, |buffer, cx| {
 491                    let mut edits = edits.into_iter().peekable();
 492                    let mut insertions = Vec::new();
 493                    let mut original_indent_columns = Vec::new();
 494                    let mut deletions = Vec::new();
 495                    let empty_str: Arc<str> = "".into();
 496                    while let Some(BufferEdit {
 497                        mut range,
 498                        new_text,
 499                        mut is_insertion,
 500                        original_indent_column,
 501                    }) = edits.next()
 502                    {
 503                        while let Some(BufferEdit {
 504                            range: next_range,
 505                            is_insertion: next_is_insertion,
 506                            ..
 507                        }) = edits.peek()
 508                        {
 509                            if range.end >= next_range.start {
 510                                range.end = cmp::max(next_range.end, range.end);
 511                                is_insertion |= *next_is_insertion;
 512                                edits.next();
 513                            } else {
 514                                break;
 515                            }
 516                        }
 517
 518                        if is_insertion {
 519                            original_indent_columns.push(original_indent_column);
 520                            insertions.push((
 521                                buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 522                                new_text.clone(),
 523                            ));
 524                        } else if !range.is_empty() {
 525                            deletions.push((
 526                                buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 527                                empty_str.clone(),
 528                            ));
 529                        }
 530                    }
 531
 532                    let deletion_autoindent_mode =
 533                        if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
 534                            Some(AutoindentMode::Block {
 535                                original_indent_columns: Default::default(),
 536                            })
 537                        } else {
 538                            None
 539                        };
 540                    let insertion_autoindent_mode =
 541                        if let Some(AutoindentMode::Block { .. }) = autoindent_mode {
 542                            Some(AutoindentMode::Block {
 543                                original_indent_columns,
 544                            })
 545                        } else {
 546                            None
 547                        };
 548
 549                    buffer.edit(deletions, deletion_autoindent_mode, cx);
 550                    buffer.edit(insertions, insertion_autoindent_mode, cx);
 551                })
 552        }
 553    }
 554
 555    pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 556        self.start_transaction_at(Instant::now(), cx)
 557    }
 558
 559    pub(crate) fn start_transaction_at(
 560        &mut self,
 561        now: Instant,
 562        cx: &mut ModelContext<Self>,
 563    ) -> Option<TransactionId> {
 564        if let Some(buffer) = self.as_singleton() {
 565            return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 566        }
 567
 568        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 569            buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 570        }
 571        self.history.start_transaction(now)
 572    }
 573
 574    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 575        self.end_transaction_at(Instant::now(), cx)
 576    }
 577
 578    pub(crate) fn end_transaction_at(
 579        &mut self,
 580        now: Instant,
 581        cx: &mut ModelContext<Self>,
 582    ) -> Option<TransactionId> {
 583        if let Some(buffer) = self.as_singleton() {
 584            return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
 585        }
 586
 587        let mut buffer_transactions = HashMap::default();
 588        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 589            if let Some(transaction_id) =
 590                buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 591            {
 592                buffer_transactions.insert(buffer.id(), transaction_id);
 593            }
 594        }
 595
 596        if self.history.end_transaction(now, buffer_transactions) {
 597            let transaction_id = self.history.group().unwrap();
 598            Some(transaction_id)
 599        } else {
 600            None
 601        }
 602    }
 603
 604    pub fn finalize_last_transaction(&mut self, cx: &mut ModelContext<Self>) {
 605        self.history.finalize_last_transaction();
 606        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 607            buffer.update(cx, |buffer, _| {
 608                buffer.finalize_last_transaction();
 609            });
 610        }
 611    }
 612
 613    pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T)
 614    where
 615        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
 616    {
 617        self.history
 618            .push_transaction(buffer_transactions, Instant::now());
 619        self.history.finalize_last_transaction();
 620    }
 621
 622    pub fn group_until_transaction(
 623        &mut self,
 624        transaction_id: TransactionId,
 625        cx: &mut ModelContext<Self>,
 626    ) {
 627        if let Some(buffer) = self.as_singleton() {
 628            buffer.update(cx, |buffer, _| {
 629                buffer.group_until_transaction(transaction_id)
 630            });
 631        } else {
 632            self.history.group_until(transaction_id);
 633        }
 634    }
 635
 636    pub fn set_active_selections(
 637        &mut self,
 638        selections: &[Selection<Anchor>],
 639        line_mode: bool,
 640        cursor_shape: CursorShape,
 641        cx: &mut ModelContext<Self>,
 642    ) {
 643        let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
 644            Default::default();
 645        let snapshot = self.read(cx);
 646        let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
 647        for selection in selections {
 648            let start_locator = snapshot.excerpt_locator_for_id(selection.start.excerpt_id);
 649            let end_locator = snapshot.excerpt_locator_for_id(selection.end.excerpt_id);
 650
 651            cursor.seek(&Some(start_locator), Bias::Left, &());
 652            while let Some(excerpt) = cursor.item() {
 653                if excerpt.locator > *end_locator {
 654                    break;
 655                }
 656
 657                let mut start = excerpt.range.context.start;
 658                let mut end = excerpt.range.context.end;
 659                if excerpt.id == selection.start.excerpt_id {
 660                    start = selection.start.text_anchor;
 661                }
 662                if excerpt.id == selection.end.excerpt_id {
 663                    end = selection.end.text_anchor;
 664                }
 665                selections_by_buffer
 666                    .entry(excerpt.buffer_id)
 667                    .or_default()
 668                    .push(Selection {
 669                        id: selection.id,
 670                        start,
 671                        end,
 672                        reversed: selection.reversed,
 673                        goal: selection.goal,
 674                    });
 675
 676                cursor.next(&());
 677            }
 678        }
 679
 680        for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
 681            if !selections_by_buffer.contains_key(buffer_id) {
 682                buffer_state
 683                    .buffer
 684                    .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 685            }
 686        }
 687
 688        for (buffer_id, mut selections) in selections_by_buffer {
 689            self.buffers.borrow()[&buffer_id]
 690                .buffer
 691                .update(cx, |buffer, cx| {
 692                    selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer));
 693                    let mut selections = selections.into_iter().peekable();
 694                    let merged_selections = Arc::from_iter(iter::from_fn(|| {
 695                        let mut selection = selections.next()?;
 696                        while let Some(next_selection) = selections.peek() {
 697                            if selection.end.cmp(&next_selection.start, buffer).is_ge() {
 698                                let next_selection = selections.next().unwrap();
 699                                if next_selection.end.cmp(&selection.end, buffer).is_ge() {
 700                                    selection.end = next_selection.end;
 701                                }
 702                            } else {
 703                                break;
 704                            }
 705                        }
 706                        Some(selection)
 707                    }));
 708                    buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx);
 709                });
 710        }
 711    }
 712
 713    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 714        for buffer in self.buffers.borrow().values() {
 715            buffer
 716                .buffer
 717                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 718        }
 719    }
 720
 721    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 722        if let Some(buffer) = self.as_singleton() {
 723            return buffer.update(cx, |buffer, cx| buffer.undo(cx));
 724        }
 725
 726        while let Some(transaction) = self.history.pop_undo() {
 727            let mut undone = false;
 728            for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
 729                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
 730                    undone |= buffer.update(cx, |buffer, cx| {
 731                        let undo_to = *buffer_transaction_id;
 732                        if let Some(entry) = buffer.peek_undo_stack() {
 733                            *buffer_transaction_id = entry.transaction_id();
 734                        }
 735                        buffer.undo_to_transaction(undo_to, cx)
 736                    });
 737                }
 738            }
 739
 740            if undone {
 741                return Some(transaction.id);
 742            }
 743        }
 744
 745        None
 746    }
 747
 748    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 749        if let Some(buffer) = self.as_singleton() {
 750            return buffer.update(cx, |buffer, cx| buffer.redo(cx));
 751        }
 752
 753        while let Some(transaction) = self.history.pop_redo() {
 754            let mut redone = false;
 755            for (buffer_id, buffer_transaction_id) in &mut transaction.buffer_transactions {
 756                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(buffer_id) {
 757                    redone |= buffer.update(cx, |buffer, cx| {
 758                        let redo_to = *buffer_transaction_id;
 759                        if let Some(entry) = buffer.peek_redo_stack() {
 760                            *buffer_transaction_id = entry.transaction_id();
 761                        }
 762                        buffer.redo_to_transaction(redo_to, cx)
 763                    });
 764                }
 765            }
 766
 767            if redone {
 768                return Some(transaction.id);
 769            }
 770        }
 771
 772        None
 773    }
 774
 775    pub fn stream_excerpts_with_context_lines(
 776        &mut self,
 777        excerpts: Vec<(ModelHandle<Buffer>, Vec<Range<text::Anchor>>)>,
 778        context_line_count: u32,
 779        cx: &mut ModelContext<Self>,
 780    ) -> (Task<()>, mpsc::Receiver<Range<Anchor>>) {
 781        let (mut tx, rx) = mpsc::channel(256);
 782        let task = cx.spawn(|this, mut cx| async move {
 783            for (buffer, ranges) in excerpts {
 784                let buffer_id = buffer.id();
 785                let buffer_snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
 786
 787                let mut excerpt_ranges = Vec::new();
 788                let mut range_counts = Vec::new();
 789                cx.background()
 790                    .scoped(|scope| {
 791                        scope.spawn(async {
 792                            let (ranges, counts) =
 793                                build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
 794                            excerpt_ranges = ranges;
 795                            range_counts = counts;
 796                        });
 797                    })
 798                    .await;
 799
 800                let mut ranges = ranges.into_iter();
 801                let mut range_counts = range_counts.into_iter();
 802                for excerpt_ranges in excerpt_ranges.chunks(100) {
 803                    let excerpt_ids = this.update(&mut cx, |this, cx| {
 804                        this.push_excerpts(buffer.clone(), excerpt_ranges.iter().cloned(), cx)
 805                    });
 806
 807                    for (excerpt_id, range_count) in
 808                        excerpt_ids.into_iter().zip(range_counts.by_ref())
 809                    {
 810                        for range in ranges.by_ref().take(range_count) {
 811                            let start = Anchor {
 812                                buffer_id: Some(buffer_id),
 813                                excerpt_id: excerpt_id.clone(),
 814                                text_anchor: range.start,
 815                            };
 816                            let end = Anchor {
 817                                buffer_id: Some(buffer_id),
 818                                excerpt_id: excerpt_id.clone(),
 819                                text_anchor: range.end,
 820                            };
 821                            if tx.send(start..end).await.is_err() {
 822                                break;
 823                            }
 824                        }
 825                    }
 826                }
 827            }
 828        });
 829        (task, rx)
 830    }
 831
 832    pub fn push_excerpts<O>(
 833        &mut self,
 834        buffer: ModelHandle<Buffer>,
 835        ranges: impl IntoIterator<Item = ExcerptRange<O>>,
 836        cx: &mut ModelContext<Self>,
 837    ) -> Vec<ExcerptId>
 838    where
 839        O: text::ToOffset,
 840    {
 841        self.insert_excerpts_after(ExcerptId::max(), buffer, ranges, cx)
 842    }
 843
 844    pub fn push_excerpts_with_context_lines<O>(
 845        &mut self,
 846        buffer: ModelHandle<Buffer>,
 847        ranges: Vec<Range<O>>,
 848        context_line_count: u32,
 849        cx: &mut ModelContext<Self>,
 850    ) -> Vec<Range<Anchor>>
 851    where
 852        O: text::ToPoint + text::ToOffset,
 853    {
 854        let buffer_id = buffer.id();
 855        let buffer_snapshot = buffer.read(cx).snapshot();
 856        let (excerpt_ranges, range_counts) =
 857            build_excerpt_ranges(&buffer_snapshot, &ranges, context_line_count);
 858
 859        let excerpt_ids = self.push_excerpts(buffer, excerpt_ranges, cx);
 860
 861        let mut anchor_ranges = Vec::new();
 862        let mut ranges = ranges.into_iter();
 863        for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.into_iter()) {
 864            anchor_ranges.extend(ranges.by_ref().take(range_count).map(|range| {
 865                let start = Anchor {
 866                    buffer_id: Some(buffer_id),
 867                    excerpt_id: excerpt_id.clone(),
 868                    text_anchor: buffer_snapshot.anchor_after(range.start),
 869                };
 870                let end = Anchor {
 871                    buffer_id: Some(buffer_id),
 872                    excerpt_id: excerpt_id.clone(),
 873                    text_anchor: buffer_snapshot.anchor_after(range.end),
 874                };
 875                start..end
 876            }))
 877        }
 878        anchor_ranges
 879    }
 880
 881    pub fn insert_excerpts_after<O>(
 882        &mut self,
 883        prev_excerpt_id: ExcerptId,
 884        buffer: ModelHandle<Buffer>,
 885        ranges: impl IntoIterator<Item = ExcerptRange<O>>,
 886        cx: &mut ModelContext<Self>,
 887    ) -> Vec<ExcerptId>
 888    where
 889        O: text::ToOffset,
 890    {
 891        let mut ids = Vec::new();
 892        let mut next_excerpt_id = self.next_excerpt_id;
 893        self.insert_excerpts_with_ids_after(
 894            prev_excerpt_id,
 895            buffer,
 896            ranges.into_iter().map(|range| {
 897                let id = ExcerptId(post_inc(&mut next_excerpt_id));
 898                ids.push(id);
 899                (id, range)
 900            }),
 901            cx,
 902        );
 903        ids
 904    }
 905
 906    pub fn insert_excerpts_with_ids_after<O>(
 907        &mut self,
 908        prev_excerpt_id: ExcerptId,
 909        buffer: ModelHandle<Buffer>,
 910        ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
 911        cx: &mut ModelContext<Self>,
 912    ) where
 913        O: text::ToOffset,
 914    {
 915        assert_eq!(self.history.transaction_depth, 0);
 916        let mut ranges = ranges.into_iter().peekable();
 917        if ranges.peek().is_none() {
 918            return Default::default();
 919        }
 920
 921        self.sync(cx);
 922
 923        let buffer_id = buffer.id();
 924        let buffer_snapshot = buffer.read(cx).snapshot();
 925
 926        let mut buffers = self.buffers.borrow_mut();
 927        let buffer_state = buffers.entry(buffer_id).or_insert_with(|| BufferState {
 928            last_version: buffer_snapshot.version().clone(),
 929            last_parse_count: buffer_snapshot.parse_count(),
 930            last_selections_update_count: buffer_snapshot.selections_update_count(),
 931            last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
 932            last_file_update_count: buffer_snapshot.file_update_count(),
 933            last_git_diff_update_count: buffer_snapshot.git_diff_update_count(),
 934            excerpts: Default::default(),
 935            _subscriptions: [
 936                cx.observe(&buffer, |_, _, cx| cx.notify()),
 937                cx.subscribe(&buffer, Self::on_buffer_event),
 938            ],
 939            buffer: buffer.clone(),
 940        });
 941
 942        let mut snapshot = self.snapshot.borrow_mut();
 943
 944        let mut prev_locator = snapshot.excerpt_locator_for_id(prev_excerpt_id).clone();
 945        let mut new_excerpt_ids = mem::take(&mut snapshot.excerpt_ids);
 946        let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
 947        let mut new_excerpts = cursor.slice(&prev_locator, Bias::Right, &());
 948        prev_locator = cursor.start().unwrap_or(Locator::min_ref()).clone();
 949
 950        let edit_start = new_excerpts.summary().text.len;
 951        new_excerpts.update_last(
 952            |excerpt| {
 953                excerpt.has_trailing_newline = true;
 954            },
 955            &(),
 956        );
 957
 958        let next_locator = if let Some(excerpt) = cursor.item() {
 959            excerpt.locator.clone()
 960        } else {
 961            Locator::max()
 962        };
 963
 964        let mut excerpts = Vec::new();
 965        while let Some((id, range)) = ranges.next() {
 966            let locator = Locator::between(&prev_locator, &next_locator);
 967            if let Err(ix) = buffer_state.excerpts.binary_search(&locator) {
 968                buffer_state.excerpts.insert(ix, locator.clone());
 969            }
 970            let range = ExcerptRange {
 971                context: buffer_snapshot.anchor_before(&range.context.start)
 972                    ..buffer_snapshot.anchor_after(&range.context.end),
 973                primary: range.primary.map(|primary| {
 974                    buffer_snapshot.anchor_before(&primary.start)
 975                        ..buffer_snapshot.anchor_after(&primary.end)
 976                }),
 977            };
 978            if id.0 >= self.next_excerpt_id {
 979                self.next_excerpt_id = id.0 + 1;
 980            }
 981            excerpts.push((id, range.clone()));
 982            let excerpt = Excerpt::new(
 983                id,
 984                locator.clone(),
 985                buffer_id,
 986                buffer_snapshot.clone(),
 987                range,
 988                ranges.peek().is_some() || cursor.item().is_some(),
 989            );
 990            new_excerpts.push(excerpt, &());
 991            prev_locator = locator.clone();
 992            new_excerpt_ids.push(ExcerptIdMapping { id, locator }, &());
 993        }
 994
 995        let edit_end = new_excerpts.summary().text.len;
 996
 997        let suffix = cursor.suffix(&());
 998        let changed_trailing_excerpt = suffix.is_empty();
 999        new_excerpts.push_tree(suffix, &());
1000        drop(cursor);
1001        snapshot.excerpts = new_excerpts;
1002        snapshot.excerpt_ids = new_excerpt_ids;
1003        if changed_trailing_excerpt {
1004            snapshot.trailing_excerpt_update_count += 1;
1005        }
1006
1007        self.subscriptions.publish_mut([Edit {
1008            old: edit_start..edit_start,
1009            new: edit_start..edit_end,
1010        }]);
1011        cx.emit(Event::Edited);
1012        cx.emit(Event::ExcerptsAdded {
1013            buffer,
1014            predecessor: prev_excerpt_id,
1015            excerpts,
1016        });
1017        cx.notify();
1018    }
1019
1020    pub fn clear(&mut self, cx: &mut ModelContext<Self>) {
1021        self.sync(cx);
1022        let ids = self.excerpt_ids();
1023        self.buffers.borrow_mut().clear();
1024        let mut snapshot = self.snapshot.borrow_mut();
1025        let prev_len = snapshot.len();
1026        snapshot.excerpts = Default::default();
1027        snapshot.trailing_excerpt_update_count += 1;
1028        snapshot.is_dirty = false;
1029        snapshot.has_conflict = false;
1030
1031        self.subscriptions.publish_mut([Edit {
1032            old: 0..prev_len,
1033            new: 0..0,
1034        }]);
1035        cx.emit(Event::Edited);
1036        cx.emit(Event::ExcerptsRemoved { ids });
1037        cx.notify();
1038    }
1039
1040    pub fn excerpts_for_buffer(
1041        &self,
1042        buffer: &ModelHandle<Buffer>,
1043        cx: &AppContext,
1044    ) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
1045        let mut excerpts = Vec::new();
1046        let snapshot = self.read(cx);
1047        let buffers = self.buffers.borrow();
1048        let mut cursor = snapshot.excerpts.cursor::<Option<&Locator>>();
1049        for locator in buffers
1050            .get(&buffer.id())
1051            .map(|state| &state.excerpts)
1052            .into_iter()
1053            .flatten()
1054        {
1055            cursor.seek_forward(&Some(locator), Bias::Left, &());
1056            if let Some(excerpt) = cursor.item() {
1057                if excerpt.locator == *locator {
1058                    excerpts.push((excerpt.id.clone(), excerpt.range.clone()));
1059                }
1060            }
1061        }
1062
1063        excerpts
1064    }
1065
1066    pub fn excerpt_ids(&self) -> Vec<ExcerptId> {
1067        self.snapshot
1068            .borrow()
1069            .excerpts
1070            .iter()
1071            .map(|entry| entry.id)
1072            .collect()
1073    }
1074
1075    pub fn excerpt_containing(
1076        &self,
1077        position: impl ToOffset,
1078        cx: &AppContext,
1079    ) -> Option<(ExcerptId, ModelHandle<Buffer>, Range<text::Anchor>)> {
1080        let snapshot = self.read(cx);
1081        let position = position.to_offset(&snapshot);
1082
1083        let mut cursor = snapshot.excerpts.cursor::<usize>();
1084        cursor.seek(&position, Bias::Right, &());
1085        cursor
1086            .item()
1087            .or_else(|| snapshot.excerpts.last())
1088            .map(|excerpt| {
1089                (
1090                    excerpt.id.clone(),
1091                    self.buffers
1092                        .borrow()
1093                        .get(&excerpt.buffer_id)
1094                        .unwrap()
1095                        .buffer
1096                        .clone(),
1097                    excerpt.range.context.clone(),
1098                )
1099            })
1100    }
1101
1102    // If point is at the end of the buffer, the last excerpt is returned
1103    pub fn point_to_buffer_offset<T: ToOffset>(
1104        &self,
1105        point: T,
1106        cx: &AppContext,
1107    ) -> Option<(ModelHandle<Buffer>, usize)> {
1108        let snapshot = self.read(cx);
1109        let offset = point.to_offset(&snapshot);
1110        let mut cursor = snapshot.excerpts.cursor::<usize>();
1111        cursor.seek(&offset, Bias::Right, &());
1112        if cursor.item().is_none() {
1113            cursor.prev(&());
1114        }
1115
1116        cursor.item().map(|excerpt| {
1117            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1118            let buffer_point = excerpt_start + offset - *cursor.start();
1119            let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1120
1121            (buffer, buffer_point)
1122        })
1123    }
1124
1125    pub fn range_to_buffer_ranges<T: ToOffset>(
1126        &self,
1127        range: Range<T>,
1128        cx: &AppContext,
1129    ) -> Vec<(ModelHandle<Buffer>, Range<usize>)> {
1130        let snapshot = self.read(cx);
1131        let start = range.start.to_offset(&snapshot);
1132        let end = range.end.to_offset(&snapshot);
1133
1134        let mut result = Vec::new();
1135        let mut cursor = snapshot.excerpts.cursor::<usize>();
1136        cursor.seek(&start, Bias::Right, &());
1137        while let Some(excerpt) = cursor.item() {
1138            if *cursor.start() > end {
1139                break;
1140            }
1141
1142            let mut end_before_newline = cursor.end(&());
1143            if excerpt.has_trailing_newline {
1144                end_before_newline -= 1;
1145            }
1146            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1147            let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
1148            let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
1149            let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
1150            result.push((buffer, start..end));
1151            cursor.next(&());
1152        }
1153
1154        result
1155    }
1156
1157    pub fn remove_excerpts(
1158        &mut self,
1159        excerpt_ids: impl IntoIterator<Item = ExcerptId>,
1160        cx: &mut ModelContext<Self>,
1161    ) {
1162        self.sync(cx);
1163        let ids = excerpt_ids.into_iter().collect::<Vec<_>>();
1164
1165        let mut buffers = self.buffers.borrow_mut();
1166        let mut snapshot = self.snapshot.borrow_mut();
1167        let mut new_excerpts = SumTree::new();
1168        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1169        let mut edits = Vec::new();
1170        let mut excerpt_ids = ids.iter().copied().peekable();
1171
1172        while let Some(excerpt_id) = excerpt_ids.next() {
1173            // Seek to the next excerpt to remove, preserving any preceding excerpts.
1174            let locator = snapshot.excerpt_locator_for_id(excerpt_id);
1175            new_excerpts.push_tree(cursor.slice(&Some(locator), Bias::Left, &()), &());
1176
1177            if let Some(mut excerpt) = cursor.item() {
1178                if excerpt.id != excerpt_id {
1179                    continue;
1180                }
1181                let mut old_start = cursor.start().1;
1182
1183                // Skip over the removed excerpt.
1184                'remove_excerpts: loop {
1185                    if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
1186                        buffer_state.excerpts.retain(|l| l != &excerpt.locator);
1187                        if buffer_state.excerpts.is_empty() {
1188                            buffers.remove(&excerpt.buffer_id);
1189                        }
1190                    }
1191                    cursor.next(&());
1192
1193                    // Skip over any subsequent excerpts that are also removed.
1194                    while let Some(&next_excerpt_id) = excerpt_ids.peek() {
1195                        let next_locator = snapshot.excerpt_locator_for_id(next_excerpt_id);
1196                        if let Some(next_excerpt) = cursor.item() {
1197                            if next_excerpt.locator == *next_locator {
1198                                excerpt_ids.next();
1199                                excerpt = next_excerpt;
1200                                continue 'remove_excerpts;
1201                            }
1202                        }
1203                        break;
1204                    }
1205
1206                    break;
1207                }
1208
1209                // When removing the last excerpt, remove the trailing newline from
1210                // the previous excerpt.
1211                if cursor.item().is_none() && old_start > 0 {
1212                    old_start -= 1;
1213                    new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
1214                }
1215
1216                // Push an edit for the removal of this run of excerpts.
1217                let old_end = cursor.start().1;
1218                let new_start = new_excerpts.summary().text.len;
1219                edits.push(Edit {
1220                    old: old_start..old_end,
1221                    new: new_start..new_start,
1222                });
1223            }
1224        }
1225        let suffix = cursor.suffix(&());
1226        let changed_trailing_excerpt = suffix.is_empty();
1227        new_excerpts.push_tree(suffix, &());
1228        drop(cursor);
1229        snapshot.excerpts = new_excerpts;
1230
1231        if changed_trailing_excerpt {
1232            snapshot.trailing_excerpt_update_count += 1;
1233        }
1234
1235        self.subscriptions.publish_mut(edits);
1236        cx.emit(Event::Edited);
1237        cx.emit(Event::ExcerptsRemoved { ids });
1238        cx.notify();
1239    }
1240
1241    pub fn text_anchor_for_position<T: ToOffset>(
1242        &self,
1243        position: T,
1244        cx: &AppContext,
1245    ) -> Option<(ModelHandle<Buffer>, language::Anchor)> {
1246        let snapshot = self.read(cx);
1247        let anchor = snapshot.anchor_before(position);
1248        let buffer = self
1249            .buffers
1250            .borrow()
1251            .get(&anchor.buffer_id?)?
1252            .buffer
1253            .clone();
1254        Some((buffer, anchor.text_anchor))
1255    }
1256
1257    fn on_buffer_event(
1258        &mut self,
1259        _: ModelHandle<Buffer>,
1260        event: &language::Event,
1261        cx: &mut ModelContext<Self>,
1262    ) {
1263        cx.emit(match event {
1264            language::Event::Edited => Event::Edited,
1265            language::Event::DirtyChanged => Event::DirtyChanged,
1266            language::Event::Saved => Event::Saved,
1267            language::Event::FileHandleChanged => Event::FileHandleChanged,
1268            language::Event::Reloaded => Event::Reloaded,
1269            language::Event::Reparsed => Event::Reparsed,
1270            language::Event::DiagnosticsUpdated => Event::DiagnosticsUpdated,
1271            language::Event::Closed => Event::Closed,
1272
1273            //
1274            language::Event::Operation(_) => return,
1275        });
1276    }
1277
1278    pub fn all_buffers(&self) -> HashSet<ModelHandle<Buffer>> {
1279        self.buffers
1280            .borrow()
1281            .values()
1282            .map(|state| state.buffer.clone())
1283            .collect()
1284    }
1285
1286    pub fn buffer(&self, buffer_id: usize) -> Option<ModelHandle<Buffer>> {
1287        self.buffers
1288            .borrow()
1289            .get(&buffer_id)
1290            .map(|state| state.buffer.clone())
1291    }
1292
1293    pub fn is_completion_trigger<T>(&self, position: T, text: &str, cx: &AppContext) -> bool
1294    where
1295        T: ToOffset,
1296    {
1297        let mut chars = text.chars();
1298        let char = if let Some(char) = chars.next() {
1299            char
1300        } else {
1301            return false;
1302        };
1303        if chars.next().is_some() {
1304            return false;
1305        }
1306
1307        if char.is_alphanumeric() || char == '_' {
1308            return true;
1309        }
1310
1311        let snapshot = self.snapshot(cx);
1312        let anchor = snapshot.anchor_before(position);
1313        anchor
1314            .buffer_id
1315            .and_then(|buffer_id| {
1316                let buffer = self.buffers.borrow().get(&buffer_id)?.buffer.clone();
1317                Some(
1318                    buffer
1319                        .read(cx)
1320                        .completion_triggers()
1321                        .iter()
1322                        .any(|string| string == text),
1323                )
1324            })
1325            .unwrap_or(false)
1326    }
1327
1328    pub fn language_at<'a, T: ToOffset>(
1329        &self,
1330        point: T,
1331        cx: &'a AppContext,
1332    ) -> Option<Arc<Language>> {
1333        self.point_to_buffer_offset(point, cx)
1334            .and_then(|(buffer, offset)| buffer.read(cx).language_at(offset))
1335    }
1336
1337    pub fn for_each_buffer(&self, mut f: impl FnMut(&ModelHandle<Buffer>)) {
1338        self.buffers
1339            .borrow()
1340            .values()
1341            .for_each(|state| f(&state.buffer))
1342    }
1343
1344    pub fn title<'a>(&'a self, cx: &'a AppContext) -> Cow<'a, str> {
1345        if let Some(title) = self.title.as_ref() {
1346            return title.into();
1347        }
1348
1349        if let Some(buffer) = self.as_singleton() {
1350            if let Some(file) = buffer.read(cx).file() {
1351                return file.file_name(cx).to_string_lossy();
1352            }
1353        }
1354
1355        "untitled".into()
1356    }
1357
1358    #[cfg(test)]
1359    pub fn is_parsing(&self, cx: &AppContext) -> bool {
1360        self.as_singleton().unwrap().read(cx).is_parsing()
1361    }
1362
1363    fn sync(&self, cx: &AppContext) {
1364        let mut snapshot = self.snapshot.borrow_mut();
1365        let mut excerpts_to_edit = Vec::new();
1366        let mut reparsed = false;
1367        let mut diagnostics_updated = false;
1368        let mut git_diff_updated = false;
1369        let mut is_dirty = false;
1370        let mut has_conflict = false;
1371        let mut edited = false;
1372        let mut buffers = self.buffers.borrow_mut();
1373        for buffer_state in buffers.values_mut() {
1374            let buffer = buffer_state.buffer.read(cx);
1375            let version = buffer.version();
1376            let parse_count = buffer.parse_count();
1377            let selections_update_count = buffer.selections_update_count();
1378            let diagnostics_update_count = buffer.diagnostics_update_count();
1379            let file_update_count = buffer.file_update_count();
1380            let git_diff_update_count = buffer.git_diff_update_count();
1381
1382            let buffer_edited = version.changed_since(&buffer_state.last_version);
1383            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
1384            let buffer_selections_updated =
1385                selections_update_count > buffer_state.last_selections_update_count;
1386            let buffer_diagnostics_updated =
1387                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
1388            let buffer_file_updated = file_update_count > buffer_state.last_file_update_count;
1389            let buffer_git_diff_updated =
1390                git_diff_update_count > buffer_state.last_git_diff_update_count;
1391            if buffer_edited
1392                || buffer_reparsed
1393                || buffer_selections_updated
1394                || buffer_diagnostics_updated
1395                || buffer_file_updated
1396                || buffer_git_diff_updated
1397            {
1398                buffer_state.last_version = version;
1399                buffer_state.last_parse_count = parse_count;
1400                buffer_state.last_selections_update_count = selections_update_count;
1401                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
1402                buffer_state.last_file_update_count = file_update_count;
1403                buffer_state.last_git_diff_update_count = git_diff_update_count;
1404                excerpts_to_edit.extend(
1405                    buffer_state
1406                        .excerpts
1407                        .iter()
1408                        .map(|locator| (locator, buffer_state.buffer.clone(), buffer_edited)),
1409                );
1410            }
1411
1412            edited |= buffer_edited;
1413            reparsed |= buffer_reparsed;
1414            diagnostics_updated |= buffer_diagnostics_updated;
1415            git_diff_updated |= buffer_git_diff_updated;
1416            is_dirty |= buffer.is_dirty();
1417            has_conflict |= buffer.has_conflict();
1418        }
1419        if edited {
1420            snapshot.edit_count += 1;
1421        }
1422        if reparsed {
1423            snapshot.parse_count += 1;
1424        }
1425        if diagnostics_updated {
1426            snapshot.diagnostics_update_count += 1;
1427        }
1428        if git_diff_updated {
1429            snapshot.git_diff_update_count += 1;
1430        }
1431        snapshot.is_dirty = is_dirty;
1432        snapshot.has_conflict = has_conflict;
1433
1434        excerpts_to_edit.sort_unstable_by_key(|(locator, _, _)| *locator);
1435
1436        let mut edits = Vec::new();
1437        let mut new_excerpts = SumTree::new();
1438        let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
1439
1440        for (locator, buffer, buffer_edited) in excerpts_to_edit {
1441            new_excerpts.push_tree(cursor.slice(&Some(locator), Bias::Left, &()), &());
1442            let old_excerpt = cursor.item().unwrap();
1443            let buffer_id = buffer.id();
1444            let buffer = buffer.read(cx);
1445
1446            let mut new_excerpt;
1447            if buffer_edited {
1448                edits.extend(
1449                    buffer
1450                        .edits_since_in_range::<usize>(
1451                            old_excerpt.buffer.version(),
1452                            old_excerpt.range.context.clone(),
1453                        )
1454                        .map(|mut edit| {
1455                            let excerpt_old_start = cursor.start().1;
1456                            let excerpt_new_start = new_excerpts.summary().text.len;
1457                            edit.old.start += excerpt_old_start;
1458                            edit.old.end += excerpt_old_start;
1459                            edit.new.start += excerpt_new_start;
1460                            edit.new.end += excerpt_new_start;
1461                            edit
1462                        }),
1463                );
1464
1465                new_excerpt = Excerpt::new(
1466                    old_excerpt.id,
1467                    locator.clone(),
1468                    buffer_id,
1469                    buffer.snapshot(),
1470                    old_excerpt.range.clone(),
1471                    old_excerpt.has_trailing_newline,
1472                );
1473            } else {
1474                new_excerpt = old_excerpt.clone();
1475                new_excerpt.buffer = buffer.snapshot();
1476            }
1477
1478            new_excerpts.push(new_excerpt, &());
1479            cursor.next(&());
1480        }
1481        new_excerpts.push_tree(cursor.suffix(&()), &());
1482
1483        drop(cursor);
1484        snapshot.excerpts = new_excerpts;
1485
1486        self.subscriptions.publish(edits);
1487    }
1488}
1489
1490#[cfg(any(test, feature = "test-support"))]
1491impl MultiBuffer {
1492    pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
1493        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
1494        cx.add_model(|cx| Self::singleton(buffer, cx))
1495    }
1496
1497    pub fn build_random(
1498        rng: &mut impl rand::Rng,
1499        cx: &mut gpui::MutableAppContext,
1500    ) -> ModelHandle<Self> {
1501        cx.add_model(|cx| {
1502            let mut multibuffer = MultiBuffer::new(0);
1503            let mutation_count = rng.gen_range(1..=5);
1504            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1505            multibuffer
1506        })
1507    }
1508
1509    pub fn randomly_edit(
1510        &mut self,
1511        rng: &mut impl rand::Rng,
1512        edit_count: usize,
1513        cx: &mut ModelContext<Self>,
1514    ) {
1515        use util::RandomCharIter;
1516
1517        let snapshot = self.read(cx);
1518        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1519        let mut last_end = None;
1520        for _ in 0..edit_count {
1521            if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1522                break;
1523            }
1524
1525            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1526            let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1527            let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1528            last_end = Some(end);
1529
1530            let mut range = start..end;
1531            if rng.gen_bool(0.2) {
1532                mem::swap(&mut range.start, &mut range.end);
1533            }
1534
1535            let new_text_len = rng.gen_range(0..10);
1536            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1537
1538            edits.push((range, new_text.into()));
1539        }
1540        log::info!("mutating multi-buffer with {:?}", edits);
1541        drop(snapshot);
1542
1543        self.edit(edits, None, cx);
1544    }
1545
1546    pub fn randomly_edit_excerpts(
1547        &mut self,
1548        rng: &mut impl rand::Rng,
1549        mutation_count: usize,
1550        cx: &mut ModelContext<Self>,
1551    ) {
1552        use rand::prelude::*;
1553        use std::env;
1554        use util::RandomCharIter;
1555
1556        let max_excerpts = env::var("MAX_EXCERPTS")
1557            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1558            .unwrap_or(5);
1559
1560        let mut buffers = Vec::new();
1561        for _ in 0..mutation_count {
1562            if rng.gen_bool(0.05) {
1563                log::info!("Clearing multi-buffer");
1564                self.clear(cx);
1565                continue;
1566            }
1567
1568            let excerpt_ids = self.excerpt_ids();
1569            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1570                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1571                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1572                    buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1573                    let buffer = buffers.last().unwrap();
1574                    log::info!(
1575                        "Creating new buffer {} with text: {:?}",
1576                        buffer.id(),
1577                        buffer.read(cx).text()
1578                    );
1579                    buffers.last().unwrap().clone()
1580                } else {
1581                    self.buffers
1582                        .borrow()
1583                        .values()
1584                        .choose(rng)
1585                        .unwrap()
1586                        .buffer
1587                        .clone()
1588                };
1589
1590                let buffer = buffer_handle.read(cx);
1591                let buffer_text = buffer.text();
1592                let ranges = (0..rng.gen_range(0..5))
1593                    .map(|_| {
1594                        let end_ix =
1595                            buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1596                        let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1597                        ExcerptRange {
1598                            context: start_ix..end_ix,
1599                            primary: None,
1600                        }
1601                    })
1602                    .collect::<Vec<_>>();
1603                log::info!(
1604                    "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1605                    buffer_handle.id(),
1606                    ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1607                    ranges
1608                        .iter()
1609                        .map(|r| &buffer_text[r.context.clone()])
1610                        .collect::<Vec<_>>()
1611                );
1612
1613                let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1614                log::info!("Inserted with ids: {:?}", excerpt_id);
1615            } else {
1616                let remove_count = rng.gen_range(1..=excerpt_ids.len());
1617                let mut excerpts_to_remove = excerpt_ids
1618                    .choose_multiple(rng, remove_count)
1619                    .cloned()
1620                    .collect::<Vec<_>>();
1621                let snapshot = self.snapshot.borrow();
1622                excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &*snapshot));
1623                drop(snapshot);
1624                log::info!("Removing excerpts {:?}", excerpts_to_remove);
1625                self.remove_excerpts(excerpts_to_remove, cx);
1626            }
1627        }
1628    }
1629
1630    pub fn randomly_mutate(
1631        &mut self,
1632        rng: &mut impl rand::Rng,
1633        mutation_count: usize,
1634        cx: &mut ModelContext<Self>,
1635    ) {
1636        use rand::prelude::*;
1637
1638        if rng.gen_bool(0.7) || self.singleton {
1639            let buffer = self
1640                .buffers
1641                .borrow()
1642                .values()
1643                .choose(rng)
1644                .map(|state| state.buffer.clone());
1645
1646            if let Some(buffer) = buffer {
1647                buffer.update(cx, |buffer, cx| {
1648                    if rng.gen() {
1649                        buffer.randomly_edit(rng, mutation_count, cx);
1650                    } else {
1651                        buffer.randomly_undo_redo(rng, cx);
1652                    }
1653                });
1654            } else {
1655                self.randomly_edit(rng, mutation_count, cx);
1656            }
1657        } else {
1658            self.randomly_edit_excerpts(rng, mutation_count, cx);
1659        }
1660
1661        self.check_invariants(cx);
1662    }
1663
1664    fn check_invariants(&self, cx: &mut ModelContext<Self>) {
1665        let snapshot = self.read(cx);
1666        let excerpts = snapshot.excerpts.items(&());
1667        let excerpt_ids = snapshot.excerpt_ids.items(&());
1668
1669        for (ix, excerpt) in excerpts.iter().enumerate() {
1670            if ix == 0 {
1671                if excerpt.locator <= Locator::min() {
1672                    panic!("invalid first excerpt locator {:?}", excerpt.locator);
1673                }
1674            } else {
1675                if excerpt.locator <= excerpts[ix - 1].locator {
1676                    panic!("excerpts are out-of-order: {:?}", excerpts);
1677                }
1678            }
1679        }
1680
1681        for (ix, entry) in excerpt_ids.iter().enumerate() {
1682            if ix == 0 {
1683                if entry.id.cmp(&ExcerptId::min(), &*snapshot).is_le() {
1684                    panic!("invalid first excerpt id {:?}", entry.id);
1685                }
1686            } else {
1687                if entry.id <= excerpt_ids[ix - 1].id {
1688                    panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
1689                }
1690            }
1691        }
1692    }
1693}
1694
1695impl Entity for MultiBuffer {
1696    type Event = Event;
1697}
1698
1699impl MultiBufferSnapshot {
1700    pub fn text(&self) -> String {
1701        self.chunks(0..self.len(), false)
1702            .map(|chunk| chunk.text)
1703            .collect()
1704    }
1705
1706    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1707        let mut offset = position.to_offset(self);
1708        let mut cursor = self.excerpts.cursor::<usize>();
1709        cursor.seek(&offset, Bias::Left, &());
1710        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1711            let end_before_footer = cursor.start() + excerpt.text_summary.len;
1712            let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1713            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1714            excerpt.buffer.reversed_chunks_in_range(start..end)
1715        });
1716        iter::from_fn(move || {
1717            if offset == *cursor.start() {
1718                cursor.prev(&());
1719                let excerpt = cursor.item()?;
1720                excerpt_chunks = Some(
1721                    excerpt
1722                        .buffer
1723                        .reversed_chunks_in_range(excerpt.range.context.clone()),
1724                );
1725            }
1726
1727            let excerpt = cursor.item().unwrap();
1728            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1729                offset -= 1;
1730                Some("\n")
1731            } else {
1732                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1733                offset -= chunk.len();
1734                Some(chunk)
1735            }
1736        })
1737        .flat_map(|c| c.chars().rev())
1738    }
1739
1740    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1741        let offset = position.to_offset(self);
1742        self.text_for_range(offset..self.len())
1743            .flat_map(|chunk| chunk.chars())
1744    }
1745
1746    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
1747        self.chunks(range, false).map(|chunk| chunk.text)
1748    }
1749
1750    pub fn is_line_blank(&self, row: u32) -> bool {
1751        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1752            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1753    }
1754
1755    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1756    where
1757        T: ToOffset,
1758    {
1759        let position = position.to_offset(self);
1760        position == self.clip_offset(position, Bias::Left)
1761            && self
1762                .bytes_in_range(position..self.len())
1763                .flatten()
1764                .copied()
1765                .take(needle.len())
1766                .eq(needle.bytes())
1767    }
1768
1769    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1770        let mut start = start.to_offset(self);
1771        let mut end = start;
1772        let mut next_chars = self.chars_at(start).peekable();
1773        let mut prev_chars = self.reversed_chars_at(start).peekable();
1774        let word_kind = cmp::max(
1775            prev_chars.peek().copied().map(char_kind),
1776            next_chars.peek().copied().map(char_kind),
1777        );
1778
1779        for ch in prev_chars {
1780            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1781                start -= ch.len_utf8();
1782            } else {
1783                break;
1784            }
1785        }
1786
1787        for ch in next_chars {
1788            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1789                end += ch.len_utf8();
1790            } else {
1791                break;
1792            }
1793        }
1794
1795        (start..end, word_kind)
1796    }
1797
1798    pub fn as_singleton(&self) -> Option<(&ExcerptId, usize, &BufferSnapshot)> {
1799        if self.singleton {
1800            self.excerpts
1801                .iter()
1802                .next()
1803                .map(|e| (&e.id, e.buffer_id, &e.buffer))
1804        } else {
1805            None
1806        }
1807    }
1808
1809    pub fn len(&self) -> usize {
1810        self.excerpts.summary().text.len
1811    }
1812
1813    pub fn is_empty(&self) -> bool {
1814        self.excerpts.summary().text.len == 0
1815    }
1816
1817    pub fn max_buffer_row(&self) -> u32 {
1818        self.excerpts.summary().max_buffer_row
1819    }
1820
1821    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1822        if let Some((_, _, buffer)) = self.as_singleton() {
1823            return buffer.clip_offset(offset, bias);
1824        }
1825
1826        let mut cursor = self.excerpts.cursor::<usize>();
1827        cursor.seek(&offset, Bias::Right, &());
1828        let overshoot = if let Some(excerpt) = cursor.item() {
1829            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1830            let buffer_offset = excerpt
1831                .buffer
1832                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1833            buffer_offset.saturating_sub(excerpt_start)
1834        } else {
1835            0
1836        };
1837        cursor.start() + overshoot
1838    }
1839
1840    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1841        if let Some((_, _, buffer)) = self.as_singleton() {
1842            return buffer.clip_point(point, bias);
1843        }
1844
1845        let mut cursor = self.excerpts.cursor::<Point>();
1846        cursor.seek(&point, Bias::Right, &());
1847        let overshoot = if let Some(excerpt) = cursor.item() {
1848            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1849            let buffer_point = excerpt
1850                .buffer
1851                .clip_point(excerpt_start + (point - cursor.start()), bias);
1852            buffer_point.saturating_sub(excerpt_start)
1853        } else {
1854            Point::zero()
1855        };
1856        *cursor.start() + overshoot
1857    }
1858
1859    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
1860        if let Some((_, _, buffer)) = self.as_singleton() {
1861            return buffer.clip_offset_utf16(offset, bias);
1862        }
1863
1864        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
1865        cursor.seek(&offset, Bias::Right, &());
1866        let overshoot = if let Some(excerpt) = cursor.item() {
1867            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1868            let buffer_offset = excerpt
1869                .buffer
1870                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
1871            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
1872        } else {
1873            OffsetUtf16(0)
1874        };
1875        *cursor.start() + overshoot
1876    }
1877
1878    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
1879        if let Some((_, _, buffer)) = self.as_singleton() {
1880            return buffer.clip_point_utf16(point, bias);
1881        }
1882
1883        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1884        cursor.seek(&point.0, Bias::Right, &());
1885        let overshoot = if let Some(excerpt) = cursor.item() {
1886            let excerpt_start = excerpt
1887                .buffer
1888                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1889            let buffer_point = excerpt
1890                .buffer
1891                .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
1892            buffer_point.saturating_sub(excerpt_start)
1893        } else {
1894            PointUtf16::zero()
1895        };
1896        *cursor.start() + overshoot
1897    }
1898
1899    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
1900        let range = range.start.to_offset(self)..range.end.to_offset(self);
1901        let mut excerpts = self.excerpts.cursor::<usize>();
1902        excerpts.seek(&range.start, Bias::Right, &());
1903
1904        let mut chunk = &[][..];
1905        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1906            let mut excerpt_bytes = excerpt
1907                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1908            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1909            Some(excerpt_bytes)
1910        } else {
1911            None
1912        };
1913
1914        MultiBufferBytes {
1915            range,
1916            excerpts,
1917            excerpt_bytes,
1918            chunk,
1919        }
1920    }
1921
1922    pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
1923        let mut result = MultiBufferRows {
1924            buffer_row_range: 0..0,
1925            excerpts: self.excerpts.cursor(),
1926        };
1927        result.seek(start_row);
1928        result
1929    }
1930
1931    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
1932        let range = range.start.to_offset(self)..range.end.to_offset(self);
1933        let mut chunks = MultiBufferChunks {
1934            range: range.clone(),
1935            excerpts: self.excerpts.cursor(),
1936            excerpt_chunks: None,
1937            language_aware,
1938        };
1939        chunks.seek(range.start);
1940        chunks
1941    }
1942
1943    pub fn offset_to_point(&self, offset: usize) -> Point {
1944        if let Some((_, _, buffer)) = self.as_singleton() {
1945            return buffer.offset_to_point(offset);
1946        }
1947
1948        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1949        cursor.seek(&offset, Bias::Right, &());
1950        if let Some(excerpt) = cursor.item() {
1951            let (start_offset, start_point) = cursor.start();
1952            let overshoot = offset - start_offset;
1953            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1954            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1955            let buffer_point = excerpt
1956                .buffer
1957                .offset_to_point(excerpt_start_offset + overshoot);
1958            *start_point + (buffer_point - excerpt_start_point)
1959        } else {
1960            self.excerpts.summary().text.lines
1961        }
1962    }
1963
1964    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1965        if let Some((_, _, buffer)) = self.as_singleton() {
1966            return buffer.offset_to_point_utf16(offset);
1967        }
1968
1969        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1970        cursor.seek(&offset, Bias::Right, &());
1971        if let Some(excerpt) = cursor.item() {
1972            let (start_offset, start_point) = cursor.start();
1973            let overshoot = offset - start_offset;
1974            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1975            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1976            let buffer_point = excerpt
1977                .buffer
1978                .offset_to_point_utf16(excerpt_start_offset + overshoot);
1979            *start_point + (buffer_point - excerpt_start_point)
1980        } else {
1981            self.excerpts.summary().text.lines_utf16()
1982        }
1983    }
1984
1985    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1986        if let Some((_, _, buffer)) = self.as_singleton() {
1987            return buffer.point_to_point_utf16(point);
1988        }
1989
1990        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1991        cursor.seek(&point, Bias::Right, &());
1992        if let Some(excerpt) = cursor.item() {
1993            let (start_offset, start_point) = cursor.start();
1994            let overshoot = point - start_offset;
1995            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1996            let excerpt_start_point_utf16 =
1997                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1998            let buffer_point = excerpt
1999                .buffer
2000                .point_to_point_utf16(excerpt_start_point + overshoot);
2001            *start_point + (buffer_point - excerpt_start_point_utf16)
2002        } else {
2003            self.excerpts.summary().text.lines_utf16()
2004        }
2005    }
2006
2007    pub fn point_to_offset(&self, point: Point) -> usize {
2008        if let Some((_, _, buffer)) = self.as_singleton() {
2009            return buffer.point_to_offset(point);
2010        }
2011
2012        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2013        cursor.seek(&point, Bias::Right, &());
2014        if let Some(excerpt) = cursor.item() {
2015            let (start_point, start_offset) = cursor.start();
2016            let overshoot = point - start_point;
2017            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2018            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2019            let buffer_offset = excerpt
2020                .buffer
2021                .point_to_offset(excerpt_start_point + overshoot);
2022            *start_offset + buffer_offset - excerpt_start_offset
2023        } else {
2024            self.excerpts.summary().text.len
2025        }
2026    }
2027
2028    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2029        if let Some((_, _, buffer)) = self.as_singleton() {
2030            return buffer.offset_utf16_to_offset(offset_utf16);
2031        }
2032
2033        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2034        cursor.seek(&offset_utf16, Bias::Right, &());
2035        if let Some(excerpt) = cursor.item() {
2036            let (start_offset_utf16, start_offset) = cursor.start();
2037            let overshoot = offset_utf16 - start_offset_utf16;
2038            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2039            let excerpt_start_offset_utf16 =
2040                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2041            let buffer_offset = excerpt
2042                .buffer
2043                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2044            *start_offset + (buffer_offset - excerpt_start_offset)
2045        } else {
2046            self.excerpts.summary().text.len
2047        }
2048    }
2049
2050    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2051        if let Some((_, _, buffer)) = self.as_singleton() {
2052            return buffer.offset_to_offset_utf16(offset);
2053        }
2054
2055        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2056        cursor.seek(&offset, Bias::Right, &());
2057        if let Some(excerpt) = cursor.item() {
2058            let (start_offset, start_offset_utf16) = cursor.start();
2059            let overshoot = offset - start_offset;
2060            let excerpt_start_offset_utf16 =
2061                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2062            let excerpt_start_offset = excerpt
2063                .buffer
2064                .offset_utf16_to_offset(excerpt_start_offset_utf16);
2065            let buffer_offset_utf16 = excerpt
2066                .buffer
2067                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2068            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2069        } else {
2070            self.excerpts.summary().text.len_utf16
2071        }
2072    }
2073
2074    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2075        if let Some((_, _, buffer)) = self.as_singleton() {
2076            return buffer.point_utf16_to_offset(point);
2077        }
2078
2079        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2080        cursor.seek(&point, Bias::Right, &());
2081        if let Some(excerpt) = cursor.item() {
2082            let (start_point, start_offset) = cursor.start();
2083            let overshoot = point - start_point;
2084            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2085            let excerpt_start_point = excerpt
2086                .buffer
2087                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2088            let buffer_offset = excerpt
2089                .buffer
2090                .point_utf16_to_offset(excerpt_start_point + overshoot);
2091            *start_offset + (buffer_offset - excerpt_start_offset)
2092        } else {
2093            self.excerpts.summary().text.len
2094        }
2095    }
2096
2097    pub fn point_to_buffer_offset<T: ToOffset>(
2098        &self,
2099        point: T,
2100    ) -> Option<(&BufferSnapshot, usize)> {
2101        let offset = point.to_offset(&self);
2102        let mut cursor = self.excerpts.cursor::<usize>();
2103        cursor.seek(&offset, Bias::Right, &());
2104        if cursor.item().is_none() {
2105            cursor.prev(&());
2106        }
2107
2108        cursor.item().map(|excerpt| {
2109            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2110            let buffer_point = excerpt_start + offset - *cursor.start();
2111            (&excerpt.buffer, buffer_point)
2112        })
2113    }
2114
2115    pub fn suggested_indents(
2116        &self,
2117        rows: impl IntoIterator<Item = u32>,
2118        cx: &AppContext,
2119    ) -> BTreeMap<u32, IndentSize> {
2120        let mut result = BTreeMap::new();
2121
2122        let mut rows_for_excerpt = Vec::new();
2123        let mut cursor = self.excerpts.cursor::<Point>();
2124        let mut rows = rows.into_iter().peekable();
2125        let mut prev_row = u32::MAX;
2126        let mut prev_language_indent_size = IndentSize::default();
2127
2128        while let Some(row) = rows.next() {
2129            cursor.seek(&Point::new(row, 0), Bias::Right, &());
2130            let excerpt = match cursor.item() {
2131                Some(excerpt) => excerpt,
2132                _ => continue,
2133            };
2134
2135            // Retrieve the language and indent size once for each disjoint region being indented.
2136            let single_indent_size = if row.saturating_sub(1) == prev_row {
2137                prev_language_indent_size
2138            } else {
2139                excerpt
2140                    .buffer
2141                    .language_indent_size_at(Point::new(row, 0), cx)
2142            };
2143            prev_language_indent_size = single_indent_size;
2144            prev_row = row;
2145
2146            let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2147            let start_multibuffer_row = cursor.start().row;
2148
2149            rows_for_excerpt.push(row);
2150            while let Some(next_row) = rows.peek().copied() {
2151                if cursor.end(&()).row > next_row {
2152                    rows_for_excerpt.push(next_row);
2153                    rows.next();
2154                } else {
2155                    break;
2156                }
2157            }
2158
2159            let buffer_rows = rows_for_excerpt
2160                .drain(..)
2161                .map(|row| start_buffer_row + row - start_multibuffer_row);
2162            let buffer_indents = excerpt
2163                .buffer
2164                .suggested_indents(buffer_rows, single_indent_size);
2165            let multibuffer_indents = buffer_indents
2166                .into_iter()
2167                .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2168            result.extend(multibuffer_indents);
2169        }
2170
2171        result
2172    }
2173
2174    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2175        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2176            let mut size = buffer.indent_size_for_line(range.start.row);
2177            size.len = size
2178                .len
2179                .min(range.end.column)
2180                .saturating_sub(range.start.column);
2181            size
2182        } else {
2183            IndentSize::spaces(0)
2184        }
2185    }
2186
2187    pub fn line_len(&self, row: u32) -> u32 {
2188        if let Some((_, range)) = self.buffer_line_for_row(row) {
2189            range.end.column - range.start.column
2190        } else {
2191            0
2192        }
2193    }
2194
2195    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2196        let mut cursor = self.excerpts.cursor::<Point>();
2197        let point = Point::new(row, 0);
2198        cursor.seek(&point, Bias::Right, &());
2199        if cursor.item().is_none() && *cursor.start() == point {
2200            cursor.prev(&());
2201        }
2202        if let Some(excerpt) = cursor.item() {
2203            let overshoot = row - cursor.start().row;
2204            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2205            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2206            let buffer_row = excerpt_start.row + overshoot;
2207            let line_start = Point::new(buffer_row, 0);
2208            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2209            return Some((
2210                &excerpt.buffer,
2211                line_start.max(excerpt_start)..line_end.min(excerpt_end),
2212            ));
2213        }
2214        None
2215    }
2216
2217    pub fn max_point(&self) -> Point {
2218        self.text_summary().lines
2219    }
2220
2221    pub fn text_summary(&self) -> TextSummary {
2222        self.excerpts.summary().text.clone()
2223    }
2224
2225    pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2226    where
2227        D: TextDimension,
2228        O: ToOffset,
2229    {
2230        let mut summary = D::default();
2231        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2232        let mut cursor = self.excerpts.cursor::<usize>();
2233        cursor.seek(&range.start, Bias::Right, &());
2234        if let Some(excerpt) = cursor.item() {
2235            let mut end_before_newline = cursor.end(&());
2236            if excerpt.has_trailing_newline {
2237                end_before_newline -= 1;
2238            }
2239
2240            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2241            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2242            let end_in_excerpt =
2243                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2244            summary.add_assign(
2245                &excerpt
2246                    .buffer
2247                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2248            );
2249
2250            if range.end > end_before_newline {
2251                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2252            }
2253
2254            cursor.next(&());
2255        }
2256
2257        if range.end > *cursor.start() {
2258            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2259                &range.end,
2260                Bias::Right,
2261                &(),
2262            )));
2263            if let Some(excerpt) = cursor.item() {
2264                range.end = cmp::max(*cursor.start(), range.end);
2265
2266                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2267                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2268                summary.add_assign(
2269                    &excerpt
2270                        .buffer
2271                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2272                );
2273            }
2274        }
2275
2276        summary
2277    }
2278
2279    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2280    where
2281        D: TextDimension + Ord + Sub<D, Output = D>,
2282    {
2283        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2284        let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2285
2286        cursor.seek(locator, Bias::Left, &());
2287        if cursor.item().is_none() {
2288            cursor.next(&());
2289        }
2290
2291        let mut position = D::from_text_summary(&cursor.start().text);
2292        if let Some(excerpt) = cursor.item() {
2293            if excerpt.id == anchor.excerpt_id {
2294                let excerpt_buffer_start =
2295                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2296                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2297                let buffer_position = cmp::min(
2298                    excerpt_buffer_end,
2299                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2300                );
2301                if buffer_position > excerpt_buffer_start {
2302                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2303                }
2304            }
2305        }
2306        position
2307    }
2308
2309    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2310    where
2311        D: TextDimension + Ord + Sub<D, Output = D>,
2312        I: 'a + IntoIterator<Item = &'a Anchor>,
2313    {
2314        if let Some((_, _, buffer)) = self.as_singleton() {
2315            return buffer
2316                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2317                .collect();
2318        }
2319
2320        let mut anchors = anchors.into_iter().peekable();
2321        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2322        let mut summaries = Vec::new();
2323        while let Some(anchor) = anchors.peek() {
2324            let excerpt_id = anchor.excerpt_id;
2325            let excerpt_anchors = iter::from_fn(|| {
2326                let anchor = anchors.peek()?;
2327                if anchor.excerpt_id == excerpt_id {
2328                    Some(&anchors.next().unwrap().text_anchor)
2329                } else {
2330                    None
2331                }
2332            });
2333
2334            let locator = self.excerpt_locator_for_id(excerpt_id);
2335            cursor.seek_forward(locator, Bias::Left, &());
2336            if cursor.item().is_none() {
2337                cursor.next(&());
2338            }
2339
2340            let position = D::from_text_summary(&cursor.start().text);
2341            if let Some(excerpt) = cursor.item() {
2342                if excerpt.id == excerpt_id {
2343                    let excerpt_buffer_start =
2344                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2345                    let excerpt_buffer_end =
2346                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2347                    summaries.extend(
2348                        excerpt
2349                            .buffer
2350                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2351                            .map(move |summary| {
2352                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2353                                let mut position = position.clone();
2354                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2355                                if summary > excerpt_buffer_start {
2356                                    position.add_assign(&(summary - excerpt_buffer_start));
2357                                }
2358                                position
2359                            }),
2360                    );
2361                    continue;
2362                }
2363            }
2364
2365            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2366        }
2367
2368        summaries
2369    }
2370
2371    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2372    where
2373        I: 'a + IntoIterator<Item = &'a Anchor>,
2374    {
2375        let mut anchors = anchors.into_iter().enumerate().peekable();
2376        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2377        cursor.next(&());
2378
2379        let mut result = Vec::new();
2380
2381        while let Some((_, anchor)) = anchors.peek() {
2382            let old_excerpt_id = anchor.excerpt_id;
2383
2384            // Find the location where this anchor's excerpt should be.
2385            let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2386            cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2387
2388            if cursor.item().is_none() {
2389                cursor.next(&());
2390            }
2391
2392            let next_excerpt = cursor.item();
2393            let prev_excerpt = cursor.prev_item();
2394
2395            // Process all of the anchors for this excerpt.
2396            while let Some((_, anchor)) = anchors.peek() {
2397                if anchor.excerpt_id != old_excerpt_id {
2398                    break;
2399                }
2400                let (anchor_ix, anchor) = anchors.next().unwrap();
2401                let mut anchor = *anchor;
2402
2403                // Leave min and max anchors unchanged if invalid or
2404                // if the old excerpt still exists at this location
2405                let mut kept_position = next_excerpt
2406                    .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2407                    || old_excerpt_id == ExcerptId::max()
2408                    || old_excerpt_id == ExcerptId::min();
2409
2410                // If the old excerpt no longer exists at this location, then attempt to
2411                // find an equivalent position for this anchor in an adjacent excerpt.
2412                if !kept_position {
2413                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2414                        if excerpt.contains(&anchor) {
2415                            anchor.excerpt_id = excerpt.id.clone();
2416                            kept_position = true;
2417                            break;
2418                        }
2419                    }
2420                }
2421
2422                // If there's no adjacent excerpt that contains the anchor's position,
2423                // then report that the anchor has lost its position.
2424                if !kept_position {
2425                    anchor = if let Some(excerpt) = next_excerpt {
2426                        let mut text_anchor = excerpt
2427                            .range
2428                            .context
2429                            .start
2430                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2431                        if text_anchor
2432                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2433                            .is_gt()
2434                        {
2435                            text_anchor = excerpt.range.context.end;
2436                        }
2437                        Anchor {
2438                            buffer_id: Some(excerpt.buffer_id),
2439                            excerpt_id: excerpt.id.clone(),
2440                            text_anchor,
2441                        }
2442                    } else if let Some(excerpt) = prev_excerpt {
2443                        let mut text_anchor = excerpt
2444                            .range
2445                            .context
2446                            .end
2447                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2448                        if text_anchor
2449                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2450                            .is_lt()
2451                        {
2452                            text_anchor = excerpt.range.context.start;
2453                        }
2454                        Anchor {
2455                            buffer_id: Some(excerpt.buffer_id),
2456                            excerpt_id: excerpt.id.clone(),
2457                            text_anchor,
2458                        }
2459                    } else if anchor.text_anchor.bias == Bias::Left {
2460                        Anchor::min()
2461                    } else {
2462                        Anchor::max()
2463                    };
2464                }
2465
2466                result.push((anchor_ix, anchor, kept_position));
2467            }
2468        }
2469        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2470        result
2471    }
2472
2473    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2474        self.anchor_at(position, Bias::Left)
2475    }
2476
2477    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2478        self.anchor_at(position, Bias::Right)
2479    }
2480
2481    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2482        let offset = position.to_offset(self);
2483        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2484            return Anchor {
2485                buffer_id: Some(buffer_id),
2486                excerpt_id: excerpt_id.clone(),
2487                text_anchor: buffer.anchor_at(offset, bias),
2488            };
2489        }
2490
2491        let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2492        cursor.seek(&offset, Bias::Right, &());
2493        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2494            cursor.prev(&());
2495        }
2496        if let Some(excerpt) = cursor.item() {
2497            let mut overshoot = offset.saturating_sub(cursor.start().0);
2498            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2499                overshoot -= 1;
2500                bias = Bias::Right;
2501            }
2502
2503            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2504            let text_anchor =
2505                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2506            Anchor {
2507                buffer_id: Some(excerpt.buffer_id),
2508                excerpt_id: excerpt.id.clone(),
2509                text_anchor,
2510            }
2511        } else if offset == 0 && bias == Bias::Left {
2512            Anchor::min()
2513        } else {
2514            Anchor::max()
2515        }
2516    }
2517
2518    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2519        let locator = self.excerpt_locator_for_id(excerpt_id);
2520        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2521        cursor.seek(locator, Bias::Left, &());
2522        if let Some(excerpt) = cursor.item() {
2523            if excerpt.id == excerpt_id {
2524                let text_anchor = excerpt.clip_anchor(text_anchor);
2525                drop(cursor);
2526                return Anchor {
2527                    buffer_id: Some(excerpt.buffer_id),
2528                    excerpt_id,
2529                    text_anchor,
2530                };
2531            }
2532        }
2533        panic!("excerpt not found");
2534    }
2535
2536    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2537        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2538            true
2539        } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2540            excerpt.buffer.can_resolve(&anchor.text_anchor)
2541        } else {
2542            false
2543        }
2544    }
2545
2546    pub fn excerpts(
2547        &self,
2548    ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2549        self.excerpts
2550            .iter()
2551            .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2552    }
2553
2554    pub fn excerpt_boundaries_in_range<R, T>(
2555        &self,
2556        range: R,
2557    ) -> impl Iterator<Item = ExcerptBoundary> + '_
2558    where
2559        R: RangeBounds<T>,
2560        T: ToOffset,
2561    {
2562        let start_offset;
2563        let start = match range.start_bound() {
2564            Bound::Included(start) => {
2565                start_offset = start.to_offset(self);
2566                Bound::Included(start_offset)
2567            }
2568            Bound::Excluded(start) => {
2569                start_offset = start.to_offset(self);
2570                Bound::Excluded(start_offset)
2571            }
2572            Bound::Unbounded => {
2573                start_offset = 0;
2574                Bound::Unbounded
2575            }
2576        };
2577        let end = match range.end_bound() {
2578            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2579            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2580            Bound::Unbounded => Bound::Unbounded,
2581        };
2582        let bounds = (start, end);
2583
2584        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2585        cursor.seek(&start_offset, Bias::Right, &());
2586        if cursor.item().is_none() {
2587            cursor.prev(&());
2588        }
2589        if !bounds.contains(&cursor.start().0) {
2590            cursor.next(&());
2591        }
2592
2593        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2594        std::iter::from_fn(move || {
2595            if self.singleton {
2596                None
2597            } else if bounds.contains(&cursor.start().0) {
2598                let excerpt = cursor.item()?;
2599                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2600                let boundary = ExcerptBoundary {
2601                    id: excerpt.id.clone(),
2602                    row: cursor.start().1.row,
2603                    buffer: excerpt.buffer.clone(),
2604                    range: excerpt.range.clone(),
2605                    starts_new_buffer,
2606                };
2607
2608                prev_buffer_id = Some(excerpt.buffer_id);
2609                cursor.next(&());
2610                Some(boundary)
2611            } else {
2612                None
2613            }
2614        })
2615    }
2616
2617    pub fn edit_count(&self) -> usize {
2618        self.edit_count
2619    }
2620
2621    pub fn parse_count(&self) -> usize {
2622        self.parse_count
2623    }
2624
2625    /// Returns the smallest enclosing bracket ranges containing the given range or
2626    /// None if no brackets contain range or the range is not contained in a single
2627    /// excerpt
2628    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2629        &self,
2630        range: Range<T>,
2631    ) -> Option<(Range<usize>, Range<usize>)> {
2632        let range = range.start.to_offset(self)..range.end.to_offset(self);
2633
2634        // Get the ranges of the innermost pair of brackets.
2635        let mut result: Option<(Range<usize>, Range<usize>)> = None;
2636
2637        let Some(enclosing_bracket_ranges) = self.enclosing_bracket_ranges(range.clone()) else { return None; };
2638
2639        for (open, close) in enclosing_bracket_ranges {
2640            let len = close.end - open.start;
2641
2642            if let Some((existing_open, existing_close)) = &result {
2643                let existing_len = existing_close.end - existing_open.start;
2644                if len > existing_len {
2645                    continue;
2646                }
2647            }
2648
2649            result = Some((open, close));
2650        }
2651
2652        result
2653    }
2654
2655    /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2656    /// not contained in a single excerpt
2657    pub fn enclosing_bracket_ranges<'a, T: ToOffset>(
2658        &'a self,
2659        range: Range<T>,
2660    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2661        let range = range.start.to_offset(self)..range.end.to_offset(self);
2662
2663        self.bracket_ranges(range.clone()).map(|range_pairs| {
2664            range_pairs
2665                .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2666        })
2667    }
2668
2669    /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2670    /// not contained in a single excerpt
2671    pub fn bracket_ranges<'a, T: ToOffset>(
2672        &'a self,
2673        range: Range<T>,
2674    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2675        let range = range.start.to_offset(self)..range.end.to_offset(self);
2676        let excerpt = self.excerpt_containing(range.clone());
2677        excerpt.map(|(excerpt, excerpt_offset)| {
2678            let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2679            let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2680
2681            let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2682            let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2683
2684            excerpt
2685                .buffer
2686                .bracket_ranges(start_in_buffer..end_in_buffer)
2687                .filter_map(move |(start_bracket_range, end_bracket_range)| {
2688                    if start_bracket_range.start < excerpt_buffer_start
2689                        || end_bracket_range.end > excerpt_buffer_end
2690                    {
2691                        return None;
2692                    }
2693
2694                    let mut start_bracket_range = start_bracket_range.clone();
2695                    start_bracket_range.start =
2696                        excerpt_offset + (start_bracket_range.start - excerpt_buffer_start);
2697                    start_bracket_range.end =
2698                        excerpt_offset + (start_bracket_range.end - excerpt_buffer_start);
2699
2700                    let mut end_bracket_range = end_bracket_range.clone();
2701                    end_bracket_range.start =
2702                        excerpt_offset + (end_bracket_range.start - excerpt_buffer_start);
2703                    end_bracket_range.end =
2704                        excerpt_offset + (end_bracket_range.end - excerpt_buffer_start);
2705                    Some((start_bracket_range, end_bracket_range))
2706                })
2707        })
2708    }
2709
2710    pub fn diagnostics_update_count(&self) -> usize {
2711        self.diagnostics_update_count
2712    }
2713
2714    pub fn git_diff_update_count(&self) -> usize {
2715        self.git_diff_update_count
2716    }
2717
2718    pub fn trailing_excerpt_update_count(&self) -> usize {
2719        self.trailing_excerpt_update_count
2720    }
2721
2722    pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2723        self.point_to_buffer_offset(point)
2724            .and_then(|(buffer, offset)| buffer.language_at(offset))
2725    }
2726
2727    pub fn language_scope_at<'a, T: ToOffset>(&'a self, point: T) -> Option<LanguageScope> {
2728        self.point_to_buffer_offset(point)
2729            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
2730    }
2731
2732    pub fn is_dirty(&self) -> bool {
2733        self.is_dirty
2734    }
2735
2736    pub fn has_conflict(&self) -> bool {
2737        self.has_conflict
2738    }
2739
2740    pub fn diagnostic_group<'a, O>(
2741        &'a self,
2742        group_id: usize,
2743    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2744    where
2745        O: text::FromAnchor + 'a,
2746    {
2747        self.as_singleton()
2748            .into_iter()
2749            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2750    }
2751
2752    pub fn diagnostics_in_range<'a, T, O>(
2753        &'a self,
2754        range: Range<T>,
2755        reversed: bool,
2756    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2757    where
2758        T: 'a + ToOffset,
2759        O: 'a + text::FromAnchor,
2760    {
2761        self.as_singleton()
2762            .into_iter()
2763            .flat_map(move |(_, _, buffer)| {
2764                buffer.diagnostics_in_range(
2765                    range.start.to_offset(self)..range.end.to_offset(self),
2766                    reversed,
2767                )
2768            })
2769    }
2770
2771    pub fn git_diff_hunks_in_range<'a>(
2772        &'a self,
2773        row_range: Range<u32>,
2774        reversed: bool,
2775    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2776        let mut cursor = self.excerpts.cursor::<Point>();
2777
2778        if reversed {
2779            cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2780            if cursor.item().is_none() {
2781                cursor.prev(&());
2782            }
2783        } else {
2784            cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
2785        }
2786
2787        std::iter::from_fn(move || {
2788            let excerpt = cursor.item()?;
2789            let multibuffer_start = *cursor.start();
2790            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2791            if multibuffer_start.row >= row_range.end {
2792                return None;
2793            }
2794
2795            let mut buffer_start = excerpt.range.context.start;
2796            let mut buffer_end = excerpt.range.context.end;
2797            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2798            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2799
2800            if row_range.start > multibuffer_start.row {
2801                let buffer_start_point =
2802                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2803                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2804            }
2805
2806            if row_range.end < multibuffer_end.row {
2807                let buffer_end_point =
2808                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2809                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2810            }
2811
2812            let buffer_hunks = excerpt
2813                .buffer
2814                .git_diff_hunks_intersecting_range(buffer_start..buffer_end, reversed)
2815                .filter_map(move |hunk| {
2816                    let start = multibuffer_start.row
2817                        + hunk
2818                            .buffer_range
2819                            .start
2820                            .saturating_sub(excerpt_start_point.row);
2821                    let end = multibuffer_start.row
2822                        + hunk
2823                            .buffer_range
2824                            .end
2825                            .min(excerpt_end_point.row + 1)
2826                            .saturating_sub(excerpt_start_point.row);
2827
2828                    Some(DiffHunk {
2829                        buffer_range: start..end,
2830                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2831                    })
2832                });
2833
2834            if reversed {
2835                cursor.prev(&());
2836            } else {
2837                cursor.next(&());
2838            }
2839
2840            Some(buffer_hunks)
2841        })
2842        .flatten()
2843    }
2844
2845    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2846        let range = range.start.to_offset(self)..range.end.to_offset(self);
2847
2848        self.excerpt_containing(range.clone())
2849            .and_then(|(excerpt, excerpt_offset)| {
2850                let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2851                let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2852
2853                let start_in_buffer =
2854                    excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2855                let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2856                let mut ancestor_buffer_range = excerpt
2857                    .buffer
2858                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2859                ancestor_buffer_range.start =
2860                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2861                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2862
2863                let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
2864                let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
2865                Some(start..end)
2866            })
2867    }
2868
2869    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2870        let (excerpt_id, _, buffer) = self.as_singleton()?;
2871        let outline = buffer.outline(theme)?;
2872        Some(Outline::new(
2873            outline
2874                .items
2875                .into_iter()
2876                .map(|item| OutlineItem {
2877                    depth: item.depth,
2878                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2879                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2880                    text: item.text,
2881                    highlight_ranges: item.highlight_ranges,
2882                    name_ranges: item.name_ranges,
2883                })
2884                .collect(),
2885        ))
2886    }
2887
2888    pub fn symbols_containing<T: ToOffset>(
2889        &self,
2890        offset: T,
2891        theme: Option<&SyntaxTheme>,
2892    ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
2893        let anchor = self.anchor_before(offset);
2894        let excerpt_id = anchor.excerpt_id();
2895        let excerpt = self.excerpt(excerpt_id)?;
2896        Some((
2897            excerpt.buffer_id,
2898            excerpt
2899                .buffer
2900                .symbols_containing(anchor.text_anchor, theme)
2901                .into_iter()
2902                .flatten()
2903                .map(|item| OutlineItem {
2904                    depth: item.depth,
2905                    range: self.anchor_in_excerpt(excerpt_id, item.range.start)
2906                        ..self.anchor_in_excerpt(excerpt_id, item.range.end),
2907                    text: item.text,
2908                    highlight_ranges: item.highlight_ranges,
2909                    name_ranges: item.name_ranges,
2910                })
2911                .collect(),
2912        ))
2913    }
2914
2915    fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
2916        if id == ExcerptId::min() {
2917            Locator::min_ref()
2918        } else if id == ExcerptId::max() {
2919            Locator::max_ref()
2920        } else {
2921            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
2922            cursor.seek(&id, Bias::Left, &());
2923            if let Some(entry) = cursor.item() {
2924                if entry.id == id {
2925                    return &entry.locator;
2926                }
2927            }
2928            panic!("invalid excerpt id {:?}", id)
2929        }
2930    }
2931
2932    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<usize> {
2933        Some(self.excerpt(excerpt_id)?.buffer_id)
2934    }
2935
2936    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
2937        Some(&self.excerpt(excerpt_id)?.buffer)
2938    }
2939
2940    fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
2941        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2942        let locator = self.excerpt_locator_for_id(excerpt_id);
2943        cursor.seek(&Some(locator), Bias::Left, &());
2944        if let Some(excerpt) = cursor.item() {
2945            if excerpt.id == excerpt_id {
2946                return Some(excerpt);
2947            }
2948        }
2949        None
2950    }
2951
2952    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
2953    fn excerpt_containing<'a, T: ToOffset>(
2954        &'a self,
2955        range: Range<T>,
2956    ) -> Option<(&'a Excerpt, usize)> {
2957        let range = range.start.to_offset(self)..range.end.to_offset(self);
2958
2959        let mut cursor = self.excerpts.cursor::<usize>();
2960        cursor.seek(&range.start, Bias::Right, &());
2961        let start_excerpt = cursor.item();
2962
2963        if range.start == range.end {
2964            return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
2965        }
2966
2967        cursor.seek(&range.end, Bias::Right, &());
2968        let end_excerpt = cursor.item();
2969
2970        start_excerpt
2971            .zip(end_excerpt)
2972            .and_then(|(start_excerpt, end_excerpt)| {
2973                if start_excerpt.id != end_excerpt.id {
2974                    return None;
2975                }
2976
2977                Some((start_excerpt, *cursor.start()))
2978            })
2979    }
2980
2981    pub fn remote_selections_in_range<'a>(
2982        &'a self,
2983        range: &'a Range<Anchor>,
2984    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
2985        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2986        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
2987        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
2988        cursor.seek(start_locator, Bias::Left, &());
2989        cursor
2990            .take_while(move |excerpt| excerpt.locator <= *end_locator)
2991            .flat_map(move |excerpt| {
2992                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
2993                if excerpt.id == range.start.excerpt_id {
2994                    query_range.start = range.start.text_anchor;
2995                }
2996                if excerpt.id == range.end.excerpt_id {
2997                    query_range.end = range.end.text_anchor;
2998                }
2999
3000                excerpt
3001                    .buffer
3002                    .remote_selections_in_range(query_range)
3003                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3004                        selections.map(move |selection| {
3005                            let mut start = Anchor {
3006                                buffer_id: Some(excerpt.buffer_id),
3007                                excerpt_id: excerpt.id.clone(),
3008                                text_anchor: selection.start,
3009                            };
3010                            let mut end = Anchor {
3011                                buffer_id: Some(excerpt.buffer_id),
3012                                excerpt_id: excerpt.id.clone(),
3013                                text_anchor: selection.end,
3014                            };
3015                            if range.start.cmp(&start, self).is_gt() {
3016                                start = range.start.clone();
3017                            }
3018                            if range.end.cmp(&end, self).is_lt() {
3019                                end = range.end.clone();
3020                            }
3021
3022                            (
3023                                replica_id,
3024                                line_mode,
3025                                cursor_shape,
3026                                Selection {
3027                                    id: selection.id,
3028                                    start,
3029                                    end,
3030                                    reversed: selection.reversed,
3031                                    goal: selection.goal,
3032                                },
3033                            )
3034                        })
3035                    })
3036            })
3037    }
3038}
3039
3040#[cfg(any(test, feature = "test-support"))]
3041impl MultiBufferSnapshot {
3042    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3043        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3044        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3045        start..end
3046    }
3047}
3048
3049impl History {
3050    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3051        self.transaction_depth += 1;
3052        if self.transaction_depth == 1 {
3053            let id = self.next_transaction_id.tick();
3054            self.undo_stack.push(Transaction {
3055                id,
3056                buffer_transactions: Default::default(),
3057                first_edit_at: now,
3058                last_edit_at: now,
3059                suppress_grouping: false,
3060            });
3061            Some(id)
3062        } else {
3063            None
3064        }
3065    }
3066
3067    fn end_transaction(
3068        &mut self,
3069        now: Instant,
3070        buffer_transactions: HashMap<usize, TransactionId>,
3071    ) -> bool {
3072        assert_ne!(self.transaction_depth, 0);
3073        self.transaction_depth -= 1;
3074        if self.transaction_depth == 0 {
3075            if buffer_transactions.is_empty() {
3076                self.undo_stack.pop();
3077                false
3078            } else {
3079                self.redo_stack.clear();
3080                let transaction = self.undo_stack.last_mut().unwrap();
3081                transaction.last_edit_at = now;
3082                for (buffer_id, transaction_id) in buffer_transactions {
3083                    transaction
3084                        .buffer_transactions
3085                        .entry(buffer_id)
3086                        .or_insert(transaction_id);
3087                }
3088                true
3089            }
3090        } else {
3091            false
3092        }
3093    }
3094
3095    fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
3096    where
3097        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3098    {
3099        assert_eq!(self.transaction_depth, 0);
3100        let transaction = Transaction {
3101            id: self.next_transaction_id.tick(),
3102            buffer_transactions: buffer_transactions
3103                .into_iter()
3104                .map(|(buffer, transaction)| (buffer.id(), transaction.id))
3105                .collect(),
3106            first_edit_at: now,
3107            last_edit_at: now,
3108            suppress_grouping: false,
3109        };
3110        if !transaction.buffer_transactions.is_empty() {
3111            self.undo_stack.push(transaction);
3112            self.redo_stack.clear();
3113        }
3114    }
3115
3116    fn finalize_last_transaction(&mut self) {
3117        if let Some(transaction) = self.undo_stack.last_mut() {
3118            transaction.suppress_grouping = true;
3119        }
3120    }
3121
3122    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3123        assert_eq!(self.transaction_depth, 0);
3124        if let Some(transaction) = self.undo_stack.pop() {
3125            self.redo_stack.push(transaction);
3126            self.redo_stack.last_mut()
3127        } else {
3128            None
3129        }
3130    }
3131
3132    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3133        assert_eq!(self.transaction_depth, 0);
3134        if let Some(transaction) = self.redo_stack.pop() {
3135            self.undo_stack.push(transaction);
3136            self.undo_stack.last_mut()
3137        } else {
3138            None
3139        }
3140    }
3141
3142    fn group(&mut self) -> Option<TransactionId> {
3143        let mut count = 0;
3144        let mut transactions = self.undo_stack.iter();
3145        if let Some(mut transaction) = transactions.next_back() {
3146            while let Some(prev_transaction) = transactions.next_back() {
3147                if !prev_transaction.suppress_grouping
3148                    && transaction.first_edit_at - prev_transaction.last_edit_at
3149                        <= self.group_interval
3150                {
3151                    transaction = prev_transaction;
3152                    count += 1;
3153                } else {
3154                    break;
3155                }
3156            }
3157        }
3158        self.group_trailing(count)
3159    }
3160
3161    fn group_until(&mut self, transaction_id: TransactionId) {
3162        let mut count = 0;
3163        for transaction in self.undo_stack.iter().rev() {
3164            if transaction.id == transaction_id {
3165                self.group_trailing(count);
3166                break;
3167            } else if transaction.suppress_grouping {
3168                break;
3169            } else {
3170                count += 1;
3171            }
3172        }
3173    }
3174
3175    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3176        let new_len = self.undo_stack.len() - n;
3177        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3178        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3179            if let Some(transaction) = transactions_to_merge.last() {
3180                last_transaction.last_edit_at = transaction.last_edit_at;
3181            }
3182            for to_merge in transactions_to_merge {
3183                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3184                    last_transaction
3185                        .buffer_transactions
3186                        .entry(*buffer_id)
3187                        .or_insert(*transaction_id);
3188                }
3189            }
3190        }
3191
3192        self.undo_stack.truncate(new_len);
3193        self.undo_stack.last().map(|t| t.id)
3194    }
3195}
3196
3197impl Excerpt {
3198    fn new(
3199        id: ExcerptId,
3200        locator: Locator,
3201        buffer_id: usize,
3202        buffer: BufferSnapshot,
3203        range: ExcerptRange<text::Anchor>,
3204        has_trailing_newline: bool,
3205    ) -> Self {
3206        Excerpt {
3207            id,
3208            locator,
3209            max_buffer_row: range.context.end.to_point(&buffer).row,
3210            text_summary: buffer
3211                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3212            buffer_id,
3213            buffer,
3214            range,
3215            has_trailing_newline,
3216        }
3217    }
3218
3219    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3220        let content_start = self.range.context.start.to_offset(&self.buffer);
3221        let chunks_start = content_start + range.start;
3222        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3223
3224        let footer_height = if self.has_trailing_newline
3225            && range.start <= self.text_summary.len
3226            && range.end > self.text_summary.len
3227        {
3228            1
3229        } else {
3230            0
3231        };
3232
3233        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3234
3235        ExcerptChunks {
3236            content_chunks,
3237            footer_height,
3238        }
3239    }
3240
3241    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3242        let content_start = self.range.context.start.to_offset(&self.buffer);
3243        let bytes_start = content_start + range.start;
3244        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3245        let footer_height = if self.has_trailing_newline
3246            && range.start <= self.text_summary.len
3247            && range.end > self.text_summary.len
3248        {
3249            1
3250        } else {
3251            0
3252        };
3253        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3254
3255        ExcerptBytes {
3256            content_bytes,
3257            footer_height,
3258        }
3259    }
3260
3261    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3262        if text_anchor
3263            .cmp(&self.range.context.start, &self.buffer)
3264            .is_lt()
3265        {
3266            self.range.context.start
3267        } else if text_anchor
3268            .cmp(&self.range.context.end, &self.buffer)
3269            .is_gt()
3270        {
3271            self.range.context.end
3272        } else {
3273            text_anchor
3274        }
3275    }
3276
3277    fn contains(&self, anchor: &Anchor) -> bool {
3278        Some(self.buffer_id) == anchor.buffer_id
3279            && self
3280                .range
3281                .context
3282                .start
3283                .cmp(&anchor.text_anchor, &self.buffer)
3284                .is_le()
3285            && self
3286                .range
3287                .context
3288                .end
3289                .cmp(&anchor.text_anchor, &self.buffer)
3290                .is_ge()
3291    }
3292}
3293
3294impl ExcerptId {
3295    pub fn min() -> Self {
3296        Self(0)
3297    }
3298
3299    pub fn max() -> Self {
3300        Self(usize::MAX)
3301    }
3302
3303    pub fn to_proto(&self) -> u64 {
3304        self.0 as _
3305    }
3306
3307    pub fn from_proto(proto: u64) -> Self {
3308        Self(proto as _)
3309    }
3310
3311    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3312        let a = snapshot.excerpt_locator_for_id(*self);
3313        let b = snapshot.excerpt_locator_for_id(*other);
3314        a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3315    }
3316}
3317
3318impl Into<usize> for ExcerptId {
3319    fn into(self) -> usize {
3320        self.0
3321    }
3322}
3323
3324impl fmt::Debug for Excerpt {
3325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3326        f.debug_struct("Excerpt")
3327            .field("id", &self.id)
3328            .field("locator", &self.locator)
3329            .field("buffer_id", &self.buffer_id)
3330            .field("range", &self.range)
3331            .field("text_summary", &self.text_summary)
3332            .field("has_trailing_newline", &self.has_trailing_newline)
3333            .finish()
3334    }
3335}
3336
3337impl sum_tree::Item for Excerpt {
3338    type Summary = ExcerptSummary;
3339
3340    fn summary(&self) -> Self::Summary {
3341        let mut text = self.text_summary.clone();
3342        if self.has_trailing_newline {
3343            text += TextSummary::from("\n");
3344        }
3345        ExcerptSummary {
3346            excerpt_id: self.id,
3347            excerpt_locator: self.locator.clone(),
3348            max_buffer_row: self.max_buffer_row,
3349            text,
3350        }
3351    }
3352}
3353
3354impl sum_tree::Item for ExcerptIdMapping {
3355    type Summary = ExcerptId;
3356
3357    fn summary(&self) -> Self::Summary {
3358        self.id
3359    }
3360}
3361
3362impl sum_tree::KeyedItem for ExcerptIdMapping {
3363    type Key = ExcerptId;
3364
3365    fn key(&self) -> Self::Key {
3366        self.id
3367    }
3368}
3369
3370impl sum_tree::Summary for ExcerptId {
3371    type Context = ();
3372
3373    fn add_summary(&mut self, other: &Self, _: &()) {
3374        *self = *other;
3375    }
3376}
3377
3378impl sum_tree::Summary for ExcerptSummary {
3379    type Context = ();
3380
3381    fn add_summary(&mut self, summary: &Self, _: &()) {
3382        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3383        self.excerpt_locator = summary.excerpt_locator.clone();
3384        self.text.add_summary(&summary.text, &());
3385        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3386    }
3387}
3388
3389impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3390    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3391        *self += &summary.text;
3392    }
3393}
3394
3395impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3396    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3397        *self += summary.text.len;
3398    }
3399}
3400
3401impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3402    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3403        Ord::cmp(self, &cursor_location.text.len)
3404    }
3405}
3406
3407impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3408    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3409        Ord::cmp(&Some(self), cursor_location)
3410    }
3411}
3412
3413impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3414    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3415        Ord::cmp(self, &cursor_location.excerpt_locator)
3416    }
3417}
3418
3419impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3420    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3421        *self += summary.text.len_utf16;
3422    }
3423}
3424
3425impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3426    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3427        *self += summary.text.lines;
3428    }
3429}
3430
3431impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3432    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3433        *self += summary.text.lines_utf16()
3434    }
3435}
3436
3437impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3438    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3439        *self = Some(&summary.excerpt_locator);
3440    }
3441}
3442
3443impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3444    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3445        *self = Some(summary.excerpt_id);
3446    }
3447}
3448
3449impl<'a> MultiBufferRows<'a> {
3450    pub fn seek(&mut self, row: u32) {
3451        self.buffer_row_range = 0..0;
3452
3453        self.excerpts
3454            .seek_forward(&Point::new(row, 0), Bias::Right, &());
3455        if self.excerpts.item().is_none() {
3456            self.excerpts.prev(&());
3457
3458            if self.excerpts.item().is_none() && row == 0 {
3459                self.buffer_row_range = 0..1;
3460                return;
3461            }
3462        }
3463
3464        if let Some(excerpt) = self.excerpts.item() {
3465            let overshoot = row - self.excerpts.start().row;
3466            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3467            self.buffer_row_range.start = excerpt_start + overshoot;
3468            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3469        }
3470    }
3471}
3472
3473impl<'a> Iterator for MultiBufferRows<'a> {
3474    type Item = Option<u32>;
3475
3476    fn next(&mut self) -> Option<Self::Item> {
3477        loop {
3478            if !self.buffer_row_range.is_empty() {
3479                let row = Some(self.buffer_row_range.start);
3480                self.buffer_row_range.start += 1;
3481                return Some(row);
3482            }
3483            self.excerpts.item()?;
3484            self.excerpts.next(&());
3485            let excerpt = self.excerpts.item()?;
3486            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3487            self.buffer_row_range.end =
3488                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3489        }
3490    }
3491}
3492
3493impl<'a> MultiBufferChunks<'a> {
3494    pub fn offset(&self) -> usize {
3495        self.range.start
3496    }
3497
3498    pub fn seek(&mut self, offset: usize) {
3499        self.range.start = offset;
3500        self.excerpts.seek(&offset, Bias::Right, &());
3501        if let Some(excerpt) = self.excerpts.item() {
3502            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3503                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3504                self.language_aware,
3505            ));
3506        } else {
3507            self.excerpt_chunks = None;
3508        }
3509    }
3510}
3511
3512impl<'a> Iterator for MultiBufferChunks<'a> {
3513    type Item = Chunk<'a>;
3514
3515    fn next(&mut self) -> Option<Self::Item> {
3516        if self.range.is_empty() {
3517            None
3518        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3519            self.range.start += chunk.text.len();
3520            Some(chunk)
3521        } else {
3522            self.excerpts.next(&());
3523            let excerpt = self.excerpts.item()?;
3524            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3525                0..self.range.end - self.excerpts.start(),
3526                self.language_aware,
3527            ));
3528            self.next()
3529        }
3530    }
3531}
3532
3533impl<'a> MultiBufferBytes<'a> {
3534    fn consume(&mut self, len: usize) {
3535        self.range.start += len;
3536        self.chunk = &self.chunk[len..];
3537
3538        if !self.range.is_empty() && self.chunk.is_empty() {
3539            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3540                self.chunk = chunk;
3541            } else {
3542                self.excerpts.next(&());
3543                if let Some(excerpt) = self.excerpts.item() {
3544                    let mut excerpt_bytes =
3545                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3546                    self.chunk = excerpt_bytes.next().unwrap();
3547                    self.excerpt_bytes = Some(excerpt_bytes);
3548                }
3549            }
3550        }
3551    }
3552}
3553
3554impl<'a> Iterator for MultiBufferBytes<'a> {
3555    type Item = &'a [u8];
3556
3557    fn next(&mut self) -> Option<Self::Item> {
3558        let chunk = self.chunk;
3559        if chunk.is_empty() {
3560            None
3561        } else {
3562            self.consume(chunk.len());
3563            Some(chunk)
3564        }
3565    }
3566}
3567
3568impl<'a> io::Read for MultiBufferBytes<'a> {
3569    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3570        let len = cmp::min(buf.len(), self.chunk.len());
3571        buf[..len].copy_from_slice(&self.chunk[..len]);
3572        if len > 0 {
3573            self.consume(len);
3574        }
3575        Ok(len)
3576    }
3577}
3578
3579impl<'a> Iterator for ExcerptBytes<'a> {
3580    type Item = &'a [u8];
3581
3582    fn next(&mut self) -> Option<Self::Item> {
3583        if let Some(chunk) = self.content_bytes.next() {
3584            if !chunk.is_empty() {
3585                return Some(chunk);
3586            }
3587        }
3588
3589        if self.footer_height > 0 {
3590            let result = &NEWLINES[..self.footer_height];
3591            self.footer_height = 0;
3592            return Some(result);
3593        }
3594
3595        None
3596    }
3597}
3598
3599impl<'a> Iterator for ExcerptChunks<'a> {
3600    type Item = Chunk<'a>;
3601
3602    fn next(&mut self) -> Option<Self::Item> {
3603        if let Some(chunk) = self.content_chunks.next() {
3604            return Some(chunk);
3605        }
3606
3607        if self.footer_height > 0 {
3608            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3609            self.footer_height = 0;
3610            return Some(Chunk {
3611                text,
3612                ..Default::default()
3613            });
3614        }
3615
3616        None
3617    }
3618}
3619
3620impl ToOffset for Point {
3621    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3622        snapshot.point_to_offset(*self)
3623    }
3624}
3625
3626impl ToOffset for usize {
3627    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3628        assert!(*self <= snapshot.len(), "offset is out of range");
3629        *self
3630    }
3631}
3632
3633impl ToOffset for OffsetUtf16 {
3634    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3635        snapshot.offset_utf16_to_offset(*self)
3636    }
3637}
3638
3639impl ToOffset for PointUtf16 {
3640    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3641        snapshot.point_utf16_to_offset(*self)
3642    }
3643}
3644
3645impl ToOffsetUtf16 for OffsetUtf16 {
3646    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3647        *self
3648    }
3649}
3650
3651impl ToOffsetUtf16 for usize {
3652    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3653        snapshot.offset_to_offset_utf16(*self)
3654    }
3655}
3656
3657impl ToPoint for usize {
3658    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3659        snapshot.offset_to_point(*self)
3660    }
3661}
3662
3663impl ToPoint for Point {
3664    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3665        *self
3666    }
3667}
3668
3669impl ToPointUtf16 for usize {
3670    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3671        snapshot.offset_to_point_utf16(*self)
3672    }
3673}
3674
3675impl ToPointUtf16 for Point {
3676    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3677        snapshot.point_to_point_utf16(*self)
3678    }
3679}
3680
3681impl ToPointUtf16 for PointUtf16 {
3682    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3683        *self
3684    }
3685}
3686
3687fn build_excerpt_ranges<T>(
3688    buffer: &BufferSnapshot,
3689    ranges: &[Range<T>],
3690    context_line_count: u32,
3691) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3692where
3693    T: text::ToPoint,
3694{
3695    let max_point = buffer.max_point();
3696    let mut range_counts = Vec::new();
3697    let mut excerpt_ranges = Vec::new();
3698    let mut range_iter = ranges
3699        .iter()
3700        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3701        .peekable();
3702    while let Some(range) = range_iter.next() {
3703        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3704        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3705        let mut ranges_in_excerpt = 1;
3706
3707        while let Some(next_range) = range_iter.peek() {
3708            if next_range.start.row <= excerpt_end.row + context_line_count {
3709                excerpt_end =
3710                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3711                ranges_in_excerpt += 1;
3712                range_iter.next();
3713            } else {
3714                break;
3715            }
3716        }
3717
3718        excerpt_ranges.push(ExcerptRange {
3719            context: excerpt_start..excerpt_end,
3720            primary: Some(range),
3721        });
3722        range_counts.push(ranges_in_excerpt);
3723    }
3724
3725    (excerpt_ranges, range_counts)
3726}
3727
3728#[cfg(test)]
3729mod tests {
3730    use super::*;
3731    use futures::StreamExt;
3732    use gpui::{MutableAppContext, TestAppContext};
3733    use language::{Buffer, Rope};
3734    use rand::prelude::*;
3735    use settings::Settings;
3736    use std::{env, rc::Rc};
3737    use unindent::Unindent;
3738
3739    use util::test::sample_text;
3740
3741    #[gpui::test]
3742    fn test_singleton(cx: &mut MutableAppContext) {
3743        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3744        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3745
3746        let snapshot = multibuffer.read(cx).snapshot(cx);
3747        assert_eq!(snapshot.text(), buffer.read(cx).text());
3748
3749        assert_eq!(
3750            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3751            (0..buffer.read(cx).row_count())
3752                .map(Some)
3753                .collect::<Vec<_>>()
3754        );
3755
3756        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
3757        let snapshot = multibuffer.read(cx).snapshot(cx);
3758
3759        assert_eq!(snapshot.text(), buffer.read(cx).text());
3760        assert_eq!(
3761            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3762            (0..buffer.read(cx).row_count())
3763                .map(Some)
3764                .collect::<Vec<_>>()
3765        );
3766    }
3767
3768    #[gpui::test]
3769    fn test_remote(cx: &mut MutableAppContext) {
3770        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3771        let guest_buffer = cx.add_model(|cx| {
3772            let state = host_buffer.read(cx).to_proto();
3773            let ops = cx
3774                .background()
3775                .block(host_buffer.read(cx).serialize_ops(None, cx));
3776            let mut buffer = Buffer::from_proto(1, state, None).unwrap();
3777            buffer
3778                .apply_ops(
3779                    ops.into_iter()
3780                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
3781                    cx,
3782                )
3783                .unwrap();
3784            buffer
3785        });
3786        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3787        let snapshot = multibuffer.read(cx).snapshot(cx);
3788        assert_eq!(snapshot.text(), "a");
3789
3790        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
3791        let snapshot = multibuffer.read(cx).snapshot(cx);
3792        assert_eq!(snapshot.text(), "ab");
3793
3794        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
3795        let snapshot = multibuffer.read(cx).snapshot(cx);
3796        assert_eq!(snapshot.text(), "abc");
3797    }
3798
3799    #[gpui::test]
3800    fn test_excerpt_boundaries_and_clipping(cx: &mut MutableAppContext) {
3801        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3802        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3803        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3804
3805        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3806        multibuffer.update(cx, |_, cx| {
3807            let events = events.clone();
3808            cx.subscribe(&multibuffer, move |_, _, event, _| {
3809                if let Event::Edited = event {
3810                    events.borrow_mut().push(event.clone())
3811                }
3812            })
3813            .detach();
3814        });
3815
3816        let subscription = multibuffer.update(cx, |multibuffer, cx| {
3817            let subscription = multibuffer.subscribe();
3818            multibuffer.push_excerpts(
3819                buffer_1.clone(),
3820                [ExcerptRange {
3821                    context: Point::new(1, 2)..Point::new(2, 5),
3822                    primary: None,
3823                }],
3824                cx,
3825            );
3826            assert_eq!(
3827                subscription.consume().into_inner(),
3828                [Edit {
3829                    old: 0..0,
3830                    new: 0..10
3831                }]
3832            );
3833
3834            multibuffer.push_excerpts(
3835                buffer_1.clone(),
3836                [ExcerptRange {
3837                    context: Point::new(3, 3)..Point::new(4, 4),
3838                    primary: None,
3839                }],
3840                cx,
3841            );
3842            multibuffer.push_excerpts(
3843                buffer_2.clone(),
3844                [ExcerptRange {
3845                    context: Point::new(3, 1)..Point::new(3, 3),
3846                    primary: None,
3847                }],
3848                cx,
3849            );
3850            assert_eq!(
3851                subscription.consume().into_inner(),
3852                [Edit {
3853                    old: 10..10,
3854                    new: 10..22
3855                }]
3856            );
3857
3858            subscription
3859        });
3860
3861        // Adding excerpts emits an edited event.
3862        assert_eq!(
3863            events.borrow().as_slice(),
3864            &[Event::Edited, Event::Edited, Event::Edited]
3865        );
3866
3867        let snapshot = multibuffer.read(cx).snapshot(cx);
3868        assert_eq!(
3869            snapshot.text(),
3870            concat!(
3871                "bbbb\n",  // Preserve newlines
3872                "ccccc\n", //
3873                "ddd\n",   //
3874                "eeee\n",  //
3875                "jj"       //
3876            )
3877        );
3878        assert_eq!(
3879            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3880            [Some(1), Some(2), Some(3), Some(4), Some(3)]
3881        );
3882        assert_eq!(
3883            snapshot.buffer_rows(2).collect::<Vec<_>>(),
3884            [Some(3), Some(4), Some(3)]
3885        );
3886        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3887        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3888
3889        assert_eq!(
3890            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3891            &[
3892                (0, "bbbb\nccccc".to_string(), true),
3893                (2, "ddd\neeee".to_string(), false),
3894                (4, "jj".to_string(), true),
3895            ]
3896        );
3897        assert_eq!(
3898            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3899            &[(0, "bbbb\nccccc".to_string(), true)]
3900        );
3901        assert_eq!(
3902            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3903            &[]
3904        );
3905        assert_eq!(
3906            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3907            &[]
3908        );
3909        assert_eq!(
3910            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3911            &[(2, "ddd\neeee".to_string(), false)]
3912        );
3913        assert_eq!(
3914            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3915            &[(2, "ddd\neeee".to_string(), false)]
3916        );
3917        assert_eq!(
3918            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3919            &[(2, "ddd\neeee".to_string(), false)]
3920        );
3921        assert_eq!(
3922            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3923            &[(4, "jj".to_string(), true)]
3924        );
3925        assert_eq!(
3926            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
3927            &[]
3928        );
3929
3930        buffer_1.update(cx, |buffer, cx| {
3931            let text = "\n";
3932            buffer.edit(
3933                [
3934                    (Point::new(0, 0)..Point::new(0, 0), text),
3935                    (Point::new(2, 1)..Point::new(2, 3), text),
3936                ],
3937                None,
3938                cx,
3939            );
3940        });
3941
3942        let snapshot = multibuffer.read(cx).snapshot(cx);
3943        assert_eq!(
3944            snapshot.text(),
3945            concat!(
3946                "bbbb\n", // Preserve newlines
3947                "c\n",    //
3948                "cc\n",   //
3949                "ddd\n",  //
3950                "eeee\n", //
3951                "jj"      //
3952            )
3953        );
3954
3955        assert_eq!(
3956            subscription.consume().into_inner(),
3957            [Edit {
3958                old: 6..8,
3959                new: 6..7
3960            }]
3961        );
3962
3963        let snapshot = multibuffer.read(cx).snapshot(cx);
3964        assert_eq!(
3965            snapshot.clip_point(Point::new(0, 5), Bias::Left),
3966            Point::new(0, 4)
3967        );
3968        assert_eq!(
3969            snapshot.clip_point(Point::new(0, 5), Bias::Right),
3970            Point::new(0, 4)
3971        );
3972        assert_eq!(
3973            snapshot.clip_point(Point::new(5, 1), Bias::Right),
3974            Point::new(5, 1)
3975        );
3976        assert_eq!(
3977            snapshot.clip_point(Point::new(5, 2), Bias::Right),
3978            Point::new(5, 2)
3979        );
3980        assert_eq!(
3981            snapshot.clip_point(Point::new(5, 3), Bias::Right),
3982            Point::new(5, 2)
3983        );
3984
3985        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
3986            let (buffer_2_excerpt_id, _) =
3987                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
3988            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
3989            multibuffer.snapshot(cx)
3990        });
3991
3992        assert_eq!(
3993            snapshot.text(),
3994            concat!(
3995                "bbbb\n", // Preserve newlines
3996                "c\n",    //
3997                "cc\n",   //
3998                "ddd\n",  //
3999                "eeee",   //
4000            )
4001        );
4002
4003        fn boundaries_in_range(
4004            range: Range<Point>,
4005            snapshot: &MultiBufferSnapshot,
4006        ) -> Vec<(u32, String, bool)> {
4007            snapshot
4008                .excerpt_boundaries_in_range(range)
4009                .map(|boundary| {
4010                    (
4011                        boundary.row,
4012                        boundary
4013                            .buffer
4014                            .text_for_range(boundary.range.context)
4015                            .collect::<String>(),
4016                        boundary.starts_new_buffer,
4017                    )
4018                })
4019                .collect::<Vec<_>>()
4020        }
4021    }
4022
4023    #[gpui::test]
4024    fn test_excerpt_events(cx: &mut MutableAppContext) {
4025        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4026        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4027
4028        let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4029        let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4030
4031        follower_multibuffer.update(cx, |_, cx| {
4032            cx.subscribe(&leader_multibuffer, |follower, _, event, cx| {
4033                match event.clone() {
4034                    Event::ExcerptsAdded {
4035                        buffer,
4036                        predecessor,
4037                        excerpts,
4038                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4039                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4040                    _ => {}
4041                }
4042            })
4043            .detach();
4044        });
4045
4046        leader_multibuffer.update(cx, |leader, cx| {
4047            leader.push_excerpts(
4048                buffer_1.clone(),
4049                [
4050                    ExcerptRange {
4051                        context: 0..8,
4052                        primary: None,
4053                    },
4054                    ExcerptRange {
4055                        context: 12..16,
4056                        primary: None,
4057                    },
4058                ],
4059                cx,
4060            );
4061            leader.insert_excerpts_after(
4062                leader.excerpt_ids()[0],
4063                buffer_2.clone(),
4064                [
4065                    ExcerptRange {
4066                        context: 0..5,
4067                        primary: None,
4068                    },
4069                    ExcerptRange {
4070                        context: 10..15,
4071                        primary: None,
4072                    },
4073                ],
4074                cx,
4075            )
4076        });
4077        assert_eq!(
4078            leader_multibuffer.read(cx).snapshot(cx).text(),
4079            follower_multibuffer.read(cx).snapshot(cx).text(),
4080        );
4081
4082        leader_multibuffer.update(cx, |leader, cx| {
4083            let excerpt_ids = leader.excerpt_ids();
4084            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4085        });
4086        assert_eq!(
4087            leader_multibuffer.read(cx).snapshot(cx).text(),
4088            follower_multibuffer.read(cx).snapshot(cx).text(),
4089        );
4090
4091        leader_multibuffer.update(cx, |leader, cx| {
4092            leader.clear(cx);
4093        });
4094        assert_eq!(
4095            leader_multibuffer.read(cx).snapshot(cx).text(),
4096            follower_multibuffer.read(cx).snapshot(cx).text(),
4097        );
4098    }
4099
4100    #[gpui::test]
4101    fn test_push_excerpts_with_context_lines(cx: &mut MutableAppContext) {
4102        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4103        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4104        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4105            multibuffer.push_excerpts_with_context_lines(
4106                buffer.clone(),
4107                vec![
4108                    Point::new(3, 2)..Point::new(4, 2),
4109                    Point::new(7, 1)..Point::new(7, 3),
4110                    Point::new(15, 0)..Point::new(15, 0),
4111                ],
4112                2,
4113                cx,
4114            )
4115        });
4116
4117        let snapshot = multibuffer.read(cx).snapshot(cx);
4118        assert_eq!(
4119            snapshot.text(),
4120            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4121        );
4122
4123        assert_eq!(
4124            anchor_ranges
4125                .iter()
4126                .map(|range| range.to_point(&snapshot))
4127                .collect::<Vec<_>>(),
4128            vec![
4129                Point::new(2, 2)..Point::new(3, 2),
4130                Point::new(6, 1)..Point::new(6, 3),
4131                Point::new(12, 0)..Point::new(12, 0)
4132            ]
4133        );
4134    }
4135
4136    #[gpui::test]
4137    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4138        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4139        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4140        let (task, anchor_ranges) = multibuffer.update(cx, |multibuffer, cx| {
4141            let snapshot = buffer.read(cx);
4142            let ranges = vec![
4143                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4144                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4145                snapshot.anchor_before(Point::new(15, 0))
4146                    ..snapshot.anchor_before(Point::new(15, 0)),
4147            ];
4148            multibuffer.stream_excerpts_with_context_lines(vec![(buffer.clone(), ranges)], 2, cx)
4149        });
4150
4151        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4152        // Ensure task is finished when stream completes.
4153        task.await;
4154
4155        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4156        assert_eq!(
4157            snapshot.text(),
4158            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4159        );
4160
4161        assert_eq!(
4162            anchor_ranges
4163                .iter()
4164                .map(|range| range.to_point(&snapshot))
4165                .collect::<Vec<_>>(),
4166            vec![
4167                Point::new(2, 2)..Point::new(3, 2),
4168                Point::new(6, 1)..Point::new(6, 3),
4169                Point::new(12, 0)..Point::new(12, 0)
4170            ]
4171        );
4172    }
4173
4174    #[gpui::test]
4175    fn test_empty_multibuffer(cx: &mut MutableAppContext) {
4176        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4177
4178        let snapshot = multibuffer.read(cx).snapshot(cx);
4179        assert_eq!(snapshot.text(), "");
4180        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4181        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4182    }
4183
4184    #[gpui::test]
4185    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
4186        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4187        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4188        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4189        buffer.update(cx, |buffer, cx| {
4190            buffer.edit([(0..0, "X")], None, cx);
4191            buffer.edit([(5..5, "Y")], None, cx);
4192        });
4193        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4194
4195        assert_eq!(old_snapshot.text(), "abcd");
4196        assert_eq!(new_snapshot.text(), "XabcdY");
4197
4198        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4199        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4200        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4201        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4202    }
4203
4204    #[gpui::test]
4205    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
4206        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4207        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4208        let multibuffer = cx.add_model(|cx| {
4209            let mut multibuffer = MultiBuffer::new(0);
4210            multibuffer.push_excerpts(
4211                buffer_1.clone(),
4212                [ExcerptRange {
4213                    context: 0..4,
4214                    primary: None,
4215                }],
4216                cx,
4217            );
4218            multibuffer.push_excerpts(
4219                buffer_2.clone(),
4220                [ExcerptRange {
4221                    context: 0..5,
4222                    primary: None,
4223                }],
4224                cx,
4225            );
4226            multibuffer
4227        });
4228        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4229
4230        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4231        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4232        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4233        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4234        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4235        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4236
4237        buffer_1.update(cx, |buffer, cx| {
4238            buffer.edit([(0..0, "W")], None, cx);
4239            buffer.edit([(5..5, "X")], None, cx);
4240        });
4241        buffer_2.update(cx, |buffer, cx| {
4242            buffer.edit([(0..0, "Y")], None, cx);
4243            buffer.edit([(6..6, "Z")], None, cx);
4244        });
4245        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4246
4247        assert_eq!(old_snapshot.text(), "abcd\nefghi");
4248        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4249
4250        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4251        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4252        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4253        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4254        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4255        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4256        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4257        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4258        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4259        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4260    }
4261
4262    #[gpui::test]
4263    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut MutableAppContext) {
4264        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4265        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4266        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4267
4268        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4269        // Add an excerpt from buffer 1 that spans this new insertion.
4270        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4271        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4272            multibuffer
4273                .push_excerpts(
4274                    buffer_1.clone(),
4275                    [ExcerptRange {
4276                        context: 0..7,
4277                        primary: None,
4278                    }],
4279                    cx,
4280                )
4281                .pop()
4282                .unwrap()
4283        });
4284
4285        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4286        assert_eq!(snapshot_1.text(), "abcd123");
4287
4288        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4289        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4290            multibuffer.remove_excerpts([excerpt_id_1], cx);
4291            let mut ids = multibuffer
4292                .push_excerpts(
4293                    buffer_2.clone(),
4294                    [
4295                        ExcerptRange {
4296                            context: 0..4,
4297                            primary: None,
4298                        },
4299                        ExcerptRange {
4300                            context: 6..10,
4301                            primary: None,
4302                        },
4303                        ExcerptRange {
4304                            context: 12..16,
4305                            primary: None,
4306                        },
4307                    ],
4308                    cx,
4309                )
4310                .into_iter();
4311            (ids.next().unwrap(), ids.next().unwrap())
4312        });
4313        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4314        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4315
4316        // The old excerpt id doesn't get reused.
4317        assert_ne!(excerpt_id_2, excerpt_id_1);
4318
4319        // Resolve some anchors from the previous snapshot in the new snapshot.
4320        // The current excerpts are from a different buffer, so we don't attempt to
4321        // resolve the old text anchor in the new buffer.
4322        assert_eq!(
4323            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4324            0
4325        );
4326        assert_eq!(
4327            snapshot_2.summaries_for_anchors::<usize, _>(&[
4328                snapshot_1.anchor_before(2),
4329                snapshot_1.anchor_after(3)
4330            ]),
4331            vec![0, 0]
4332        );
4333
4334        // Refresh anchors from the old snapshot. The return value indicates that both
4335        // anchors lost their original excerpt.
4336        let refresh =
4337            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4338        assert_eq!(
4339            refresh,
4340            &[
4341                (0, snapshot_2.anchor_before(0), false),
4342                (1, snapshot_2.anchor_after(0), false),
4343            ]
4344        );
4345
4346        // Replace the middle excerpt with a smaller excerpt in buffer 2,
4347        // that intersects the old excerpt.
4348        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4349            multibuffer.remove_excerpts([excerpt_id_3], cx);
4350            multibuffer
4351                .insert_excerpts_after(
4352                    excerpt_id_2,
4353                    buffer_2.clone(),
4354                    [ExcerptRange {
4355                        context: 5..8,
4356                        primary: None,
4357                    }],
4358                    cx,
4359                )
4360                .pop()
4361                .unwrap()
4362        });
4363
4364        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4365        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4366        assert_ne!(excerpt_id_5, excerpt_id_3);
4367
4368        // Resolve some anchors from the previous snapshot in the new snapshot.
4369        // The third anchor can't be resolved, since its excerpt has been removed,
4370        // so it resolves to the same position as its predecessor.
4371        let anchors = [
4372            snapshot_2.anchor_before(0),
4373            snapshot_2.anchor_after(2),
4374            snapshot_2.anchor_after(6),
4375            snapshot_2.anchor_after(14),
4376        ];
4377        assert_eq!(
4378            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4379            &[0, 2, 9, 13]
4380        );
4381
4382        let new_anchors = snapshot_3.refresh_anchors(&anchors);
4383        assert_eq!(
4384            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4385            &[(0, true), (1, true), (2, true), (3, true)]
4386        );
4387        assert_eq!(
4388            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4389            &[0, 2, 7, 13]
4390        );
4391    }
4392
4393    #[gpui::test]
4394    async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4395        use git::diff::DiffHunkStatus;
4396
4397        // buffer has two modified hunks with two rows each
4398        let buffer_1 = cx.add_model(|cx| {
4399            let mut buffer = Buffer::new(
4400                0,
4401                "
4402                1.zero
4403                1.ONE
4404                1.TWO
4405                1.three
4406                1.FOUR
4407                1.FIVE
4408                1.six
4409            "
4410                .unindent(),
4411                cx,
4412            );
4413            buffer.set_diff_base(
4414                Some(
4415                    "
4416                1.zero
4417                1.one
4418                1.two
4419                1.three
4420                1.four
4421                1.five
4422                1.six
4423            "
4424                    .unindent(),
4425                ),
4426                cx,
4427            );
4428            buffer
4429        });
4430
4431        // buffer has a deletion hunk and an insertion hunk
4432        let buffer_2 = cx.add_model(|cx| {
4433            let mut buffer = Buffer::new(
4434                0,
4435                "
4436                2.zero
4437                2.one
4438                2.two
4439                2.three
4440                2.four
4441                2.five
4442                2.six
4443            "
4444                .unindent(),
4445                cx,
4446            );
4447            buffer.set_diff_base(
4448                Some(
4449                    "
4450                2.zero
4451                2.one
4452                2.one-and-a-half
4453                2.two
4454                2.three
4455                2.four
4456                2.six
4457            "
4458                    .unindent(),
4459                ),
4460                cx,
4461            );
4462            buffer
4463        });
4464
4465        cx.foreground().run_until_parked();
4466
4467        let multibuffer = cx.add_model(|cx| {
4468            let mut multibuffer = MultiBuffer::new(0);
4469            multibuffer.push_excerpts(
4470                buffer_1.clone(),
4471                [
4472                    // excerpt ends in the middle of a modified hunk
4473                    ExcerptRange {
4474                        context: Point::new(0, 0)..Point::new(1, 5),
4475                        primary: Default::default(),
4476                    },
4477                    // excerpt begins in the middle of a modified hunk
4478                    ExcerptRange {
4479                        context: Point::new(5, 0)..Point::new(6, 5),
4480                        primary: Default::default(),
4481                    },
4482                ],
4483                cx,
4484            );
4485            multibuffer.push_excerpts(
4486                buffer_2.clone(),
4487                [
4488                    // excerpt ends at a deletion
4489                    ExcerptRange {
4490                        context: Point::new(0, 0)..Point::new(1, 5),
4491                        primary: Default::default(),
4492                    },
4493                    // excerpt starts at a deletion
4494                    ExcerptRange {
4495                        context: Point::new(2, 0)..Point::new(2, 5),
4496                        primary: Default::default(),
4497                    },
4498                    // excerpt fully contains a deletion hunk
4499                    ExcerptRange {
4500                        context: Point::new(1, 0)..Point::new(2, 5),
4501                        primary: Default::default(),
4502                    },
4503                    // excerpt fully contains an insertion hunk
4504                    ExcerptRange {
4505                        context: Point::new(4, 0)..Point::new(6, 5),
4506                        primary: Default::default(),
4507                    },
4508                ],
4509                cx,
4510            );
4511            multibuffer
4512        });
4513
4514        let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4515
4516        assert_eq!(
4517            snapshot.text(),
4518            "
4519                1.zero
4520                1.ONE
4521                1.FIVE
4522                1.six
4523                2.zero
4524                2.one
4525                2.two
4526                2.one
4527                2.two
4528                2.four
4529                2.five
4530                2.six"
4531                .unindent()
4532        );
4533
4534        let expected = [
4535            (DiffHunkStatus::Modified, 1..2),
4536            (DiffHunkStatus::Modified, 2..3),
4537            //TODO: Define better when and where removed hunks show up at range extremities
4538            (DiffHunkStatus::Removed, 6..6),
4539            (DiffHunkStatus::Removed, 8..8),
4540            (DiffHunkStatus::Added, 10..11),
4541        ];
4542
4543        assert_eq!(
4544            snapshot
4545                .git_diff_hunks_in_range(0..12, false)
4546                .map(|hunk| (hunk.status(), hunk.buffer_range))
4547                .collect::<Vec<_>>(),
4548            &expected,
4549        );
4550
4551        assert_eq!(
4552            snapshot
4553                .git_diff_hunks_in_range(0..12, true)
4554                .map(|hunk| (hunk.status(), hunk.buffer_range))
4555                .collect::<Vec<_>>(),
4556            expected
4557                .iter()
4558                .rev()
4559                .cloned()
4560                .collect::<Vec<_>>()
4561                .as_slice(),
4562        );
4563    }
4564
4565    #[gpui::test(iterations = 100)]
4566    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
4567        let operations = env::var("OPERATIONS")
4568            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4569            .unwrap_or(10);
4570
4571        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4572        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4573        let mut excerpt_ids = Vec::<ExcerptId>::new();
4574        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4575        let mut anchors = Vec::new();
4576        let mut old_versions = Vec::new();
4577
4578        for _ in 0..operations {
4579            match rng.gen_range(0..100) {
4580                0..=19 if !buffers.is_empty() => {
4581                    let buffer = buffers.choose(&mut rng).unwrap();
4582                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4583                }
4584                20..=29 if !expected_excerpts.is_empty() => {
4585                    let mut ids_to_remove = vec![];
4586                    for _ in 0..rng.gen_range(1..=3) {
4587                        if expected_excerpts.is_empty() {
4588                            break;
4589                        }
4590
4591                        let ix = rng.gen_range(0..expected_excerpts.len());
4592                        ids_to_remove.push(excerpt_ids.remove(ix));
4593                        let (buffer, range) = expected_excerpts.remove(ix);
4594                        let buffer = buffer.read(cx);
4595                        log::info!(
4596                            "Removing excerpt {}: {:?}",
4597                            ix,
4598                            buffer
4599                                .text_for_range(range.to_offset(buffer))
4600                                .collect::<String>(),
4601                        );
4602                    }
4603                    let snapshot = multibuffer.read(cx).read(cx);
4604                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4605                    drop(snapshot);
4606                    multibuffer.update(cx, |multibuffer, cx| {
4607                        multibuffer.remove_excerpts(ids_to_remove, cx)
4608                    });
4609                }
4610                30..=39 if !expected_excerpts.is_empty() => {
4611                    let multibuffer = multibuffer.read(cx).read(cx);
4612                    let offset =
4613                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4614                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4615                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4616                    anchors.push(multibuffer.anchor_at(offset, bias));
4617                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4618                }
4619                40..=44 if !anchors.is_empty() => {
4620                    let multibuffer = multibuffer.read(cx).read(cx);
4621                    let prev_len = anchors.len();
4622                    anchors = multibuffer
4623                        .refresh_anchors(&anchors)
4624                        .into_iter()
4625                        .map(|a| a.1)
4626                        .collect();
4627
4628                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4629                    // overshoot its boundaries.
4630                    assert_eq!(anchors.len(), prev_len);
4631                    for anchor in &anchors {
4632                        if anchor.excerpt_id == ExcerptId::min()
4633                            || anchor.excerpt_id == ExcerptId::max()
4634                        {
4635                            continue;
4636                        }
4637
4638                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4639                        assert_eq!(excerpt.id, anchor.excerpt_id);
4640                        assert!(excerpt.contains(anchor));
4641                    }
4642                }
4643                _ => {
4644                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4645                        let base_text = util::RandomCharIter::new(&mut rng)
4646                            .take(10)
4647                            .collect::<String>();
4648                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4649                        buffers.last().unwrap()
4650                    } else {
4651                        buffers.choose(&mut rng).unwrap()
4652                    };
4653
4654                    let buffer = buffer_handle.read(cx);
4655                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4656                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4657                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4658                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4659                    let prev_excerpt_id = excerpt_ids
4660                        .get(prev_excerpt_ix)
4661                        .cloned()
4662                        .unwrap_or_else(ExcerptId::max);
4663                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4664
4665                    log::info!(
4666                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4667                        excerpt_ix,
4668                        expected_excerpts.len(),
4669                        buffer_handle.id(),
4670                        buffer.text(),
4671                        start_ix..end_ix,
4672                        &buffer.text()[start_ix..end_ix]
4673                    );
4674
4675                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4676                        multibuffer
4677                            .insert_excerpts_after(
4678                                prev_excerpt_id,
4679                                buffer_handle.clone(),
4680                                [ExcerptRange {
4681                                    context: start_ix..end_ix,
4682                                    primary: None,
4683                                }],
4684                                cx,
4685                            )
4686                            .pop()
4687                            .unwrap()
4688                    });
4689
4690                    excerpt_ids.insert(excerpt_ix, excerpt_id);
4691                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
4692                }
4693            }
4694
4695            if rng.gen_bool(0.3) {
4696                multibuffer.update(cx, |multibuffer, cx| {
4697                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
4698                })
4699            }
4700
4701            let snapshot = multibuffer.read(cx).snapshot(cx);
4702
4703            let mut excerpt_starts = Vec::new();
4704            let mut expected_text = String::new();
4705            let mut expected_buffer_rows = Vec::new();
4706            for (buffer, range) in &expected_excerpts {
4707                let buffer = buffer.read(cx);
4708                let buffer_range = range.to_offset(buffer);
4709
4710                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
4711                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
4712                expected_text.push('\n');
4713
4714                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
4715                    ..=buffer.offset_to_point(buffer_range.end).row;
4716                for row in buffer_row_range {
4717                    expected_buffer_rows.push(Some(row));
4718                }
4719            }
4720            // Remove final trailing newline.
4721            if !expected_excerpts.is_empty() {
4722                expected_text.pop();
4723            }
4724
4725            // Always report one buffer row
4726            if expected_buffer_rows.is_empty() {
4727                expected_buffer_rows.push(Some(0));
4728            }
4729
4730            assert_eq!(snapshot.text(), expected_text);
4731            log::info!("MultiBuffer text: {:?}", expected_text);
4732
4733            assert_eq!(
4734                snapshot.buffer_rows(0).collect::<Vec<_>>(),
4735                expected_buffer_rows,
4736            );
4737
4738            for _ in 0..5 {
4739                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
4740                assert_eq!(
4741                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
4742                    &expected_buffer_rows[start_row..],
4743                    "buffer_rows({})",
4744                    start_row
4745                );
4746            }
4747
4748            assert_eq!(
4749                snapshot.max_buffer_row(),
4750                expected_buffer_rows.into_iter().flatten().max().unwrap()
4751            );
4752
4753            let mut excerpt_starts = excerpt_starts.into_iter();
4754            for (buffer, range) in &expected_excerpts {
4755                let buffer_id = buffer.id();
4756                let buffer = buffer.read(cx);
4757                let buffer_range = range.to_offset(buffer);
4758                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
4759                let buffer_start_point_utf16 =
4760                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
4761
4762                let excerpt_start = excerpt_starts.next().unwrap();
4763                let mut offset = excerpt_start.len;
4764                let mut buffer_offset = buffer_range.start;
4765                let mut point = excerpt_start.lines;
4766                let mut buffer_point = buffer_start_point;
4767                let mut point_utf16 = excerpt_start.lines_utf16();
4768                let mut buffer_point_utf16 = buffer_start_point_utf16;
4769                for ch in buffer
4770                    .snapshot()
4771                    .chunks(buffer_range.clone(), false)
4772                    .flat_map(|c| c.text.chars())
4773                {
4774                    for _ in 0..ch.len_utf8() {
4775                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
4776                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
4777                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
4778                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
4779                        assert_eq!(
4780                            left_offset,
4781                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
4782                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
4783                            offset,
4784                            buffer_id,
4785                            buffer_offset,
4786                        );
4787                        assert_eq!(
4788                            right_offset,
4789                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
4790                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
4791                            offset,
4792                            buffer_id,
4793                            buffer_offset,
4794                        );
4795
4796                        let left_point = snapshot.clip_point(point, Bias::Left);
4797                        let right_point = snapshot.clip_point(point, Bias::Right);
4798                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
4799                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
4800                        assert_eq!(
4801                            left_point,
4802                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
4803                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
4804                            point,
4805                            buffer_id,
4806                            buffer_point,
4807                        );
4808                        assert_eq!(
4809                            right_point,
4810                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
4811                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
4812                            point,
4813                            buffer_id,
4814                            buffer_point,
4815                        );
4816
4817                        assert_eq!(
4818                            snapshot.point_to_offset(left_point),
4819                            left_offset,
4820                            "point_to_offset({:?})",
4821                            left_point,
4822                        );
4823                        assert_eq!(
4824                            snapshot.offset_to_point(left_offset),
4825                            left_point,
4826                            "offset_to_point({:?})",
4827                            left_offset,
4828                        );
4829
4830                        offset += 1;
4831                        buffer_offset += 1;
4832                        if ch == '\n' {
4833                            point += Point::new(1, 0);
4834                            buffer_point += Point::new(1, 0);
4835                        } else {
4836                            point += Point::new(0, 1);
4837                            buffer_point += Point::new(0, 1);
4838                        }
4839                    }
4840
4841                    for _ in 0..ch.len_utf16() {
4842                        let left_point_utf16 =
4843                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
4844                        let right_point_utf16 =
4845                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
4846                        let buffer_left_point_utf16 =
4847                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
4848                        let buffer_right_point_utf16 =
4849                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
4850                        assert_eq!(
4851                            left_point_utf16,
4852                            excerpt_start.lines_utf16()
4853                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
4854                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4855                            point_utf16,
4856                            buffer_id,
4857                            buffer_point_utf16,
4858                        );
4859                        assert_eq!(
4860                            right_point_utf16,
4861                            excerpt_start.lines_utf16()
4862                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
4863                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4864                            point_utf16,
4865                            buffer_id,
4866                            buffer_point_utf16,
4867                        );
4868
4869                        if ch == '\n' {
4870                            point_utf16 += PointUtf16::new(1, 0);
4871                            buffer_point_utf16 += PointUtf16::new(1, 0);
4872                        } else {
4873                            point_utf16 += PointUtf16::new(0, 1);
4874                            buffer_point_utf16 += PointUtf16::new(0, 1);
4875                        }
4876                    }
4877                }
4878            }
4879
4880            for (row, line) in expected_text.split('\n').enumerate() {
4881                assert_eq!(
4882                    snapshot.line_len(row as u32),
4883                    line.len() as u32,
4884                    "line_len({}).",
4885                    row
4886                );
4887            }
4888
4889            let text_rope = Rope::from(expected_text.as_str());
4890            for _ in 0..10 {
4891                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4892                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4893
4894                let text_for_range = snapshot
4895                    .text_for_range(start_ix..end_ix)
4896                    .collect::<String>();
4897                assert_eq!(
4898                    text_for_range,
4899                    &expected_text[start_ix..end_ix],
4900                    "incorrect text for range {:?}",
4901                    start_ix..end_ix
4902                );
4903
4904                let excerpted_buffer_ranges = multibuffer
4905                    .read(cx)
4906                    .range_to_buffer_ranges(start_ix..end_ix, cx);
4907                let excerpted_buffers_text = excerpted_buffer_ranges
4908                    .into_iter()
4909                    .map(|(buffer, buffer_range)| {
4910                        buffer
4911                            .read(cx)
4912                            .text_for_range(buffer_range)
4913                            .collect::<String>()
4914                    })
4915                    .collect::<Vec<_>>()
4916                    .join("\n");
4917                assert_eq!(excerpted_buffers_text, text_for_range);
4918
4919                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
4920                assert_eq!(
4921                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
4922                    expected_summary,
4923                    "incorrect summary for range {:?}",
4924                    start_ix..end_ix
4925                );
4926            }
4927
4928            // Anchor resolution
4929            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
4930            assert_eq!(anchors.len(), summaries.len());
4931            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
4932                assert!(resolved_offset <= snapshot.len());
4933                assert_eq!(
4934                    snapshot.summary_for_anchor::<usize>(anchor),
4935                    resolved_offset
4936                );
4937            }
4938
4939            for _ in 0..10 {
4940                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4941                assert_eq!(
4942                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
4943                    expected_text[..end_ix].chars().rev().collect::<String>(),
4944                );
4945            }
4946
4947            for _ in 0..10 {
4948                let end_ix = rng.gen_range(0..=text_rope.len());
4949                let start_ix = rng.gen_range(0..=end_ix);
4950                assert_eq!(
4951                    snapshot
4952                        .bytes_in_range(start_ix..end_ix)
4953                        .flatten()
4954                        .copied()
4955                        .collect::<Vec<_>>(),
4956                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
4957                    "bytes_in_range({:?})",
4958                    start_ix..end_ix,
4959                );
4960            }
4961        }
4962
4963        let snapshot = multibuffer.read(cx).snapshot(cx);
4964        for (old_snapshot, subscription) in old_versions {
4965            let edits = subscription.consume().into_inner();
4966
4967            log::info!(
4968                "applying subscription edits to old text: {:?}: {:?}",
4969                old_snapshot.text(),
4970                edits,
4971            );
4972
4973            let mut text = old_snapshot.text();
4974            for edit in edits {
4975                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
4976                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
4977            }
4978            assert_eq!(text.to_string(), snapshot.text());
4979        }
4980    }
4981
4982    #[gpui::test]
4983    fn test_history(cx: &mut MutableAppContext) {
4984        cx.set_global(Settings::test(cx));
4985        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
4986        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
4987        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4988        let group_interval = multibuffer.read(cx).history.group_interval;
4989        multibuffer.update(cx, |multibuffer, cx| {
4990            multibuffer.push_excerpts(
4991                buffer_1.clone(),
4992                [ExcerptRange {
4993                    context: 0..buffer_1.read(cx).len(),
4994                    primary: None,
4995                }],
4996                cx,
4997            );
4998            multibuffer.push_excerpts(
4999                buffer_2.clone(),
5000                [ExcerptRange {
5001                    context: 0..buffer_2.read(cx).len(),
5002                    primary: None,
5003                }],
5004                cx,
5005            );
5006        });
5007
5008        let mut now = Instant::now();
5009
5010        multibuffer.update(cx, |multibuffer, cx| {
5011            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5012            multibuffer.edit(
5013                [
5014                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5015                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5016                ],
5017                None,
5018                cx,
5019            );
5020            multibuffer.edit(
5021                [
5022                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5023                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5024                ],
5025                None,
5026                cx,
5027            );
5028            multibuffer.end_transaction_at(now, cx);
5029            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5030
5031            // Edit buffer 1 through the multibuffer
5032            now += 2 * group_interval;
5033            multibuffer.start_transaction_at(now, cx);
5034            multibuffer.edit([(2..2, "C")], None, cx);
5035            multibuffer.end_transaction_at(now, cx);
5036            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5037
5038            // Edit buffer 1 independently
5039            buffer_1.update(cx, |buffer_1, cx| {
5040                buffer_1.start_transaction_at(now);
5041                buffer_1.edit([(3..3, "D")], None, cx);
5042                buffer_1.end_transaction_at(now, cx);
5043
5044                now += 2 * group_interval;
5045                buffer_1.start_transaction_at(now);
5046                buffer_1.edit([(4..4, "E")], None, cx);
5047                buffer_1.end_transaction_at(now, cx);
5048            });
5049            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5050
5051            // An undo in the multibuffer undoes the multibuffer transaction
5052            // and also any individual buffer edits that have occured since
5053            // that transaction.
5054            multibuffer.undo(cx);
5055            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5056
5057            multibuffer.undo(cx);
5058            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5059
5060            multibuffer.redo(cx);
5061            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5062
5063            multibuffer.redo(cx);
5064            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5065
5066            // Undo buffer 2 independently.
5067            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5068            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5069
5070            // An undo in the multibuffer undoes the components of the
5071            // the last multibuffer transaction that are not already undone.
5072            multibuffer.undo(cx);
5073            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5074
5075            multibuffer.undo(cx);
5076            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5077
5078            multibuffer.redo(cx);
5079            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5080
5081            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5082            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5083
5084            // Redo stack gets cleared after an edit.
5085            now += 2 * group_interval;
5086            multibuffer.start_transaction_at(now, cx);
5087            multibuffer.edit([(0..0, "X")], None, cx);
5088            multibuffer.end_transaction_at(now, cx);
5089            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5090            multibuffer.redo(cx);
5091            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5092            multibuffer.undo(cx);
5093            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5094            multibuffer.undo(cx);
5095            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5096
5097            // Transactions can be grouped manually.
5098            multibuffer.redo(cx);
5099            multibuffer.redo(cx);
5100            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5101            multibuffer.group_until_transaction(transaction_1, cx);
5102            multibuffer.undo(cx);
5103            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5104            multibuffer.redo(cx);
5105            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5106        });
5107    }
5108}