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