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::AppContext) -> 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(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> ModelHandle<Self> {
1498        cx.add_model(|cx| {
1499            let mut multibuffer = MultiBuffer::new(0);
1500            let mutation_count = rng.gen_range(1..=5);
1501            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1502            multibuffer
1503        })
1504    }
1505
1506    pub fn randomly_edit(
1507        &mut self,
1508        rng: &mut impl rand::Rng,
1509        edit_count: usize,
1510        cx: &mut ModelContext<Self>,
1511    ) {
1512        use util::RandomCharIter;
1513
1514        let snapshot = self.read(cx);
1515        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1516        let mut last_end = None;
1517        for _ in 0..edit_count {
1518            if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1519                break;
1520            }
1521
1522            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1523            let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1524            let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1525            last_end = Some(end);
1526
1527            let mut range = start..end;
1528            if rng.gen_bool(0.2) {
1529                mem::swap(&mut range.start, &mut range.end);
1530            }
1531
1532            let new_text_len = rng.gen_range(0..10);
1533            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1534
1535            edits.push((range, new_text.into()));
1536        }
1537        log::info!("mutating multi-buffer with {:?}", edits);
1538        drop(snapshot);
1539
1540        self.edit(edits, None, cx);
1541    }
1542
1543    pub fn randomly_edit_excerpts(
1544        &mut self,
1545        rng: &mut impl rand::Rng,
1546        mutation_count: usize,
1547        cx: &mut ModelContext<Self>,
1548    ) {
1549        use rand::prelude::*;
1550        use std::env;
1551        use util::RandomCharIter;
1552
1553        let max_excerpts = env::var("MAX_EXCERPTS")
1554            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1555            .unwrap_or(5);
1556
1557        let mut buffers = Vec::new();
1558        for _ in 0..mutation_count {
1559            if rng.gen_bool(0.05) {
1560                log::info!("Clearing multi-buffer");
1561                self.clear(cx);
1562                continue;
1563            }
1564
1565            let excerpt_ids = self.excerpt_ids();
1566            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1567                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1568                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1569                    buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1570                    let buffer = buffers.last().unwrap();
1571                    log::info!(
1572                        "Creating new buffer {} with text: {:?}",
1573                        buffer.id(),
1574                        buffer.read(cx).text()
1575                    );
1576                    buffers.last().unwrap().clone()
1577                } else {
1578                    self.buffers
1579                        .borrow()
1580                        .values()
1581                        .choose(rng)
1582                        .unwrap()
1583                        .buffer
1584                        .clone()
1585                };
1586
1587                let buffer = buffer_handle.read(cx);
1588                let buffer_text = buffer.text();
1589                let ranges = (0..rng.gen_range(0..5))
1590                    .map(|_| {
1591                        let end_ix =
1592                            buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1593                        let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1594                        ExcerptRange {
1595                            context: start_ix..end_ix,
1596                            primary: None,
1597                        }
1598                    })
1599                    .collect::<Vec<_>>();
1600                log::info!(
1601                    "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1602                    buffer_handle.id(),
1603                    ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1604                    ranges
1605                        .iter()
1606                        .map(|r| &buffer_text[r.context.clone()])
1607                        .collect::<Vec<_>>()
1608                );
1609
1610                let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1611                log::info!("Inserted with ids: {:?}", excerpt_id);
1612            } else {
1613                let remove_count = rng.gen_range(1..=excerpt_ids.len());
1614                let mut excerpts_to_remove = excerpt_ids
1615                    .choose_multiple(rng, remove_count)
1616                    .cloned()
1617                    .collect::<Vec<_>>();
1618                let snapshot = self.snapshot.borrow();
1619                excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &*snapshot));
1620                drop(snapshot);
1621                log::info!("Removing excerpts {:?}", excerpts_to_remove);
1622                self.remove_excerpts(excerpts_to_remove, cx);
1623            }
1624        }
1625    }
1626
1627    pub fn randomly_mutate(
1628        &mut self,
1629        rng: &mut impl rand::Rng,
1630        mutation_count: usize,
1631        cx: &mut ModelContext<Self>,
1632    ) {
1633        use rand::prelude::*;
1634
1635        if rng.gen_bool(0.7) || self.singleton {
1636            let buffer = self
1637                .buffers
1638                .borrow()
1639                .values()
1640                .choose(rng)
1641                .map(|state| state.buffer.clone());
1642
1643            if let Some(buffer) = buffer {
1644                buffer.update(cx, |buffer, cx| {
1645                    if rng.gen() {
1646                        buffer.randomly_edit(rng, mutation_count, cx);
1647                    } else {
1648                        buffer.randomly_undo_redo(rng, cx);
1649                    }
1650                });
1651            } else {
1652                self.randomly_edit(rng, mutation_count, cx);
1653            }
1654        } else {
1655            self.randomly_edit_excerpts(rng, mutation_count, cx);
1656        }
1657
1658        self.check_invariants(cx);
1659    }
1660
1661    fn check_invariants(&self, cx: &mut ModelContext<Self>) {
1662        let snapshot = self.read(cx);
1663        let excerpts = snapshot.excerpts.items(&());
1664        let excerpt_ids = snapshot.excerpt_ids.items(&());
1665
1666        for (ix, excerpt) in excerpts.iter().enumerate() {
1667            if ix == 0 {
1668                if excerpt.locator <= Locator::min() {
1669                    panic!("invalid first excerpt locator {:?}", excerpt.locator);
1670                }
1671            } else {
1672                if excerpt.locator <= excerpts[ix - 1].locator {
1673                    panic!("excerpts are out-of-order: {:?}", excerpts);
1674                }
1675            }
1676        }
1677
1678        for (ix, entry) in excerpt_ids.iter().enumerate() {
1679            if ix == 0 {
1680                if entry.id.cmp(&ExcerptId::min(), &*snapshot).is_le() {
1681                    panic!("invalid first excerpt id {:?}", entry.id);
1682                }
1683            } else {
1684                if entry.id <= excerpt_ids[ix - 1].id {
1685                    panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
1686                }
1687            }
1688        }
1689    }
1690}
1691
1692impl Entity for MultiBuffer {
1693    type Event = Event;
1694}
1695
1696impl MultiBufferSnapshot {
1697    pub fn text(&self) -> String {
1698        self.chunks(0..self.len(), false)
1699            .map(|chunk| chunk.text)
1700            .collect()
1701    }
1702
1703    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1704        let mut offset = position.to_offset(self);
1705        let mut cursor = self.excerpts.cursor::<usize>();
1706        cursor.seek(&offset, Bias::Left, &());
1707        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1708            let end_before_footer = cursor.start() + excerpt.text_summary.len;
1709            let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1710            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1711            excerpt.buffer.reversed_chunks_in_range(start..end)
1712        });
1713        iter::from_fn(move || {
1714            if offset == *cursor.start() {
1715                cursor.prev(&());
1716                let excerpt = cursor.item()?;
1717                excerpt_chunks = Some(
1718                    excerpt
1719                        .buffer
1720                        .reversed_chunks_in_range(excerpt.range.context.clone()),
1721                );
1722            }
1723
1724            let excerpt = cursor.item().unwrap();
1725            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1726                offset -= 1;
1727                Some("\n")
1728            } else {
1729                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1730                offset -= chunk.len();
1731                Some(chunk)
1732            }
1733        })
1734        .flat_map(|c| c.chars().rev())
1735    }
1736
1737    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1738        let offset = position.to_offset(self);
1739        self.text_for_range(offset..self.len())
1740            .flat_map(|chunk| chunk.chars())
1741    }
1742
1743    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
1744        self.chunks(range, false).map(|chunk| chunk.text)
1745    }
1746
1747    pub fn is_line_blank(&self, row: u32) -> bool {
1748        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1749            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1750    }
1751
1752    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1753    where
1754        T: ToOffset,
1755    {
1756        let position = position.to_offset(self);
1757        position == self.clip_offset(position, Bias::Left)
1758            && self
1759                .bytes_in_range(position..self.len())
1760                .flatten()
1761                .copied()
1762                .take(needle.len())
1763                .eq(needle.bytes())
1764    }
1765
1766    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1767        let mut start = start.to_offset(self);
1768        let mut end = start;
1769        let mut next_chars = self.chars_at(start).peekable();
1770        let mut prev_chars = self.reversed_chars_at(start).peekable();
1771        let word_kind = cmp::max(
1772            prev_chars.peek().copied().map(char_kind),
1773            next_chars.peek().copied().map(char_kind),
1774        );
1775
1776        for ch in prev_chars {
1777            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1778                start -= ch.len_utf8();
1779            } else {
1780                break;
1781            }
1782        }
1783
1784        for ch in next_chars {
1785            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1786                end += ch.len_utf8();
1787            } else {
1788                break;
1789            }
1790        }
1791
1792        (start..end, word_kind)
1793    }
1794
1795    pub fn as_singleton(&self) -> Option<(&ExcerptId, usize, &BufferSnapshot)> {
1796        if self.singleton {
1797            self.excerpts
1798                .iter()
1799                .next()
1800                .map(|e| (&e.id, e.buffer_id, &e.buffer))
1801        } else {
1802            None
1803        }
1804    }
1805
1806    pub fn len(&self) -> usize {
1807        self.excerpts.summary().text.len
1808    }
1809
1810    pub fn is_empty(&self) -> bool {
1811        self.excerpts.summary().text.len == 0
1812    }
1813
1814    pub fn max_buffer_row(&self) -> u32 {
1815        self.excerpts.summary().max_buffer_row
1816    }
1817
1818    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1819        if let Some((_, _, buffer)) = self.as_singleton() {
1820            return buffer.clip_offset(offset, bias);
1821        }
1822
1823        let mut cursor = self.excerpts.cursor::<usize>();
1824        cursor.seek(&offset, Bias::Right, &());
1825        let overshoot = if let Some(excerpt) = cursor.item() {
1826            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1827            let buffer_offset = excerpt
1828                .buffer
1829                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1830            buffer_offset.saturating_sub(excerpt_start)
1831        } else {
1832            0
1833        };
1834        cursor.start() + overshoot
1835    }
1836
1837    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1838        if let Some((_, _, buffer)) = self.as_singleton() {
1839            return buffer.clip_point(point, bias);
1840        }
1841
1842        let mut cursor = self.excerpts.cursor::<Point>();
1843        cursor.seek(&point, Bias::Right, &());
1844        let overshoot = if let Some(excerpt) = cursor.item() {
1845            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1846            let buffer_point = excerpt
1847                .buffer
1848                .clip_point(excerpt_start + (point - cursor.start()), bias);
1849            buffer_point.saturating_sub(excerpt_start)
1850        } else {
1851            Point::zero()
1852        };
1853        *cursor.start() + overshoot
1854    }
1855
1856    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
1857        if let Some((_, _, buffer)) = self.as_singleton() {
1858            return buffer.clip_offset_utf16(offset, bias);
1859        }
1860
1861        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
1862        cursor.seek(&offset, Bias::Right, &());
1863        let overshoot = if let Some(excerpt) = cursor.item() {
1864            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1865            let buffer_offset = excerpt
1866                .buffer
1867                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
1868            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
1869        } else {
1870            OffsetUtf16(0)
1871        };
1872        *cursor.start() + overshoot
1873    }
1874
1875    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
1876        if let Some((_, _, buffer)) = self.as_singleton() {
1877            return buffer.clip_point_utf16(point, bias);
1878        }
1879
1880        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1881        cursor.seek(&point.0, Bias::Right, &());
1882        let overshoot = if let Some(excerpt) = cursor.item() {
1883            let excerpt_start = excerpt
1884                .buffer
1885                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1886            let buffer_point = excerpt
1887                .buffer
1888                .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
1889            buffer_point.saturating_sub(excerpt_start)
1890        } else {
1891            PointUtf16::zero()
1892        };
1893        *cursor.start() + overshoot
1894    }
1895
1896    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
1897        let range = range.start.to_offset(self)..range.end.to_offset(self);
1898        let mut excerpts = self.excerpts.cursor::<usize>();
1899        excerpts.seek(&range.start, Bias::Right, &());
1900
1901        let mut chunk = &[][..];
1902        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1903            let mut excerpt_bytes = excerpt
1904                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1905            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1906            Some(excerpt_bytes)
1907        } else {
1908            None
1909        };
1910
1911        MultiBufferBytes {
1912            range,
1913            excerpts,
1914            excerpt_bytes,
1915            chunk,
1916        }
1917    }
1918
1919    pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
1920        let mut result = MultiBufferRows {
1921            buffer_row_range: 0..0,
1922            excerpts: self.excerpts.cursor(),
1923        };
1924        result.seek(start_row);
1925        result
1926    }
1927
1928    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
1929        let range = range.start.to_offset(self)..range.end.to_offset(self);
1930        let mut chunks = MultiBufferChunks {
1931            range: range.clone(),
1932            excerpts: self.excerpts.cursor(),
1933            excerpt_chunks: None,
1934            language_aware,
1935        };
1936        chunks.seek(range.start);
1937        chunks
1938    }
1939
1940    pub fn offset_to_point(&self, offset: usize) -> Point {
1941        if let Some((_, _, buffer)) = self.as_singleton() {
1942            return buffer.offset_to_point(offset);
1943        }
1944
1945        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1946        cursor.seek(&offset, Bias::Right, &());
1947        if let Some(excerpt) = cursor.item() {
1948            let (start_offset, start_point) = cursor.start();
1949            let overshoot = offset - start_offset;
1950            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1951            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1952            let buffer_point = excerpt
1953                .buffer
1954                .offset_to_point(excerpt_start_offset + overshoot);
1955            *start_point + (buffer_point - excerpt_start_point)
1956        } else {
1957            self.excerpts.summary().text.lines
1958        }
1959    }
1960
1961    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1962        if let Some((_, _, buffer)) = self.as_singleton() {
1963            return buffer.offset_to_point_utf16(offset);
1964        }
1965
1966        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1967        cursor.seek(&offset, Bias::Right, &());
1968        if let Some(excerpt) = cursor.item() {
1969            let (start_offset, start_point) = cursor.start();
1970            let overshoot = offset - start_offset;
1971            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1972            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1973            let buffer_point = excerpt
1974                .buffer
1975                .offset_to_point_utf16(excerpt_start_offset + overshoot);
1976            *start_point + (buffer_point - excerpt_start_point)
1977        } else {
1978            self.excerpts.summary().text.lines_utf16()
1979        }
1980    }
1981
1982    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1983        if let Some((_, _, buffer)) = self.as_singleton() {
1984            return buffer.point_to_point_utf16(point);
1985        }
1986
1987        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1988        cursor.seek(&point, Bias::Right, &());
1989        if let Some(excerpt) = cursor.item() {
1990            let (start_offset, start_point) = cursor.start();
1991            let overshoot = point - start_offset;
1992            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1993            let excerpt_start_point_utf16 =
1994                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1995            let buffer_point = excerpt
1996                .buffer
1997                .point_to_point_utf16(excerpt_start_point + overshoot);
1998            *start_point + (buffer_point - excerpt_start_point_utf16)
1999        } else {
2000            self.excerpts.summary().text.lines_utf16()
2001        }
2002    }
2003
2004    pub fn point_to_offset(&self, point: Point) -> usize {
2005        if let Some((_, _, buffer)) = self.as_singleton() {
2006            return buffer.point_to_offset(point);
2007        }
2008
2009        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2010        cursor.seek(&point, Bias::Right, &());
2011        if let Some(excerpt) = cursor.item() {
2012            let (start_point, start_offset) = cursor.start();
2013            let overshoot = point - start_point;
2014            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2015            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2016            let buffer_offset = excerpt
2017                .buffer
2018                .point_to_offset(excerpt_start_point + overshoot);
2019            *start_offset + buffer_offset - excerpt_start_offset
2020        } else {
2021            self.excerpts.summary().text.len
2022        }
2023    }
2024
2025    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2026        if let Some((_, _, buffer)) = self.as_singleton() {
2027            return buffer.offset_utf16_to_offset(offset_utf16);
2028        }
2029
2030        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2031        cursor.seek(&offset_utf16, Bias::Right, &());
2032        if let Some(excerpt) = cursor.item() {
2033            let (start_offset_utf16, start_offset) = cursor.start();
2034            let overshoot = offset_utf16 - start_offset_utf16;
2035            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2036            let excerpt_start_offset_utf16 =
2037                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2038            let buffer_offset = excerpt
2039                .buffer
2040                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2041            *start_offset + (buffer_offset - excerpt_start_offset)
2042        } else {
2043            self.excerpts.summary().text.len
2044        }
2045    }
2046
2047    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2048        if let Some((_, _, buffer)) = self.as_singleton() {
2049            return buffer.offset_to_offset_utf16(offset);
2050        }
2051
2052        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2053        cursor.seek(&offset, Bias::Right, &());
2054        if let Some(excerpt) = cursor.item() {
2055            let (start_offset, start_offset_utf16) = cursor.start();
2056            let overshoot = offset - start_offset;
2057            let excerpt_start_offset_utf16 =
2058                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2059            let excerpt_start_offset = excerpt
2060                .buffer
2061                .offset_utf16_to_offset(excerpt_start_offset_utf16);
2062            let buffer_offset_utf16 = excerpt
2063                .buffer
2064                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2065            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2066        } else {
2067            self.excerpts.summary().text.len_utf16
2068        }
2069    }
2070
2071    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2072        if let Some((_, _, buffer)) = self.as_singleton() {
2073            return buffer.point_utf16_to_offset(point);
2074        }
2075
2076        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2077        cursor.seek(&point, Bias::Right, &());
2078        if let Some(excerpt) = cursor.item() {
2079            let (start_point, start_offset) = cursor.start();
2080            let overshoot = point - start_point;
2081            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2082            let excerpt_start_point = excerpt
2083                .buffer
2084                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2085            let buffer_offset = excerpt
2086                .buffer
2087                .point_utf16_to_offset(excerpt_start_point + overshoot);
2088            *start_offset + (buffer_offset - excerpt_start_offset)
2089        } else {
2090            self.excerpts.summary().text.len
2091        }
2092    }
2093
2094    pub fn point_to_buffer_offset<T: ToOffset>(
2095        &self,
2096        point: T,
2097    ) -> Option<(&BufferSnapshot, usize)> {
2098        let offset = point.to_offset(&self);
2099        let mut cursor = self.excerpts.cursor::<usize>();
2100        cursor.seek(&offset, Bias::Right, &());
2101        if cursor.item().is_none() {
2102            cursor.prev(&());
2103        }
2104
2105        cursor.item().map(|excerpt| {
2106            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2107            let buffer_point = excerpt_start + offset - *cursor.start();
2108            (&excerpt.buffer, buffer_point)
2109        })
2110    }
2111
2112    pub fn suggested_indents(
2113        &self,
2114        rows: impl IntoIterator<Item = u32>,
2115        cx: &AppContext,
2116    ) -> BTreeMap<u32, IndentSize> {
2117        let mut result = BTreeMap::new();
2118
2119        let mut rows_for_excerpt = Vec::new();
2120        let mut cursor = self.excerpts.cursor::<Point>();
2121        let mut rows = rows.into_iter().peekable();
2122        let mut prev_row = u32::MAX;
2123        let mut prev_language_indent_size = IndentSize::default();
2124
2125        while let Some(row) = rows.next() {
2126            cursor.seek(&Point::new(row, 0), Bias::Right, &());
2127            let excerpt = match cursor.item() {
2128                Some(excerpt) => excerpt,
2129                _ => continue,
2130            };
2131
2132            // Retrieve the language and indent size once for each disjoint region being indented.
2133            let single_indent_size = if row.saturating_sub(1) == prev_row {
2134                prev_language_indent_size
2135            } else {
2136                excerpt
2137                    .buffer
2138                    .language_indent_size_at(Point::new(row, 0), cx)
2139            };
2140            prev_language_indent_size = single_indent_size;
2141            prev_row = row;
2142
2143            let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2144            let start_multibuffer_row = cursor.start().row;
2145
2146            rows_for_excerpt.push(row);
2147            while let Some(next_row) = rows.peek().copied() {
2148                if cursor.end(&()).row > next_row {
2149                    rows_for_excerpt.push(next_row);
2150                    rows.next();
2151                } else {
2152                    break;
2153                }
2154            }
2155
2156            let buffer_rows = rows_for_excerpt
2157                .drain(..)
2158                .map(|row| start_buffer_row + row - start_multibuffer_row);
2159            let buffer_indents = excerpt
2160                .buffer
2161                .suggested_indents(buffer_rows, single_indent_size);
2162            let multibuffer_indents = buffer_indents
2163                .into_iter()
2164                .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2165            result.extend(multibuffer_indents);
2166        }
2167
2168        result
2169    }
2170
2171    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2172        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2173            let mut size = buffer.indent_size_for_line(range.start.row);
2174            size.len = size
2175                .len
2176                .min(range.end.column)
2177                .saturating_sub(range.start.column);
2178            size
2179        } else {
2180            IndentSize::spaces(0)
2181        }
2182    }
2183
2184    pub fn line_len(&self, row: u32) -> u32 {
2185        if let Some((_, range)) = self.buffer_line_for_row(row) {
2186            range.end.column - range.start.column
2187        } else {
2188            0
2189        }
2190    }
2191
2192    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2193        let mut cursor = self.excerpts.cursor::<Point>();
2194        let point = Point::new(row, 0);
2195        cursor.seek(&point, Bias::Right, &());
2196        if cursor.item().is_none() && *cursor.start() == point {
2197            cursor.prev(&());
2198        }
2199        if let Some(excerpt) = cursor.item() {
2200            let overshoot = row - cursor.start().row;
2201            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2202            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2203            let buffer_row = excerpt_start.row + overshoot;
2204            let line_start = Point::new(buffer_row, 0);
2205            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2206            return Some((
2207                &excerpt.buffer,
2208                line_start.max(excerpt_start)..line_end.min(excerpt_end),
2209            ));
2210        }
2211        None
2212    }
2213
2214    pub fn max_point(&self) -> Point {
2215        self.text_summary().lines
2216    }
2217
2218    pub fn text_summary(&self) -> TextSummary {
2219        self.excerpts.summary().text.clone()
2220    }
2221
2222    pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2223    where
2224        D: TextDimension,
2225        O: ToOffset,
2226    {
2227        let mut summary = D::default();
2228        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2229        let mut cursor = self.excerpts.cursor::<usize>();
2230        cursor.seek(&range.start, Bias::Right, &());
2231        if let Some(excerpt) = cursor.item() {
2232            let mut end_before_newline = cursor.end(&());
2233            if excerpt.has_trailing_newline {
2234                end_before_newline -= 1;
2235            }
2236
2237            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2238            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2239            let end_in_excerpt =
2240                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2241            summary.add_assign(
2242                &excerpt
2243                    .buffer
2244                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2245            );
2246
2247            if range.end > end_before_newline {
2248                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2249            }
2250
2251            cursor.next(&());
2252        }
2253
2254        if range.end > *cursor.start() {
2255            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2256                &range.end,
2257                Bias::Right,
2258                &(),
2259            )));
2260            if let Some(excerpt) = cursor.item() {
2261                range.end = cmp::max(*cursor.start(), range.end);
2262
2263                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2264                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2265                summary.add_assign(
2266                    &excerpt
2267                        .buffer
2268                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2269                );
2270            }
2271        }
2272
2273        summary
2274    }
2275
2276    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2277    where
2278        D: TextDimension + Ord + Sub<D, Output = D>,
2279    {
2280        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2281        let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2282
2283        cursor.seek(locator, Bias::Left, &());
2284        if cursor.item().is_none() {
2285            cursor.next(&());
2286        }
2287
2288        let mut position = D::from_text_summary(&cursor.start().text);
2289        if let Some(excerpt) = cursor.item() {
2290            if excerpt.id == anchor.excerpt_id {
2291                let excerpt_buffer_start =
2292                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2293                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2294                let buffer_position = cmp::min(
2295                    excerpt_buffer_end,
2296                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2297                );
2298                if buffer_position > excerpt_buffer_start {
2299                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2300                }
2301            }
2302        }
2303        position
2304    }
2305
2306    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2307    where
2308        D: TextDimension + Ord + Sub<D, Output = D>,
2309        I: 'a + IntoIterator<Item = &'a Anchor>,
2310    {
2311        if let Some((_, _, buffer)) = self.as_singleton() {
2312            return buffer
2313                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2314                .collect();
2315        }
2316
2317        let mut anchors = anchors.into_iter().peekable();
2318        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2319        let mut summaries = Vec::new();
2320        while let Some(anchor) = anchors.peek() {
2321            let excerpt_id = anchor.excerpt_id;
2322            let excerpt_anchors = iter::from_fn(|| {
2323                let anchor = anchors.peek()?;
2324                if anchor.excerpt_id == excerpt_id {
2325                    Some(&anchors.next().unwrap().text_anchor)
2326                } else {
2327                    None
2328                }
2329            });
2330
2331            let locator = self.excerpt_locator_for_id(excerpt_id);
2332            cursor.seek_forward(locator, Bias::Left, &());
2333            if cursor.item().is_none() {
2334                cursor.next(&());
2335            }
2336
2337            let position = D::from_text_summary(&cursor.start().text);
2338            if let Some(excerpt) = cursor.item() {
2339                if excerpt.id == excerpt_id {
2340                    let excerpt_buffer_start =
2341                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2342                    let excerpt_buffer_end =
2343                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2344                    summaries.extend(
2345                        excerpt
2346                            .buffer
2347                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2348                            .map(move |summary| {
2349                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2350                                let mut position = position.clone();
2351                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2352                                if summary > excerpt_buffer_start {
2353                                    position.add_assign(&(summary - excerpt_buffer_start));
2354                                }
2355                                position
2356                            }),
2357                    );
2358                    continue;
2359                }
2360            }
2361
2362            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2363        }
2364
2365        summaries
2366    }
2367
2368    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2369    where
2370        I: 'a + IntoIterator<Item = &'a Anchor>,
2371    {
2372        let mut anchors = anchors.into_iter().enumerate().peekable();
2373        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2374        cursor.next(&());
2375
2376        let mut result = Vec::new();
2377
2378        while let Some((_, anchor)) = anchors.peek() {
2379            let old_excerpt_id = anchor.excerpt_id;
2380
2381            // Find the location where this anchor's excerpt should be.
2382            let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2383            cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2384
2385            if cursor.item().is_none() {
2386                cursor.next(&());
2387            }
2388
2389            let next_excerpt = cursor.item();
2390            let prev_excerpt = cursor.prev_item();
2391
2392            // Process all of the anchors for this excerpt.
2393            while let Some((_, anchor)) = anchors.peek() {
2394                if anchor.excerpt_id != old_excerpt_id {
2395                    break;
2396                }
2397                let (anchor_ix, anchor) = anchors.next().unwrap();
2398                let mut anchor = *anchor;
2399
2400                // Leave min and max anchors unchanged if invalid or
2401                // if the old excerpt still exists at this location
2402                let mut kept_position = next_excerpt
2403                    .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2404                    || old_excerpt_id == ExcerptId::max()
2405                    || old_excerpt_id == ExcerptId::min();
2406
2407                // If the old excerpt no longer exists at this location, then attempt to
2408                // find an equivalent position for this anchor in an adjacent excerpt.
2409                if !kept_position {
2410                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2411                        if excerpt.contains(&anchor) {
2412                            anchor.excerpt_id = excerpt.id.clone();
2413                            kept_position = true;
2414                            break;
2415                        }
2416                    }
2417                }
2418
2419                // If there's no adjacent excerpt that contains the anchor's position,
2420                // then report that the anchor has lost its position.
2421                if !kept_position {
2422                    anchor = if let Some(excerpt) = next_excerpt {
2423                        let mut text_anchor = excerpt
2424                            .range
2425                            .context
2426                            .start
2427                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2428                        if text_anchor
2429                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2430                            .is_gt()
2431                        {
2432                            text_anchor = excerpt.range.context.end;
2433                        }
2434                        Anchor {
2435                            buffer_id: Some(excerpt.buffer_id),
2436                            excerpt_id: excerpt.id.clone(),
2437                            text_anchor,
2438                        }
2439                    } else if let Some(excerpt) = prev_excerpt {
2440                        let mut text_anchor = excerpt
2441                            .range
2442                            .context
2443                            .end
2444                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2445                        if text_anchor
2446                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2447                            .is_lt()
2448                        {
2449                            text_anchor = excerpt.range.context.start;
2450                        }
2451                        Anchor {
2452                            buffer_id: Some(excerpt.buffer_id),
2453                            excerpt_id: excerpt.id.clone(),
2454                            text_anchor,
2455                        }
2456                    } else if anchor.text_anchor.bias == Bias::Left {
2457                        Anchor::min()
2458                    } else {
2459                        Anchor::max()
2460                    };
2461                }
2462
2463                result.push((anchor_ix, anchor, kept_position));
2464            }
2465        }
2466        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2467        result
2468    }
2469
2470    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2471        self.anchor_at(position, Bias::Left)
2472    }
2473
2474    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2475        self.anchor_at(position, Bias::Right)
2476    }
2477
2478    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2479        let offset = position.to_offset(self);
2480        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2481            return Anchor {
2482                buffer_id: Some(buffer_id),
2483                excerpt_id: excerpt_id.clone(),
2484                text_anchor: buffer.anchor_at(offset, bias),
2485            };
2486        }
2487
2488        let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2489        cursor.seek(&offset, Bias::Right, &());
2490        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2491            cursor.prev(&());
2492        }
2493        if let Some(excerpt) = cursor.item() {
2494            let mut overshoot = offset.saturating_sub(cursor.start().0);
2495            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2496                overshoot -= 1;
2497                bias = Bias::Right;
2498            }
2499
2500            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2501            let text_anchor =
2502                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2503            Anchor {
2504                buffer_id: Some(excerpt.buffer_id),
2505                excerpt_id: excerpt.id.clone(),
2506                text_anchor,
2507            }
2508        } else if offset == 0 && bias == Bias::Left {
2509            Anchor::min()
2510        } else {
2511            Anchor::max()
2512        }
2513    }
2514
2515    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2516        let locator = self.excerpt_locator_for_id(excerpt_id);
2517        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2518        cursor.seek(locator, Bias::Left, &());
2519        if let Some(excerpt) = cursor.item() {
2520            if excerpt.id == excerpt_id {
2521                let text_anchor = excerpt.clip_anchor(text_anchor);
2522                drop(cursor);
2523                return Anchor {
2524                    buffer_id: Some(excerpt.buffer_id),
2525                    excerpt_id,
2526                    text_anchor,
2527                };
2528            }
2529        }
2530        panic!("excerpt not found");
2531    }
2532
2533    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2534        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2535            true
2536        } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2537            excerpt.buffer.can_resolve(&anchor.text_anchor)
2538        } else {
2539            false
2540        }
2541    }
2542
2543    pub fn excerpts(
2544        &self,
2545    ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2546        self.excerpts
2547            .iter()
2548            .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2549    }
2550
2551    pub fn excerpt_boundaries_in_range<R, T>(
2552        &self,
2553        range: R,
2554    ) -> impl Iterator<Item = ExcerptBoundary> + '_
2555    where
2556        R: RangeBounds<T>,
2557        T: ToOffset,
2558    {
2559        let start_offset;
2560        let start = match range.start_bound() {
2561            Bound::Included(start) => {
2562                start_offset = start.to_offset(self);
2563                Bound::Included(start_offset)
2564            }
2565            Bound::Excluded(start) => {
2566                start_offset = start.to_offset(self);
2567                Bound::Excluded(start_offset)
2568            }
2569            Bound::Unbounded => {
2570                start_offset = 0;
2571                Bound::Unbounded
2572            }
2573        };
2574        let end = match range.end_bound() {
2575            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2576            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2577            Bound::Unbounded => Bound::Unbounded,
2578        };
2579        let bounds = (start, end);
2580
2581        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2582        cursor.seek(&start_offset, Bias::Right, &());
2583        if cursor.item().is_none() {
2584            cursor.prev(&());
2585        }
2586        if !bounds.contains(&cursor.start().0) {
2587            cursor.next(&());
2588        }
2589
2590        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2591        std::iter::from_fn(move || {
2592            if self.singleton {
2593                None
2594            } else if bounds.contains(&cursor.start().0) {
2595                let excerpt = cursor.item()?;
2596                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2597                let boundary = ExcerptBoundary {
2598                    id: excerpt.id.clone(),
2599                    row: cursor.start().1.row,
2600                    buffer: excerpt.buffer.clone(),
2601                    range: excerpt.range.clone(),
2602                    starts_new_buffer,
2603                };
2604
2605                prev_buffer_id = Some(excerpt.buffer_id);
2606                cursor.next(&());
2607                Some(boundary)
2608            } else {
2609                None
2610            }
2611        })
2612    }
2613
2614    pub fn edit_count(&self) -> usize {
2615        self.edit_count
2616    }
2617
2618    pub fn parse_count(&self) -> usize {
2619        self.parse_count
2620    }
2621
2622    /// Returns the smallest enclosing bracket ranges containing the given range or
2623    /// None if no brackets contain range or the range is not contained in a single
2624    /// excerpt
2625    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2626        &self,
2627        range: Range<T>,
2628    ) -> Option<(Range<usize>, Range<usize>)> {
2629        let range = range.start.to_offset(self)..range.end.to_offset(self);
2630
2631        // Get the ranges of the innermost pair of brackets.
2632        let mut result: Option<(Range<usize>, Range<usize>)> = None;
2633
2634        let Some(enclosing_bracket_ranges) = self.enclosing_bracket_ranges(range.clone()) else { return None; };
2635
2636        for (open, close) in enclosing_bracket_ranges {
2637            let len = close.end - open.start;
2638
2639            if let Some((existing_open, existing_close)) = &result {
2640                let existing_len = existing_close.end - existing_open.start;
2641                if len > existing_len {
2642                    continue;
2643                }
2644            }
2645
2646            result = Some((open, close));
2647        }
2648
2649        result
2650    }
2651
2652    /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2653    /// not contained in a single excerpt
2654    pub fn enclosing_bracket_ranges<'a, T: ToOffset>(
2655        &'a self,
2656        range: Range<T>,
2657    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2658        let range = range.start.to_offset(self)..range.end.to_offset(self);
2659
2660        self.bracket_ranges(range.clone()).map(|range_pairs| {
2661            range_pairs
2662                .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2663        })
2664    }
2665
2666    /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2667    /// not contained in a single excerpt
2668    pub fn bracket_ranges<'a, T: ToOffset>(
2669        &'a self,
2670        range: Range<T>,
2671    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2672        let range = range.start.to_offset(self)..range.end.to_offset(self);
2673        let excerpt = self.excerpt_containing(range.clone());
2674        excerpt.map(|(excerpt, excerpt_offset)| {
2675            let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2676            let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2677
2678            let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2679            let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2680
2681            excerpt
2682                .buffer
2683                .bracket_ranges(start_in_buffer..end_in_buffer)
2684                .filter_map(move |(start_bracket_range, end_bracket_range)| {
2685                    if start_bracket_range.start < excerpt_buffer_start
2686                        || end_bracket_range.end > excerpt_buffer_end
2687                    {
2688                        return None;
2689                    }
2690
2691                    let mut start_bracket_range = start_bracket_range.clone();
2692                    start_bracket_range.start =
2693                        excerpt_offset + (start_bracket_range.start - excerpt_buffer_start);
2694                    start_bracket_range.end =
2695                        excerpt_offset + (start_bracket_range.end - excerpt_buffer_start);
2696
2697                    let mut end_bracket_range = end_bracket_range.clone();
2698                    end_bracket_range.start =
2699                        excerpt_offset + (end_bracket_range.start - excerpt_buffer_start);
2700                    end_bracket_range.end =
2701                        excerpt_offset + (end_bracket_range.end - excerpt_buffer_start);
2702                    Some((start_bracket_range, end_bracket_range))
2703                })
2704        })
2705    }
2706
2707    pub fn diagnostics_update_count(&self) -> usize {
2708        self.diagnostics_update_count
2709    }
2710
2711    pub fn git_diff_update_count(&self) -> usize {
2712        self.git_diff_update_count
2713    }
2714
2715    pub fn trailing_excerpt_update_count(&self) -> usize {
2716        self.trailing_excerpt_update_count
2717    }
2718
2719    pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2720        self.point_to_buffer_offset(point)
2721            .and_then(|(buffer, offset)| buffer.language_at(offset))
2722    }
2723
2724    pub fn language_scope_at<'a, T: ToOffset>(&'a self, point: T) -> Option<LanguageScope> {
2725        self.point_to_buffer_offset(point)
2726            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
2727    }
2728
2729    pub fn is_dirty(&self) -> bool {
2730        self.is_dirty
2731    }
2732
2733    pub fn has_conflict(&self) -> bool {
2734        self.has_conflict
2735    }
2736
2737    pub fn diagnostic_group<'a, O>(
2738        &'a self,
2739        group_id: usize,
2740    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2741    where
2742        O: text::FromAnchor + 'a,
2743    {
2744        self.as_singleton()
2745            .into_iter()
2746            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2747    }
2748
2749    pub fn diagnostics_in_range<'a, T, O>(
2750        &'a self,
2751        range: Range<T>,
2752        reversed: bool,
2753    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2754    where
2755        T: 'a + ToOffset,
2756        O: 'a + text::FromAnchor,
2757    {
2758        self.as_singleton()
2759            .into_iter()
2760            .flat_map(move |(_, _, buffer)| {
2761                buffer.diagnostics_in_range(
2762                    range.start.to_offset(self)..range.end.to_offset(self),
2763                    reversed,
2764                )
2765            })
2766    }
2767
2768    pub fn git_diff_hunks_in_range<'a>(
2769        &'a self,
2770        row_range: Range<u32>,
2771        reversed: bool,
2772    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2773        let mut cursor = self.excerpts.cursor::<Point>();
2774
2775        if reversed {
2776            cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2777            if cursor.item().is_none() {
2778                cursor.prev(&());
2779            }
2780        } else {
2781            cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
2782        }
2783
2784        std::iter::from_fn(move || {
2785            let excerpt = cursor.item()?;
2786            let multibuffer_start = *cursor.start();
2787            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2788            if multibuffer_start.row >= row_range.end {
2789                return None;
2790            }
2791
2792            let mut buffer_start = excerpt.range.context.start;
2793            let mut buffer_end = excerpt.range.context.end;
2794            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2795            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2796
2797            if row_range.start > multibuffer_start.row {
2798                let buffer_start_point =
2799                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2800                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2801            }
2802
2803            if row_range.end < multibuffer_end.row {
2804                let buffer_end_point =
2805                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2806                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2807            }
2808
2809            let buffer_hunks = excerpt
2810                .buffer
2811                .git_diff_hunks_intersecting_range(buffer_start..buffer_end, reversed)
2812                .filter_map(move |hunk| {
2813                    let start = multibuffer_start.row
2814                        + hunk
2815                            .buffer_range
2816                            .start
2817                            .saturating_sub(excerpt_start_point.row);
2818                    let end = multibuffer_start.row
2819                        + hunk
2820                            .buffer_range
2821                            .end
2822                            .min(excerpt_end_point.row + 1)
2823                            .saturating_sub(excerpt_start_point.row);
2824
2825                    Some(DiffHunk {
2826                        buffer_range: start..end,
2827                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2828                    })
2829                });
2830
2831            if reversed {
2832                cursor.prev(&());
2833            } else {
2834                cursor.next(&());
2835            }
2836
2837            Some(buffer_hunks)
2838        })
2839        .flatten()
2840    }
2841
2842    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2843        let range = range.start.to_offset(self)..range.end.to_offset(self);
2844
2845        self.excerpt_containing(range.clone())
2846            .and_then(|(excerpt, excerpt_offset)| {
2847                let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2848                let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2849
2850                let start_in_buffer =
2851                    excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2852                let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2853                let mut ancestor_buffer_range = excerpt
2854                    .buffer
2855                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2856                ancestor_buffer_range.start =
2857                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2858                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2859
2860                let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
2861                let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
2862                Some(start..end)
2863            })
2864    }
2865
2866    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2867        let (excerpt_id, _, buffer) = self.as_singleton()?;
2868        let outline = buffer.outline(theme)?;
2869        Some(Outline::new(
2870            outline
2871                .items
2872                .into_iter()
2873                .map(|item| OutlineItem {
2874                    depth: item.depth,
2875                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2876                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2877                    text: item.text,
2878                    highlight_ranges: item.highlight_ranges,
2879                    name_ranges: item.name_ranges,
2880                })
2881                .collect(),
2882        ))
2883    }
2884
2885    pub fn symbols_containing<T: ToOffset>(
2886        &self,
2887        offset: T,
2888        theme: Option<&SyntaxTheme>,
2889    ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
2890        let anchor = self.anchor_before(offset);
2891        let excerpt_id = anchor.excerpt_id();
2892        let excerpt = self.excerpt(excerpt_id)?;
2893        Some((
2894            excerpt.buffer_id,
2895            excerpt
2896                .buffer
2897                .symbols_containing(anchor.text_anchor, theme)
2898                .into_iter()
2899                .flatten()
2900                .map(|item| OutlineItem {
2901                    depth: item.depth,
2902                    range: self.anchor_in_excerpt(excerpt_id, item.range.start)
2903                        ..self.anchor_in_excerpt(excerpt_id, item.range.end),
2904                    text: item.text,
2905                    highlight_ranges: item.highlight_ranges,
2906                    name_ranges: item.name_ranges,
2907                })
2908                .collect(),
2909        ))
2910    }
2911
2912    fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
2913        if id == ExcerptId::min() {
2914            Locator::min_ref()
2915        } else if id == ExcerptId::max() {
2916            Locator::max_ref()
2917        } else {
2918            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
2919            cursor.seek(&id, Bias::Left, &());
2920            if let Some(entry) = cursor.item() {
2921                if entry.id == id {
2922                    return &entry.locator;
2923                }
2924            }
2925            panic!("invalid excerpt id {:?}", id)
2926        }
2927    }
2928
2929    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<usize> {
2930        Some(self.excerpt(excerpt_id)?.buffer_id)
2931    }
2932
2933    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
2934        Some(&self.excerpt(excerpt_id)?.buffer)
2935    }
2936
2937    fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
2938        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2939        let locator = self.excerpt_locator_for_id(excerpt_id);
2940        cursor.seek(&Some(locator), Bias::Left, &());
2941        if let Some(excerpt) = cursor.item() {
2942            if excerpt.id == excerpt_id {
2943                return Some(excerpt);
2944            }
2945        }
2946        None
2947    }
2948
2949    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
2950    fn excerpt_containing<'a, T: ToOffset>(
2951        &'a self,
2952        range: Range<T>,
2953    ) -> Option<(&'a Excerpt, usize)> {
2954        let range = range.start.to_offset(self)..range.end.to_offset(self);
2955
2956        let mut cursor = self.excerpts.cursor::<usize>();
2957        cursor.seek(&range.start, Bias::Right, &());
2958        let start_excerpt = cursor.item();
2959
2960        if range.start == range.end {
2961            return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
2962        }
2963
2964        cursor.seek(&range.end, Bias::Right, &());
2965        let end_excerpt = cursor.item();
2966
2967        start_excerpt
2968            .zip(end_excerpt)
2969            .and_then(|(start_excerpt, end_excerpt)| {
2970                if start_excerpt.id != end_excerpt.id {
2971                    return None;
2972                }
2973
2974                Some((start_excerpt, *cursor.start()))
2975            })
2976    }
2977
2978    pub fn remote_selections_in_range<'a>(
2979        &'a self,
2980        range: &'a Range<Anchor>,
2981    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
2982        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2983        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
2984        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
2985        cursor.seek(start_locator, Bias::Left, &());
2986        cursor
2987            .take_while(move |excerpt| excerpt.locator <= *end_locator)
2988            .flat_map(move |excerpt| {
2989                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
2990                if excerpt.id == range.start.excerpt_id {
2991                    query_range.start = range.start.text_anchor;
2992                }
2993                if excerpt.id == range.end.excerpt_id {
2994                    query_range.end = range.end.text_anchor;
2995                }
2996
2997                excerpt
2998                    .buffer
2999                    .remote_selections_in_range(query_range)
3000                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3001                        selections.map(move |selection| {
3002                            let mut start = Anchor {
3003                                buffer_id: Some(excerpt.buffer_id),
3004                                excerpt_id: excerpt.id.clone(),
3005                                text_anchor: selection.start,
3006                            };
3007                            let mut end = Anchor {
3008                                buffer_id: Some(excerpt.buffer_id),
3009                                excerpt_id: excerpt.id.clone(),
3010                                text_anchor: selection.end,
3011                            };
3012                            if range.start.cmp(&start, self).is_gt() {
3013                                start = range.start.clone();
3014                            }
3015                            if range.end.cmp(&end, self).is_lt() {
3016                                end = range.end.clone();
3017                            }
3018
3019                            (
3020                                replica_id,
3021                                line_mode,
3022                                cursor_shape,
3023                                Selection {
3024                                    id: selection.id,
3025                                    start,
3026                                    end,
3027                                    reversed: selection.reversed,
3028                                    goal: selection.goal,
3029                                },
3030                            )
3031                        })
3032                    })
3033            })
3034    }
3035}
3036
3037#[cfg(any(test, feature = "test-support"))]
3038impl MultiBufferSnapshot {
3039    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3040        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3041        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3042        start..end
3043    }
3044}
3045
3046impl History {
3047    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3048        self.transaction_depth += 1;
3049        if self.transaction_depth == 1 {
3050            let id = self.next_transaction_id.tick();
3051            self.undo_stack.push(Transaction {
3052                id,
3053                buffer_transactions: Default::default(),
3054                first_edit_at: now,
3055                last_edit_at: now,
3056                suppress_grouping: false,
3057            });
3058            Some(id)
3059        } else {
3060            None
3061        }
3062    }
3063
3064    fn end_transaction(
3065        &mut self,
3066        now: Instant,
3067        buffer_transactions: HashMap<usize, TransactionId>,
3068    ) -> bool {
3069        assert_ne!(self.transaction_depth, 0);
3070        self.transaction_depth -= 1;
3071        if self.transaction_depth == 0 {
3072            if buffer_transactions.is_empty() {
3073                self.undo_stack.pop();
3074                false
3075            } else {
3076                self.redo_stack.clear();
3077                let transaction = self.undo_stack.last_mut().unwrap();
3078                transaction.last_edit_at = now;
3079                for (buffer_id, transaction_id) in buffer_transactions {
3080                    transaction
3081                        .buffer_transactions
3082                        .entry(buffer_id)
3083                        .or_insert(transaction_id);
3084                }
3085                true
3086            }
3087        } else {
3088            false
3089        }
3090    }
3091
3092    fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
3093    where
3094        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3095    {
3096        assert_eq!(self.transaction_depth, 0);
3097        let transaction = Transaction {
3098            id: self.next_transaction_id.tick(),
3099            buffer_transactions: buffer_transactions
3100                .into_iter()
3101                .map(|(buffer, transaction)| (buffer.id(), transaction.id))
3102                .collect(),
3103            first_edit_at: now,
3104            last_edit_at: now,
3105            suppress_grouping: false,
3106        };
3107        if !transaction.buffer_transactions.is_empty() {
3108            self.undo_stack.push(transaction);
3109            self.redo_stack.clear();
3110        }
3111    }
3112
3113    fn finalize_last_transaction(&mut self) {
3114        if let Some(transaction) = self.undo_stack.last_mut() {
3115            transaction.suppress_grouping = true;
3116        }
3117    }
3118
3119    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3120        assert_eq!(self.transaction_depth, 0);
3121        if let Some(transaction) = self.undo_stack.pop() {
3122            self.redo_stack.push(transaction);
3123            self.redo_stack.last_mut()
3124        } else {
3125            None
3126        }
3127    }
3128
3129    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3130        assert_eq!(self.transaction_depth, 0);
3131        if let Some(transaction) = self.redo_stack.pop() {
3132            self.undo_stack.push(transaction);
3133            self.undo_stack.last_mut()
3134        } else {
3135            None
3136        }
3137    }
3138
3139    fn group(&mut self) -> Option<TransactionId> {
3140        let mut count = 0;
3141        let mut transactions = self.undo_stack.iter();
3142        if let Some(mut transaction) = transactions.next_back() {
3143            while let Some(prev_transaction) = transactions.next_back() {
3144                if !prev_transaction.suppress_grouping
3145                    && transaction.first_edit_at - prev_transaction.last_edit_at
3146                        <= self.group_interval
3147                {
3148                    transaction = prev_transaction;
3149                    count += 1;
3150                } else {
3151                    break;
3152                }
3153            }
3154        }
3155        self.group_trailing(count)
3156    }
3157
3158    fn group_until(&mut self, transaction_id: TransactionId) {
3159        let mut count = 0;
3160        for transaction in self.undo_stack.iter().rev() {
3161            if transaction.id == transaction_id {
3162                self.group_trailing(count);
3163                break;
3164            } else if transaction.suppress_grouping {
3165                break;
3166            } else {
3167                count += 1;
3168            }
3169        }
3170    }
3171
3172    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3173        let new_len = self.undo_stack.len() - n;
3174        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3175        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3176            if let Some(transaction) = transactions_to_merge.last() {
3177                last_transaction.last_edit_at = transaction.last_edit_at;
3178            }
3179            for to_merge in transactions_to_merge {
3180                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3181                    last_transaction
3182                        .buffer_transactions
3183                        .entry(*buffer_id)
3184                        .or_insert(*transaction_id);
3185                }
3186            }
3187        }
3188
3189        self.undo_stack.truncate(new_len);
3190        self.undo_stack.last().map(|t| t.id)
3191    }
3192}
3193
3194impl Excerpt {
3195    fn new(
3196        id: ExcerptId,
3197        locator: Locator,
3198        buffer_id: usize,
3199        buffer: BufferSnapshot,
3200        range: ExcerptRange<text::Anchor>,
3201        has_trailing_newline: bool,
3202    ) -> Self {
3203        Excerpt {
3204            id,
3205            locator,
3206            max_buffer_row: range.context.end.to_point(&buffer).row,
3207            text_summary: buffer
3208                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3209            buffer_id,
3210            buffer,
3211            range,
3212            has_trailing_newline,
3213        }
3214    }
3215
3216    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3217        let content_start = self.range.context.start.to_offset(&self.buffer);
3218        let chunks_start = content_start + range.start;
3219        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3220
3221        let footer_height = if self.has_trailing_newline
3222            && range.start <= self.text_summary.len
3223            && range.end > self.text_summary.len
3224        {
3225            1
3226        } else {
3227            0
3228        };
3229
3230        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3231
3232        ExcerptChunks {
3233            content_chunks,
3234            footer_height,
3235        }
3236    }
3237
3238    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3239        let content_start = self.range.context.start.to_offset(&self.buffer);
3240        let bytes_start = content_start + range.start;
3241        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3242        let footer_height = if self.has_trailing_newline
3243            && range.start <= self.text_summary.len
3244            && range.end > self.text_summary.len
3245        {
3246            1
3247        } else {
3248            0
3249        };
3250        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3251
3252        ExcerptBytes {
3253            content_bytes,
3254            footer_height,
3255        }
3256    }
3257
3258    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3259        if text_anchor
3260            .cmp(&self.range.context.start, &self.buffer)
3261            .is_lt()
3262        {
3263            self.range.context.start
3264        } else if text_anchor
3265            .cmp(&self.range.context.end, &self.buffer)
3266            .is_gt()
3267        {
3268            self.range.context.end
3269        } else {
3270            text_anchor
3271        }
3272    }
3273
3274    fn contains(&self, anchor: &Anchor) -> bool {
3275        Some(self.buffer_id) == anchor.buffer_id
3276            && self
3277                .range
3278                .context
3279                .start
3280                .cmp(&anchor.text_anchor, &self.buffer)
3281                .is_le()
3282            && self
3283                .range
3284                .context
3285                .end
3286                .cmp(&anchor.text_anchor, &self.buffer)
3287                .is_ge()
3288    }
3289}
3290
3291impl ExcerptId {
3292    pub fn min() -> Self {
3293        Self(0)
3294    }
3295
3296    pub fn max() -> Self {
3297        Self(usize::MAX)
3298    }
3299
3300    pub fn to_proto(&self) -> u64 {
3301        self.0 as _
3302    }
3303
3304    pub fn from_proto(proto: u64) -> Self {
3305        Self(proto as _)
3306    }
3307
3308    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3309        let a = snapshot.excerpt_locator_for_id(*self);
3310        let b = snapshot.excerpt_locator_for_id(*other);
3311        a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3312    }
3313}
3314
3315impl Into<usize> for ExcerptId {
3316    fn into(self) -> usize {
3317        self.0
3318    }
3319}
3320
3321impl fmt::Debug for Excerpt {
3322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3323        f.debug_struct("Excerpt")
3324            .field("id", &self.id)
3325            .field("locator", &self.locator)
3326            .field("buffer_id", &self.buffer_id)
3327            .field("range", &self.range)
3328            .field("text_summary", &self.text_summary)
3329            .field("has_trailing_newline", &self.has_trailing_newline)
3330            .finish()
3331    }
3332}
3333
3334impl sum_tree::Item for Excerpt {
3335    type Summary = ExcerptSummary;
3336
3337    fn summary(&self) -> Self::Summary {
3338        let mut text = self.text_summary.clone();
3339        if self.has_trailing_newline {
3340            text += TextSummary::from("\n");
3341        }
3342        ExcerptSummary {
3343            excerpt_id: self.id,
3344            excerpt_locator: self.locator.clone(),
3345            max_buffer_row: self.max_buffer_row,
3346            text,
3347        }
3348    }
3349}
3350
3351impl sum_tree::Item for ExcerptIdMapping {
3352    type Summary = ExcerptId;
3353
3354    fn summary(&self) -> Self::Summary {
3355        self.id
3356    }
3357}
3358
3359impl sum_tree::KeyedItem for ExcerptIdMapping {
3360    type Key = ExcerptId;
3361
3362    fn key(&self) -> Self::Key {
3363        self.id
3364    }
3365}
3366
3367impl sum_tree::Summary for ExcerptId {
3368    type Context = ();
3369
3370    fn add_summary(&mut self, other: &Self, _: &()) {
3371        *self = *other;
3372    }
3373}
3374
3375impl sum_tree::Summary for ExcerptSummary {
3376    type Context = ();
3377
3378    fn add_summary(&mut self, summary: &Self, _: &()) {
3379        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3380        self.excerpt_locator = summary.excerpt_locator.clone();
3381        self.text.add_summary(&summary.text, &());
3382        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3383    }
3384}
3385
3386impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3387    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3388        *self += &summary.text;
3389    }
3390}
3391
3392impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3393    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3394        *self += summary.text.len;
3395    }
3396}
3397
3398impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3399    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3400        Ord::cmp(self, &cursor_location.text.len)
3401    }
3402}
3403
3404impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3405    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3406        Ord::cmp(&Some(self), cursor_location)
3407    }
3408}
3409
3410impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3411    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3412        Ord::cmp(self, &cursor_location.excerpt_locator)
3413    }
3414}
3415
3416impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3417    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3418        *self += summary.text.len_utf16;
3419    }
3420}
3421
3422impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3423    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3424        *self += summary.text.lines;
3425    }
3426}
3427
3428impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3429    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3430        *self += summary.text.lines_utf16()
3431    }
3432}
3433
3434impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3435    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3436        *self = Some(&summary.excerpt_locator);
3437    }
3438}
3439
3440impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3441    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3442        *self = Some(summary.excerpt_id);
3443    }
3444}
3445
3446impl<'a> MultiBufferRows<'a> {
3447    pub fn seek(&mut self, row: u32) {
3448        self.buffer_row_range = 0..0;
3449
3450        self.excerpts
3451            .seek_forward(&Point::new(row, 0), Bias::Right, &());
3452        if self.excerpts.item().is_none() {
3453            self.excerpts.prev(&());
3454
3455            if self.excerpts.item().is_none() && row == 0 {
3456                self.buffer_row_range = 0..1;
3457                return;
3458            }
3459        }
3460
3461        if let Some(excerpt) = self.excerpts.item() {
3462            let overshoot = row - self.excerpts.start().row;
3463            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3464            self.buffer_row_range.start = excerpt_start + overshoot;
3465            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3466        }
3467    }
3468}
3469
3470impl<'a> Iterator for MultiBufferRows<'a> {
3471    type Item = Option<u32>;
3472
3473    fn next(&mut self) -> Option<Self::Item> {
3474        loop {
3475            if !self.buffer_row_range.is_empty() {
3476                let row = Some(self.buffer_row_range.start);
3477                self.buffer_row_range.start += 1;
3478                return Some(row);
3479            }
3480            self.excerpts.item()?;
3481            self.excerpts.next(&());
3482            let excerpt = self.excerpts.item()?;
3483            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3484            self.buffer_row_range.end =
3485                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3486        }
3487    }
3488}
3489
3490impl<'a> MultiBufferChunks<'a> {
3491    pub fn offset(&self) -> usize {
3492        self.range.start
3493    }
3494
3495    pub fn seek(&mut self, offset: usize) {
3496        self.range.start = offset;
3497        self.excerpts.seek(&offset, Bias::Right, &());
3498        if let Some(excerpt) = self.excerpts.item() {
3499            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3500                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3501                self.language_aware,
3502            ));
3503        } else {
3504            self.excerpt_chunks = None;
3505        }
3506    }
3507}
3508
3509impl<'a> Iterator for MultiBufferChunks<'a> {
3510    type Item = Chunk<'a>;
3511
3512    fn next(&mut self) -> Option<Self::Item> {
3513        if self.range.is_empty() {
3514            None
3515        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3516            self.range.start += chunk.text.len();
3517            Some(chunk)
3518        } else {
3519            self.excerpts.next(&());
3520            let excerpt = self.excerpts.item()?;
3521            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3522                0..self.range.end - self.excerpts.start(),
3523                self.language_aware,
3524            ));
3525            self.next()
3526        }
3527    }
3528}
3529
3530impl<'a> MultiBufferBytes<'a> {
3531    fn consume(&mut self, len: usize) {
3532        self.range.start += len;
3533        self.chunk = &self.chunk[len..];
3534
3535        if !self.range.is_empty() && self.chunk.is_empty() {
3536            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3537                self.chunk = chunk;
3538            } else {
3539                self.excerpts.next(&());
3540                if let Some(excerpt) = self.excerpts.item() {
3541                    let mut excerpt_bytes =
3542                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3543                    self.chunk = excerpt_bytes.next().unwrap();
3544                    self.excerpt_bytes = Some(excerpt_bytes);
3545                }
3546            }
3547        }
3548    }
3549}
3550
3551impl<'a> Iterator for MultiBufferBytes<'a> {
3552    type Item = &'a [u8];
3553
3554    fn next(&mut self) -> Option<Self::Item> {
3555        let chunk = self.chunk;
3556        if chunk.is_empty() {
3557            None
3558        } else {
3559            self.consume(chunk.len());
3560            Some(chunk)
3561        }
3562    }
3563}
3564
3565impl<'a> io::Read for MultiBufferBytes<'a> {
3566    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3567        let len = cmp::min(buf.len(), self.chunk.len());
3568        buf[..len].copy_from_slice(&self.chunk[..len]);
3569        if len > 0 {
3570            self.consume(len);
3571        }
3572        Ok(len)
3573    }
3574}
3575
3576impl<'a> Iterator for ExcerptBytes<'a> {
3577    type Item = &'a [u8];
3578
3579    fn next(&mut self) -> Option<Self::Item> {
3580        if let Some(chunk) = self.content_bytes.next() {
3581            if !chunk.is_empty() {
3582                return Some(chunk);
3583            }
3584        }
3585
3586        if self.footer_height > 0 {
3587            let result = &NEWLINES[..self.footer_height];
3588            self.footer_height = 0;
3589            return Some(result);
3590        }
3591
3592        None
3593    }
3594}
3595
3596impl<'a> Iterator for ExcerptChunks<'a> {
3597    type Item = Chunk<'a>;
3598
3599    fn next(&mut self) -> Option<Self::Item> {
3600        if let Some(chunk) = self.content_chunks.next() {
3601            return Some(chunk);
3602        }
3603
3604        if self.footer_height > 0 {
3605            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3606            self.footer_height = 0;
3607            return Some(Chunk {
3608                text,
3609                ..Default::default()
3610            });
3611        }
3612
3613        None
3614    }
3615}
3616
3617impl ToOffset for Point {
3618    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3619        snapshot.point_to_offset(*self)
3620    }
3621}
3622
3623impl ToOffset for usize {
3624    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3625        assert!(*self <= snapshot.len(), "offset is out of range");
3626        *self
3627    }
3628}
3629
3630impl ToOffset for OffsetUtf16 {
3631    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3632        snapshot.offset_utf16_to_offset(*self)
3633    }
3634}
3635
3636impl ToOffset for PointUtf16 {
3637    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3638        snapshot.point_utf16_to_offset(*self)
3639    }
3640}
3641
3642impl ToOffsetUtf16 for OffsetUtf16 {
3643    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3644        *self
3645    }
3646}
3647
3648impl ToOffsetUtf16 for usize {
3649    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3650        snapshot.offset_to_offset_utf16(*self)
3651    }
3652}
3653
3654impl ToPoint for usize {
3655    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3656        snapshot.offset_to_point(*self)
3657    }
3658}
3659
3660impl ToPoint for Point {
3661    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3662        *self
3663    }
3664}
3665
3666impl ToPointUtf16 for usize {
3667    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3668        snapshot.offset_to_point_utf16(*self)
3669    }
3670}
3671
3672impl ToPointUtf16 for Point {
3673    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3674        snapshot.point_to_point_utf16(*self)
3675    }
3676}
3677
3678impl ToPointUtf16 for PointUtf16 {
3679    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3680        *self
3681    }
3682}
3683
3684fn build_excerpt_ranges<T>(
3685    buffer: &BufferSnapshot,
3686    ranges: &[Range<T>],
3687    context_line_count: u32,
3688) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3689where
3690    T: text::ToPoint,
3691{
3692    let max_point = buffer.max_point();
3693    let mut range_counts = Vec::new();
3694    let mut excerpt_ranges = Vec::new();
3695    let mut range_iter = ranges
3696        .iter()
3697        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3698        .peekable();
3699    while let Some(range) = range_iter.next() {
3700        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3701        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3702        let mut ranges_in_excerpt = 1;
3703
3704        while let Some(next_range) = range_iter.peek() {
3705            if next_range.start.row <= excerpt_end.row + context_line_count {
3706                excerpt_end =
3707                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3708                ranges_in_excerpt += 1;
3709                range_iter.next();
3710            } else {
3711                break;
3712            }
3713        }
3714
3715        excerpt_ranges.push(ExcerptRange {
3716            context: excerpt_start..excerpt_end,
3717            primary: Some(range),
3718        });
3719        range_counts.push(ranges_in_excerpt);
3720    }
3721
3722    (excerpt_ranges, range_counts)
3723}
3724
3725#[cfg(test)]
3726mod tests {
3727    use super::*;
3728    use futures::StreamExt;
3729    use gpui::{AppContext, TestAppContext};
3730    use language::{Buffer, Rope};
3731    use rand::prelude::*;
3732    use settings::Settings;
3733    use std::{env, rc::Rc};
3734    use unindent::Unindent;
3735
3736    use util::test::sample_text;
3737
3738    #[gpui::test]
3739    fn test_singleton(cx: &mut AppContext) {
3740        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3741        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3742
3743        let snapshot = multibuffer.read(cx).snapshot(cx);
3744        assert_eq!(snapshot.text(), buffer.read(cx).text());
3745
3746        assert_eq!(
3747            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3748            (0..buffer.read(cx).row_count())
3749                .map(Some)
3750                .collect::<Vec<_>>()
3751        );
3752
3753        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
3754        let snapshot = multibuffer.read(cx).snapshot(cx);
3755
3756        assert_eq!(snapshot.text(), buffer.read(cx).text());
3757        assert_eq!(
3758            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3759            (0..buffer.read(cx).row_count())
3760                .map(Some)
3761                .collect::<Vec<_>>()
3762        );
3763    }
3764
3765    #[gpui::test]
3766    fn test_remote(cx: &mut AppContext) {
3767        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3768        let guest_buffer = cx.add_model(|cx| {
3769            let state = host_buffer.read(cx).to_proto();
3770            let ops = cx
3771                .background()
3772                .block(host_buffer.read(cx).serialize_ops(None, cx));
3773            let mut buffer = Buffer::from_proto(1, state, None).unwrap();
3774            buffer
3775                .apply_ops(
3776                    ops.into_iter()
3777                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
3778                    cx,
3779                )
3780                .unwrap();
3781            buffer
3782        });
3783        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3784        let snapshot = multibuffer.read(cx).snapshot(cx);
3785        assert_eq!(snapshot.text(), "a");
3786
3787        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
3788        let snapshot = multibuffer.read(cx).snapshot(cx);
3789        assert_eq!(snapshot.text(), "ab");
3790
3791        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
3792        let snapshot = multibuffer.read(cx).snapshot(cx);
3793        assert_eq!(snapshot.text(), "abc");
3794    }
3795
3796    #[gpui::test]
3797    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
3798        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3799        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3800        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3801
3802        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3803        multibuffer.update(cx, |_, cx| {
3804            let events = events.clone();
3805            cx.subscribe(&multibuffer, move |_, _, event, _| {
3806                if let Event::Edited = event {
3807                    events.borrow_mut().push(event.clone())
3808                }
3809            })
3810            .detach();
3811        });
3812
3813        let subscription = multibuffer.update(cx, |multibuffer, cx| {
3814            let subscription = multibuffer.subscribe();
3815            multibuffer.push_excerpts(
3816                buffer_1.clone(),
3817                [ExcerptRange {
3818                    context: Point::new(1, 2)..Point::new(2, 5),
3819                    primary: None,
3820                }],
3821                cx,
3822            );
3823            assert_eq!(
3824                subscription.consume().into_inner(),
3825                [Edit {
3826                    old: 0..0,
3827                    new: 0..10
3828                }]
3829            );
3830
3831            multibuffer.push_excerpts(
3832                buffer_1.clone(),
3833                [ExcerptRange {
3834                    context: Point::new(3, 3)..Point::new(4, 4),
3835                    primary: None,
3836                }],
3837                cx,
3838            );
3839            multibuffer.push_excerpts(
3840                buffer_2.clone(),
3841                [ExcerptRange {
3842                    context: Point::new(3, 1)..Point::new(3, 3),
3843                    primary: None,
3844                }],
3845                cx,
3846            );
3847            assert_eq!(
3848                subscription.consume().into_inner(),
3849                [Edit {
3850                    old: 10..10,
3851                    new: 10..22
3852                }]
3853            );
3854
3855            subscription
3856        });
3857
3858        // Adding excerpts emits an edited event.
3859        assert_eq!(
3860            events.borrow().as_slice(),
3861            &[Event::Edited, Event::Edited, Event::Edited]
3862        );
3863
3864        let snapshot = multibuffer.read(cx).snapshot(cx);
3865        assert_eq!(
3866            snapshot.text(),
3867            concat!(
3868                "bbbb\n",  // Preserve newlines
3869                "ccccc\n", //
3870                "ddd\n",   //
3871                "eeee\n",  //
3872                "jj"       //
3873            )
3874        );
3875        assert_eq!(
3876            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3877            [Some(1), Some(2), Some(3), Some(4), Some(3)]
3878        );
3879        assert_eq!(
3880            snapshot.buffer_rows(2).collect::<Vec<_>>(),
3881            [Some(3), Some(4), Some(3)]
3882        );
3883        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3884        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3885
3886        assert_eq!(
3887            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3888            &[
3889                (0, "bbbb\nccccc".to_string(), true),
3890                (2, "ddd\neeee".to_string(), false),
3891                (4, "jj".to_string(), true),
3892            ]
3893        );
3894        assert_eq!(
3895            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3896            &[(0, "bbbb\nccccc".to_string(), true)]
3897        );
3898        assert_eq!(
3899            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3900            &[]
3901        );
3902        assert_eq!(
3903            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3904            &[]
3905        );
3906        assert_eq!(
3907            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3908            &[(2, "ddd\neeee".to_string(), false)]
3909        );
3910        assert_eq!(
3911            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3912            &[(2, "ddd\neeee".to_string(), false)]
3913        );
3914        assert_eq!(
3915            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3916            &[(2, "ddd\neeee".to_string(), false)]
3917        );
3918        assert_eq!(
3919            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3920            &[(4, "jj".to_string(), true)]
3921        );
3922        assert_eq!(
3923            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
3924            &[]
3925        );
3926
3927        buffer_1.update(cx, |buffer, cx| {
3928            let text = "\n";
3929            buffer.edit(
3930                [
3931                    (Point::new(0, 0)..Point::new(0, 0), text),
3932                    (Point::new(2, 1)..Point::new(2, 3), text),
3933                ],
3934                None,
3935                cx,
3936            );
3937        });
3938
3939        let snapshot = multibuffer.read(cx).snapshot(cx);
3940        assert_eq!(
3941            snapshot.text(),
3942            concat!(
3943                "bbbb\n", // Preserve newlines
3944                "c\n",    //
3945                "cc\n",   //
3946                "ddd\n",  //
3947                "eeee\n", //
3948                "jj"      //
3949            )
3950        );
3951
3952        assert_eq!(
3953            subscription.consume().into_inner(),
3954            [Edit {
3955                old: 6..8,
3956                new: 6..7
3957            }]
3958        );
3959
3960        let snapshot = multibuffer.read(cx).snapshot(cx);
3961        assert_eq!(
3962            snapshot.clip_point(Point::new(0, 5), Bias::Left),
3963            Point::new(0, 4)
3964        );
3965        assert_eq!(
3966            snapshot.clip_point(Point::new(0, 5), Bias::Right),
3967            Point::new(0, 4)
3968        );
3969        assert_eq!(
3970            snapshot.clip_point(Point::new(5, 1), Bias::Right),
3971            Point::new(5, 1)
3972        );
3973        assert_eq!(
3974            snapshot.clip_point(Point::new(5, 2), Bias::Right),
3975            Point::new(5, 2)
3976        );
3977        assert_eq!(
3978            snapshot.clip_point(Point::new(5, 3), Bias::Right),
3979            Point::new(5, 2)
3980        );
3981
3982        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
3983            let (buffer_2_excerpt_id, _) =
3984                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
3985            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
3986            multibuffer.snapshot(cx)
3987        });
3988
3989        assert_eq!(
3990            snapshot.text(),
3991            concat!(
3992                "bbbb\n", // Preserve newlines
3993                "c\n",    //
3994                "cc\n",   //
3995                "ddd\n",  //
3996                "eeee",   //
3997            )
3998        );
3999
4000        fn boundaries_in_range(
4001            range: Range<Point>,
4002            snapshot: &MultiBufferSnapshot,
4003        ) -> Vec<(u32, String, bool)> {
4004            snapshot
4005                .excerpt_boundaries_in_range(range)
4006                .map(|boundary| {
4007                    (
4008                        boundary.row,
4009                        boundary
4010                            .buffer
4011                            .text_for_range(boundary.range.context)
4012                            .collect::<String>(),
4013                        boundary.starts_new_buffer,
4014                    )
4015                })
4016                .collect::<Vec<_>>()
4017        }
4018    }
4019
4020    #[gpui::test]
4021    fn test_excerpt_events(cx: &mut AppContext) {
4022        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4023        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4024
4025        let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4026        let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4027
4028        follower_multibuffer.update(cx, |_, cx| {
4029            cx.subscribe(&leader_multibuffer, |follower, _, event, cx| {
4030                match event.clone() {
4031                    Event::ExcerptsAdded {
4032                        buffer,
4033                        predecessor,
4034                        excerpts,
4035                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4036                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4037                    _ => {}
4038                }
4039            })
4040            .detach();
4041        });
4042
4043        leader_multibuffer.update(cx, |leader, cx| {
4044            leader.push_excerpts(
4045                buffer_1.clone(),
4046                [
4047                    ExcerptRange {
4048                        context: 0..8,
4049                        primary: None,
4050                    },
4051                    ExcerptRange {
4052                        context: 12..16,
4053                        primary: None,
4054                    },
4055                ],
4056                cx,
4057            );
4058            leader.insert_excerpts_after(
4059                leader.excerpt_ids()[0],
4060                buffer_2.clone(),
4061                [
4062                    ExcerptRange {
4063                        context: 0..5,
4064                        primary: None,
4065                    },
4066                    ExcerptRange {
4067                        context: 10..15,
4068                        primary: None,
4069                    },
4070                ],
4071                cx,
4072            )
4073        });
4074        assert_eq!(
4075            leader_multibuffer.read(cx).snapshot(cx).text(),
4076            follower_multibuffer.read(cx).snapshot(cx).text(),
4077        );
4078
4079        leader_multibuffer.update(cx, |leader, cx| {
4080            let excerpt_ids = leader.excerpt_ids();
4081            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4082        });
4083        assert_eq!(
4084            leader_multibuffer.read(cx).snapshot(cx).text(),
4085            follower_multibuffer.read(cx).snapshot(cx).text(),
4086        );
4087
4088        leader_multibuffer.update(cx, |leader, cx| {
4089            leader.clear(cx);
4090        });
4091        assert_eq!(
4092            leader_multibuffer.read(cx).snapshot(cx).text(),
4093            follower_multibuffer.read(cx).snapshot(cx).text(),
4094        );
4095    }
4096
4097    #[gpui::test]
4098    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4099        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4100        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4101        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4102            multibuffer.push_excerpts_with_context_lines(
4103                buffer.clone(),
4104                vec![
4105                    Point::new(3, 2)..Point::new(4, 2),
4106                    Point::new(7, 1)..Point::new(7, 3),
4107                    Point::new(15, 0)..Point::new(15, 0),
4108                ],
4109                2,
4110                cx,
4111            )
4112        });
4113
4114        let snapshot = multibuffer.read(cx).snapshot(cx);
4115        assert_eq!(
4116            snapshot.text(),
4117            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4118        );
4119
4120        assert_eq!(
4121            anchor_ranges
4122                .iter()
4123                .map(|range| range.to_point(&snapshot))
4124                .collect::<Vec<_>>(),
4125            vec![
4126                Point::new(2, 2)..Point::new(3, 2),
4127                Point::new(6, 1)..Point::new(6, 3),
4128                Point::new(12, 0)..Point::new(12, 0)
4129            ]
4130        );
4131    }
4132
4133    #[gpui::test]
4134    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4135        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4136        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4137        let (task, anchor_ranges) = multibuffer.update(cx, |multibuffer, cx| {
4138            let snapshot = buffer.read(cx);
4139            let ranges = vec![
4140                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4141                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4142                snapshot.anchor_before(Point::new(15, 0))
4143                    ..snapshot.anchor_before(Point::new(15, 0)),
4144            ];
4145            multibuffer.stream_excerpts_with_context_lines(vec![(buffer.clone(), ranges)], 2, cx)
4146        });
4147
4148        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4149        // Ensure task is finished when stream completes.
4150        task.await;
4151
4152        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4153        assert_eq!(
4154            snapshot.text(),
4155            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4156        );
4157
4158        assert_eq!(
4159            anchor_ranges
4160                .iter()
4161                .map(|range| range.to_point(&snapshot))
4162                .collect::<Vec<_>>(),
4163            vec![
4164                Point::new(2, 2)..Point::new(3, 2),
4165                Point::new(6, 1)..Point::new(6, 3),
4166                Point::new(12, 0)..Point::new(12, 0)
4167            ]
4168        );
4169    }
4170
4171    #[gpui::test]
4172    fn test_empty_multibuffer(cx: &mut AppContext) {
4173        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4174
4175        let snapshot = multibuffer.read(cx).snapshot(cx);
4176        assert_eq!(snapshot.text(), "");
4177        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4178        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4179    }
4180
4181    #[gpui::test]
4182    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
4183        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4184        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4185        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4186        buffer.update(cx, |buffer, cx| {
4187            buffer.edit([(0..0, "X")], None, cx);
4188            buffer.edit([(5..5, "Y")], None, cx);
4189        });
4190        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4191
4192        assert_eq!(old_snapshot.text(), "abcd");
4193        assert_eq!(new_snapshot.text(), "XabcdY");
4194
4195        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4196        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4197        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4198        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4199    }
4200
4201    #[gpui::test]
4202    fn test_multibuffer_anchors(cx: &mut AppContext) {
4203        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4204        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4205        let multibuffer = cx.add_model(|cx| {
4206            let mut multibuffer = MultiBuffer::new(0);
4207            multibuffer.push_excerpts(
4208                buffer_1.clone(),
4209                [ExcerptRange {
4210                    context: 0..4,
4211                    primary: None,
4212                }],
4213                cx,
4214            );
4215            multibuffer.push_excerpts(
4216                buffer_2.clone(),
4217                [ExcerptRange {
4218                    context: 0..5,
4219                    primary: None,
4220                }],
4221                cx,
4222            );
4223            multibuffer
4224        });
4225        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4226
4227        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4228        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4229        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4230        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4231        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4232        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4233
4234        buffer_1.update(cx, |buffer, cx| {
4235            buffer.edit([(0..0, "W")], None, cx);
4236            buffer.edit([(5..5, "X")], None, cx);
4237        });
4238        buffer_2.update(cx, |buffer, cx| {
4239            buffer.edit([(0..0, "Y")], None, cx);
4240            buffer.edit([(6..6, "Z")], None, cx);
4241        });
4242        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4243
4244        assert_eq!(old_snapshot.text(), "abcd\nefghi");
4245        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4246
4247        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4248        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4249        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4250        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4251        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4252        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4253        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4254        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4255        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4256        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4257    }
4258
4259    #[gpui::test]
4260    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
4261        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4262        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4263        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4264
4265        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4266        // Add an excerpt from buffer 1 that spans this new insertion.
4267        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4268        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4269            multibuffer
4270                .push_excerpts(
4271                    buffer_1.clone(),
4272                    [ExcerptRange {
4273                        context: 0..7,
4274                        primary: None,
4275                    }],
4276                    cx,
4277                )
4278                .pop()
4279                .unwrap()
4280        });
4281
4282        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4283        assert_eq!(snapshot_1.text(), "abcd123");
4284
4285        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4286        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4287            multibuffer.remove_excerpts([excerpt_id_1], cx);
4288            let mut ids = multibuffer
4289                .push_excerpts(
4290                    buffer_2.clone(),
4291                    [
4292                        ExcerptRange {
4293                            context: 0..4,
4294                            primary: None,
4295                        },
4296                        ExcerptRange {
4297                            context: 6..10,
4298                            primary: None,
4299                        },
4300                        ExcerptRange {
4301                            context: 12..16,
4302                            primary: None,
4303                        },
4304                    ],
4305                    cx,
4306                )
4307                .into_iter();
4308            (ids.next().unwrap(), ids.next().unwrap())
4309        });
4310        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4311        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4312
4313        // The old excerpt id doesn't get reused.
4314        assert_ne!(excerpt_id_2, excerpt_id_1);
4315
4316        // Resolve some anchors from the previous snapshot in the new snapshot.
4317        // The current excerpts are from a different buffer, so we don't attempt to
4318        // resolve the old text anchor in the new buffer.
4319        assert_eq!(
4320            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4321            0
4322        );
4323        assert_eq!(
4324            snapshot_2.summaries_for_anchors::<usize, _>(&[
4325                snapshot_1.anchor_before(2),
4326                snapshot_1.anchor_after(3)
4327            ]),
4328            vec![0, 0]
4329        );
4330
4331        // Refresh anchors from the old snapshot. The return value indicates that both
4332        // anchors lost their original excerpt.
4333        let refresh =
4334            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4335        assert_eq!(
4336            refresh,
4337            &[
4338                (0, snapshot_2.anchor_before(0), false),
4339                (1, snapshot_2.anchor_after(0), false),
4340            ]
4341        );
4342
4343        // Replace the middle excerpt with a smaller excerpt in buffer 2,
4344        // that intersects the old excerpt.
4345        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4346            multibuffer.remove_excerpts([excerpt_id_3], cx);
4347            multibuffer
4348                .insert_excerpts_after(
4349                    excerpt_id_2,
4350                    buffer_2.clone(),
4351                    [ExcerptRange {
4352                        context: 5..8,
4353                        primary: None,
4354                    }],
4355                    cx,
4356                )
4357                .pop()
4358                .unwrap()
4359        });
4360
4361        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4362        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4363        assert_ne!(excerpt_id_5, excerpt_id_3);
4364
4365        // Resolve some anchors from the previous snapshot in the new snapshot.
4366        // The third anchor can't be resolved, since its excerpt has been removed,
4367        // so it resolves to the same position as its predecessor.
4368        let anchors = [
4369            snapshot_2.anchor_before(0),
4370            snapshot_2.anchor_after(2),
4371            snapshot_2.anchor_after(6),
4372            snapshot_2.anchor_after(14),
4373        ];
4374        assert_eq!(
4375            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4376            &[0, 2, 9, 13]
4377        );
4378
4379        let new_anchors = snapshot_3.refresh_anchors(&anchors);
4380        assert_eq!(
4381            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4382            &[(0, true), (1, true), (2, true), (3, true)]
4383        );
4384        assert_eq!(
4385            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4386            &[0, 2, 7, 13]
4387        );
4388    }
4389
4390    #[gpui::test]
4391    async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4392        use git::diff::DiffHunkStatus;
4393
4394        // buffer has two modified hunks with two rows each
4395        let buffer_1 = cx.add_model(|cx| {
4396            let mut buffer = Buffer::new(
4397                0,
4398                "
4399                1.zero
4400                1.ONE
4401                1.TWO
4402                1.three
4403                1.FOUR
4404                1.FIVE
4405                1.six
4406            "
4407                .unindent(),
4408                cx,
4409            );
4410            buffer.set_diff_base(
4411                Some(
4412                    "
4413                1.zero
4414                1.one
4415                1.two
4416                1.three
4417                1.four
4418                1.five
4419                1.six
4420            "
4421                    .unindent(),
4422                ),
4423                cx,
4424            );
4425            buffer
4426        });
4427
4428        // buffer has a deletion hunk and an insertion hunk
4429        let buffer_2 = cx.add_model(|cx| {
4430            let mut buffer = Buffer::new(
4431                0,
4432                "
4433                2.zero
4434                2.one
4435                2.two
4436                2.three
4437                2.four
4438                2.five
4439                2.six
4440            "
4441                .unindent(),
4442                cx,
4443            );
4444            buffer.set_diff_base(
4445                Some(
4446                    "
4447                2.zero
4448                2.one
4449                2.one-and-a-half
4450                2.two
4451                2.three
4452                2.four
4453                2.six
4454            "
4455                    .unindent(),
4456                ),
4457                cx,
4458            );
4459            buffer
4460        });
4461
4462        cx.foreground().run_until_parked();
4463
4464        let multibuffer = cx.add_model(|cx| {
4465            let mut multibuffer = MultiBuffer::new(0);
4466            multibuffer.push_excerpts(
4467                buffer_1.clone(),
4468                [
4469                    // excerpt ends in the middle of a modified hunk
4470                    ExcerptRange {
4471                        context: Point::new(0, 0)..Point::new(1, 5),
4472                        primary: Default::default(),
4473                    },
4474                    // excerpt begins in the middle of a modified hunk
4475                    ExcerptRange {
4476                        context: Point::new(5, 0)..Point::new(6, 5),
4477                        primary: Default::default(),
4478                    },
4479                ],
4480                cx,
4481            );
4482            multibuffer.push_excerpts(
4483                buffer_2.clone(),
4484                [
4485                    // excerpt ends at a deletion
4486                    ExcerptRange {
4487                        context: Point::new(0, 0)..Point::new(1, 5),
4488                        primary: Default::default(),
4489                    },
4490                    // excerpt starts at a deletion
4491                    ExcerptRange {
4492                        context: Point::new(2, 0)..Point::new(2, 5),
4493                        primary: Default::default(),
4494                    },
4495                    // excerpt fully contains a deletion hunk
4496                    ExcerptRange {
4497                        context: Point::new(1, 0)..Point::new(2, 5),
4498                        primary: Default::default(),
4499                    },
4500                    // excerpt fully contains an insertion hunk
4501                    ExcerptRange {
4502                        context: Point::new(4, 0)..Point::new(6, 5),
4503                        primary: Default::default(),
4504                    },
4505                ],
4506                cx,
4507            );
4508            multibuffer
4509        });
4510
4511        let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4512
4513        assert_eq!(
4514            snapshot.text(),
4515            "
4516                1.zero
4517                1.ONE
4518                1.FIVE
4519                1.six
4520                2.zero
4521                2.one
4522                2.two
4523                2.one
4524                2.two
4525                2.four
4526                2.five
4527                2.six"
4528                .unindent()
4529        );
4530
4531        let expected = [
4532            (DiffHunkStatus::Modified, 1..2),
4533            (DiffHunkStatus::Modified, 2..3),
4534            //TODO: Define better when and where removed hunks show up at range extremities
4535            (DiffHunkStatus::Removed, 6..6),
4536            (DiffHunkStatus::Removed, 8..8),
4537            (DiffHunkStatus::Added, 10..11),
4538        ];
4539
4540        assert_eq!(
4541            snapshot
4542                .git_diff_hunks_in_range(0..12, false)
4543                .map(|hunk| (hunk.status(), hunk.buffer_range))
4544                .collect::<Vec<_>>(),
4545            &expected,
4546        );
4547
4548        assert_eq!(
4549            snapshot
4550                .git_diff_hunks_in_range(0..12, true)
4551                .map(|hunk| (hunk.status(), hunk.buffer_range))
4552                .collect::<Vec<_>>(),
4553            expected
4554                .iter()
4555                .rev()
4556                .cloned()
4557                .collect::<Vec<_>>()
4558                .as_slice(),
4559        );
4560    }
4561
4562    #[gpui::test(iterations = 100)]
4563    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
4564        let operations = env::var("OPERATIONS")
4565            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4566            .unwrap_or(10);
4567
4568        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4569        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4570        let mut excerpt_ids = Vec::<ExcerptId>::new();
4571        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4572        let mut anchors = Vec::new();
4573        let mut old_versions = Vec::new();
4574
4575        for _ in 0..operations {
4576            match rng.gen_range(0..100) {
4577                0..=19 if !buffers.is_empty() => {
4578                    let buffer = buffers.choose(&mut rng).unwrap();
4579                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4580                }
4581                20..=29 if !expected_excerpts.is_empty() => {
4582                    let mut ids_to_remove = vec![];
4583                    for _ in 0..rng.gen_range(1..=3) {
4584                        if expected_excerpts.is_empty() {
4585                            break;
4586                        }
4587
4588                        let ix = rng.gen_range(0..expected_excerpts.len());
4589                        ids_to_remove.push(excerpt_ids.remove(ix));
4590                        let (buffer, range) = expected_excerpts.remove(ix);
4591                        let buffer = buffer.read(cx);
4592                        log::info!(
4593                            "Removing excerpt {}: {:?}",
4594                            ix,
4595                            buffer
4596                                .text_for_range(range.to_offset(buffer))
4597                                .collect::<String>(),
4598                        );
4599                    }
4600                    let snapshot = multibuffer.read(cx).read(cx);
4601                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4602                    drop(snapshot);
4603                    multibuffer.update(cx, |multibuffer, cx| {
4604                        multibuffer.remove_excerpts(ids_to_remove, cx)
4605                    });
4606                }
4607                30..=39 if !expected_excerpts.is_empty() => {
4608                    let multibuffer = multibuffer.read(cx).read(cx);
4609                    let offset =
4610                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4611                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4612                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4613                    anchors.push(multibuffer.anchor_at(offset, bias));
4614                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4615                }
4616                40..=44 if !anchors.is_empty() => {
4617                    let multibuffer = multibuffer.read(cx).read(cx);
4618                    let prev_len = anchors.len();
4619                    anchors = multibuffer
4620                        .refresh_anchors(&anchors)
4621                        .into_iter()
4622                        .map(|a| a.1)
4623                        .collect();
4624
4625                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4626                    // overshoot its boundaries.
4627                    assert_eq!(anchors.len(), prev_len);
4628                    for anchor in &anchors {
4629                        if anchor.excerpt_id == ExcerptId::min()
4630                            || anchor.excerpt_id == ExcerptId::max()
4631                        {
4632                            continue;
4633                        }
4634
4635                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4636                        assert_eq!(excerpt.id, anchor.excerpt_id);
4637                        assert!(excerpt.contains(anchor));
4638                    }
4639                }
4640                _ => {
4641                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4642                        let base_text = util::RandomCharIter::new(&mut rng)
4643                            .take(10)
4644                            .collect::<String>();
4645                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4646                        buffers.last().unwrap()
4647                    } else {
4648                        buffers.choose(&mut rng).unwrap()
4649                    };
4650
4651                    let buffer = buffer_handle.read(cx);
4652                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4653                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4654                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4655                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4656                    let prev_excerpt_id = excerpt_ids
4657                        .get(prev_excerpt_ix)
4658                        .cloned()
4659                        .unwrap_or_else(ExcerptId::max);
4660                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4661
4662                    log::info!(
4663                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4664                        excerpt_ix,
4665                        expected_excerpts.len(),
4666                        buffer_handle.id(),
4667                        buffer.text(),
4668                        start_ix..end_ix,
4669                        &buffer.text()[start_ix..end_ix]
4670                    );
4671
4672                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4673                        multibuffer
4674                            .insert_excerpts_after(
4675                                prev_excerpt_id,
4676                                buffer_handle.clone(),
4677                                [ExcerptRange {
4678                                    context: start_ix..end_ix,
4679                                    primary: None,
4680                                }],
4681                                cx,
4682                            )
4683                            .pop()
4684                            .unwrap()
4685                    });
4686
4687                    excerpt_ids.insert(excerpt_ix, excerpt_id);
4688                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
4689                }
4690            }
4691
4692            if rng.gen_bool(0.3) {
4693                multibuffer.update(cx, |multibuffer, cx| {
4694                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
4695                })
4696            }
4697
4698            let snapshot = multibuffer.read(cx).snapshot(cx);
4699
4700            let mut excerpt_starts = Vec::new();
4701            let mut expected_text = String::new();
4702            let mut expected_buffer_rows = Vec::new();
4703            for (buffer, range) in &expected_excerpts {
4704                let buffer = buffer.read(cx);
4705                let buffer_range = range.to_offset(buffer);
4706
4707                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
4708                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
4709                expected_text.push('\n');
4710
4711                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
4712                    ..=buffer.offset_to_point(buffer_range.end).row;
4713                for row in buffer_row_range {
4714                    expected_buffer_rows.push(Some(row));
4715                }
4716            }
4717            // Remove final trailing newline.
4718            if !expected_excerpts.is_empty() {
4719                expected_text.pop();
4720            }
4721
4722            // Always report one buffer row
4723            if expected_buffer_rows.is_empty() {
4724                expected_buffer_rows.push(Some(0));
4725            }
4726
4727            assert_eq!(snapshot.text(), expected_text);
4728            log::info!("MultiBuffer text: {:?}", expected_text);
4729
4730            assert_eq!(
4731                snapshot.buffer_rows(0).collect::<Vec<_>>(),
4732                expected_buffer_rows,
4733            );
4734
4735            for _ in 0..5 {
4736                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
4737                assert_eq!(
4738                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
4739                    &expected_buffer_rows[start_row..],
4740                    "buffer_rows({})",
4741                    start_row
4742                );
4743            }
4744
4745            assert_eq!(
4746                snapshot.max_buffer_row(),
4747                expected_buffer_rows.into_iter().flatten().max().unwrap()
4748            );
4749
4750            let mut excerpt_starts = excerpt_starts.into_iter();
4751            for (buffer, range) in &expected_excerpts {
4752                let buffer_id = buffer.id();
4753                let buffer = buffer.read(cx);
4754                let buffer_range = range.to_offset(buffer);
4755                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
4756                let buffer_start_point_utf16 =
4757                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
4758
4759                let excerpt_start = excerpt_starts.next().unwrap();
4760                let mut offset = excerpt_start.len;
4761                let mut buffer_offset = buffer_range.start;
4762                let mut point = excerpt_start.lines;
4763                let mut buffer_point = buffer_start_point;
4764                let mut point_utf16 = excerpt_start.lines_utf16();
4765                let mut buffer_point_utf16 = buffer_start_point_utf16;
4766                for ch in buffer
4767                    .snapshot()
4768                    .chunks(buffer_range.clone(), false)
4769                    .flat_map(|c| c.text.chars())
4770                {
4771                    for _ in 0..ch.len_utf8() {
4772                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
4773                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
4774                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
4775                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
4776                        assert_eq!(
4777                            left_offset,
4778                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
4779                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
4780                            offset,
4781                            buffer_id,
4782                            buffer_offset,
4783                        );
4784                        assert_eq!(
4785                            right_offset,
4786                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
4787                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
4788                            offset,
4789                            buffer_id,
4790                            buffer_offset,
4791                        );
4792
4793                        let left_point = snapshot.clip_point(point, Bias::Left);
4794                        let right_point = snapshot.clip_point(point, Bias::Right);
4795                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
4796                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
4797                        assert_eq!(
4798                            left_point,
4799                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
4800                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
4801                            point,
4802                            buffer_id,
4803                            buffer_point,
4804                        );
4805                        assert_eq!(
4806                            right_point,
4807                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
4808                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
4809                            point,
4810                            buffer_id,
4811                            buffer_point,
4812                        );
4813
4814                        assert_eq!(
4815                            snapshot.point_to_offset(left_point),
4816                            left_offset,
4817                            "point_to_offset({:?})",
4818                            left_point,
4819                        );
4820                        assert_eq!(
4821                            snapshot.offset_to_point(left_offset),
4822                            left_point,
4823                            "offset_to_point({:?})",
4824                            left_offset,
4825                        );
4826
4827                        offset += 1;
4828                        buffer_offset += 1;
4829                        if ch == '\n' {
4830                            point += Point::new(1, 0);
4831                            buffer_point += Point::new(1, 0);
4832                        } else {
4833                            point += Point::new(0, 1);
4834                            buffer_point += Point::new(0, 1);
4835                        }
4836                    }
4837
4838                    for _ in 0..ch.len_utf16() {
4839                        let left_point_utf16 =
4840                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
4841                        let right_point_utf16 =
4842                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
4843                        let buffer_left_point_utf16 =
4844                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
4845                        let buffer_right_point_utf16 =
4846                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
4847                        assert_eq!(
4848                            left_point_utf16,
4849                            excerpt_start.lines_utf16()
4850                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
4851                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4852                            point_utf16,
4853                            buffer_id,
4854                            buffer_point_utf16,
4855                        );
4856                        assert_eq!(
4857                            right_point_utf16,
4858                            excerpt_start.lines_utf16()
4859                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
4860                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4861                            point_utf16,
4862                            buffer_id,
4863                            buffer_point_utf16,
4864                        );
4865
4866                        if ch == '\n' {
4867                            point_utf16 += PointUtf16::new(1, 0);
4868                            buffer_point_utf16 += PointUtf16::new(1, 0);
4869                        } else {
4870                            point_utf16 += PointUtf16::new(0, 1);
4871                            buffer_point_utf16 += PointUtf16::new(0, 1);
4872                        }
4873                    }
4874                }
4875            }
4876
4877            for (row, line) in expected_text.split('\n').enumerate() {
4878                assert_eq!(
4879                    snapshot.line_len(row as u32),
4880                    line.len() as u32,
4881                    "line_len({}).",
4882                    row
4883                );
4884            }
4885
4886            let text_rope = Rope::from(expected_text.as_str());
4887            for _ in 0..10 {
4888                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4889                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4890
4891                let text_for_range = snapshot
4892                    .text_for_range(start_ix..end_ix)
4893                    .collect::<String>();
4894                assert_eq!(
4895                    text_for_range,
4896                    &expected_text[start_ix..end_ix],
4897                    "incorrect text for range {:?}",
4898                    start_ix..end_ix
4899                );
4900
4901                let excerpted_buffer_ranges = multibuffer
4902                    .read(cx)
4903                    .range_to_buffer_ranges(start_ix..end_ix, cx);
4904                let excerpted_buffers_text = excerpted_buffer_ranges
4905                    .into_iter()
4906                    .map(|(buffer, buffer_range)| {
4907                        buffer
4908                            .read(cx)
4909                            .text_for_range(buffer_range)
4910                            .collect::<String>()
4911                    })
4912                    .collect::<Vec<_>>()
4913                    .join("\n");
4914                assert_eq!(excerpted_buffers_text, text_for_range);
4915
4916                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
4917                assert_eq!(
4918                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
4919                    expected_summary,
4920                    "incorrect summary for range {:?}",
4921                    start_ix..end_ix
4922                );
4923            }
4924
4925            // Anchor resolution
4926            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
4927            assert_eq!(anchors.len(), summaries.len());
4928            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
4929                assert!(resolved_offset <= snapshot.len());
4930                assert_eq!(
4931                    snapshot.summary_for_anchor::<usize>(anchor),
4932                    resolved_offset
4933                );
4934            }
4935
4936            for _ in 0..10 {
4937                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4938                assert_eq!(
4939                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
4940                    expected_text[..end_ix].chars().rev().collect::<String>(),
4941                );
4942            }
4943
4944            for _ in 0..10 {
4945                let end_ix = rng.gen_range(0..=text_rope.len());
4946                let start_ix = rng.gen_range(0..=end_ix);
4947                assert_eq!(
4948                    snapshot
4949                        .bytes_in_range(start_ix..end_ix)
4950                        .flatten()
4951                        .copied()
4952                        .collect::<Vec<_>>(),
4953                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
4954                    "bytes_in_range({:?})",
4955                    start_ix..end_ix,
4956                );
4957            }
4958        }
4959
4960        let snapshot = multibuffer.read(cx).snapshot(cx);
4961        for (old_snapshot, subscription) in old_versions {
4962            let edits = subscription.consume().into_inner();
4963
4964            log::info!(
4965                "applying subscription edits to old text: {:?}: {:?}",
4966                old_snapshot.text(),
4967                edits,
4968            );
4969
4970            let mut text = old_snapshot.text();
4971            for edit in edits {
4972                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
4973                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
4974            }
4975            assert_eq!(text.to_string(), snapshot.text());
4976        }
4977    }
4978
4979    #[gpui::test]
4980    fn test_history(cx: &mut AppContext) {
4981        cx.set_global(Settings::test(cx));
4982        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
4983        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
4984        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4985        let group_interval = multibuffer.read(cx).history.group_interval;
4986        multibuffer.update(cx, |multibuffer, cx| {
4987            multibuffer.push_excerpts(
4988                buffer_1.clone(),
4989                [ExcerptRange {
4990                    context: 0..buffer_1.read(cx).len(),
4991                    primary: None,
4992                }],
4993                cx,
4994            );
4995            multibuffer.push_excerpts(
4996                buffer_2.clone(),
4997                [ExcerptRange {
4998                    context: 0..buffer_2.read(cx).len(),
4999                    primary: None,
5000                }],
5001                cx,
5002            );
5003        });
5004
5005        let mut now = Instant::now();
5006
5007        multibuffer.update(cx, |multibuffer, cx| {
5008            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5009            multibuffer.edit(
5010                [
5011                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5012                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5013                ],
5014                None,
5015                cx,
5016            );
5017            multibuffer.edit(
5018                [
5019                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5020                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5021                ],
5022                None,
5023                cx,
5024            );
5025            multibuffer.end_transaction_at(now, cx);
5026            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5027
5028            // Edit buffer 1 through the multibuffer
5029            now += 2 * group_interval;
5030            multibuffer.start_transaction_at(now, cx);
5031            multibuffer.edit([(2..2, "C")], None, cx);
5032            multibuffer.end_transaction_at(now, cx);
5033            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5034
5035            // Edit buffer 1 independently
5036            buffer_1.update(cx, |buffer_1, cx| {
5037                buffer_1.start_transaction_at(now);
5038                buffer_1.edit([(3..3, "D")], None, cx);
5039                buffer_1.end_transaction_at(now, cx);
5040
5041                now += 2 * group_interval;
5042                buffer_1.start_transaction_at(now);
5043                buffer_1.edit([(4..4, "E")], None, cx);
5044                buffer_1.end_transaction_at(now, cx);
5045            });
5046            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5047
5048            // An undo in the multibuffer undoes the multibuffer transaction
5049            // and also any individual buffer edits that have occured since
5050            // that transaction.
5051            multibuffer.undo(cx);
5052            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5053
5054            multibuffer.undo(cx);
5055            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5056
5057            multibuffer.redo(cx);
5058            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5059
5060            multibuffer.redo(cx);
5061            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5062
5063            // Undo buffer 2 independently.
5064            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5065            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5066
5067            // An undo in the multibuffer undoes the components of the
5068            // the last multibuffer transaction that are not already undone.
5069            multibuffer.undo(cx);
5070            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5071
5072            multibuffer.undo(cx);
5073            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5074
5075            multibuffer.redo(cx);
5076            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5077
5078            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5079            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5080
5081            // Redo stack gets cleared after an edit.
5082            now += 2 * group_interval;
5083            multibuffer.start_transaction_at(now, cx);
5084            multibuffer.edit([(0..0, "X")], None, cx);
5085            multibuffer.end_transaction_at(now, cx);
5086            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5087            multibuffer.redo(cx);
5088            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5089            multibuffer.undo(cx);
5090            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5091            multibuffer.undo(cx);
5092            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5093
5094            // Transactions can be grouped manually.
5095            multibuffer.redo(cx);
5096            multibuffer.redo(cx);
5097            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5098            multibuffer.group_until_transaction(transaction_1, cx);
5099            multibuffer.undo(cx);
5100            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5101            multibuffer.redo(cx);
5102            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5103        });
5104    }
5105}