multi_buffer.rs

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