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