multi_buffer.rs

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