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 git_diff_hunks_in_range<'a>(
2845        &'a self,
2846        row_range: Range<u32>,
2847        reversed: bool,
2848    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2849        let mut cursor = self.excerpts.cursor::<Point>();
2850
2851        if reversed {
2852            cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2853            if cursor.item().is_none() {
2854                cursor.prev(&());
2855            }
2856        } else {
2857            cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
2858        }
2859
2860        std::iter::from_fn(move || {
2861            let excerpt = cursor.item()?;
2862            let multibuffer_start = *cursor.start();
2863            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2864            if multibuffer_start.row >= row_range.end {
2865                return None;
2866            }
2867
2868            let mut buffer_start = excerpt.range.context.start;
2869            let mut buffer_end = excerpt.range.context.end;
2870            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2871            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2872
2873            if row_range.start > multibuffer_start.row {
2874                let buffer_start_point =
2875                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2876                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2877            }
2878
2879            if row_range.end < multibuffer_end.row {
2880                let buffer_end_point =
2881                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2882                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2883            }
2884
2885            let buffer_hunks = excerpt
2886                .buffer
2887                .git_diff_hunks_intersecting_range(buffer_start..buffer_end, reversed)
2888                .filter_map(move |hunk| {
2889                    let start = multibuffer_start.row
2890                        + hunk
2891                            .buffer_range
2892                            .start
2893                            .saturating_sub(excerpt_start_point.row);
2894                    let end = multibuffer_start.row
2895                        + hunk
2896                            .buffer_range
2897                            .end
2898                            .min(excerpt_end_point.row + 1)
2899                            .saturating_sub(excerpt_start_point.row);
2900
2901                    Some(DiffHunk {
2902                        buffer_range: start..end,
2903                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2904                    })
2905                });
2906
2907            if reversed {
2908                cursor.prev(&());
2909            } else {
2910                cursor.next(&());
2911            }
2912
2913            Some(buffer_hunks)
2914        })
2915        .flatten()
2916    }
2917
2918    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2919        let range = range.start.to_offset(self)..range.end.to_offset(self);
2920
2921        self.excerpt_containing(range.clone())
2922            .and_then(|(excerpt, excerpt_offset)| {
2923                let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2924                let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2925
2926                let start_in_buffer =
2927                    excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2928                let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2929                let mut ancestor_buffer_range = excerpt
2930                    .buffer
2931                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2932                ancestor_buffer_range.start =
2933                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2934                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2935
2936                let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
2937                let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
2938                Some(start..end)
2939            })
2940    }
2941
2942    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2943        let (excerpt_id, _, buffer) = self.as_singleton()?;
2944        let outline = buffer.outline(theme)?;
2945        Some(Outline::new(
2946            outline
2947                .items
2948                .into_iter()
2949                .map(|item| OutlineItem {
2950                    depth: item.depth,
2951                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2952                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2953                    text: item.text,
2954                    highlight_ranges: item.highlight_ranges,
2955                    name_ranges: item.name_ranges,
2956                })
2957                .collect(),
2958        ))
2959    }
2960
2961    pub fn symbols_containing<T: ToOffset>(
2962        &self,
2963        offset: T,
2964        theme: Option<&SyntaxTheme>,
2965    ) -> Option<(u64, Vec<OutlineItem<Anchor>>)> {
2966        let anchor = self.anchor_before(offset);
2967        let excerpt_id = anchor.excerpt_id();
2968        let excerpt = self.excerpt(excerpt_id)?;
2969        Some((
2970            excerpt.buffer_id,
2971            excerpt
2972                .buffer
2973                .symbols_containing(anchor.text_anchor, theme)
2974                .into_iter()
2975                .flatten()
2976                .map(|item| OutlineItem {
2977                    depth: item.depth,
2978                    range: self.anchor_in_excerpt(excerpt_id, item.range.start)
2979                        ..self.anchor_in_excerpt(excerpt_id, item.range.end),
2980                    text: item.text,
2981                    highlight_ranges: item.highlight_ranges,
2982                    name_ranges: item.name_ranges,
2983                })
2984                .collect(),
2985        ))
2986    }
2987
2988    fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
2989        if id == ExcerptId::min() {
2990            Locator::min_ref()
2991        } else if id == ExcerptId::max() {
2992            Locator::max_ref()
2993        } else {
2994            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
2995            cursor.seek(&id, Bias::Left, &());
2996            if let Some(entry) = cursor.item() {
2997                if entry.id == id {
2998                    return &entry.locator;
2999                }
3000            }
3001            panic!("invalid excerpt id {:?}", id)
3002        }
3003    }
3004
3005    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<u64> {
3006        Some(self.excerpt(excerpt_id)?.buffer_id)
3007    }
3008
3009    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3010        Some(&self.excerpt(excerpt_id)?.buffer)
3011    }
3012
3013    fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
3014        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3015        let locator = self.excerpt_locator_for_id(excerpt_id);
3016        cursor.seek(&Some(locator), Bias::Left, &());
3017        if let Some(excerpt) = cursor.item() {
3018            if excerpt.id == excerpt_id {
3019                return Some(excerpt);
3020            }
3021        }
3022        None
3023    }
3024
3025    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3026    fn excerpt_containing<'a, T: ToOffset>(
3027        &'a self,
3028        range: Range<T>,
3029    ) -> Option<(&'a Excerpt, usize)> {
3030        let range = range.start.to_offset(self)..range.end.to_offset(self);
3031
3032        let mut cursor = self.excerpts.cursor::<usize>();
3033        cursor.seek(&range.start, Bias::Right, &());
3034        let start_excerpt = cursor.item();
3035
3036        if range.start == range.end {
3037            return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
3038        }
3039
3040        cursor.seek(&range.end, Bias::Right, &());
3041        let end_excerpt = cursor.item();
3042
3043        start_excerpt
3044            .zip(end_excerpt)
3045            .and_then(|(start_excerpt, end_excerpt)| {
3046                if start_excerpt.id != end_excerpt.id {
3047                    return None;
3048                }
3049
3050                Some((start_excerpt, *cursor.start()))
3051            })
3052    }
3053
3054    pub fn remote_selections_in_range<'a>(
3055        &'a self,
3056        range: &'a Range<Anchor>,
3057    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3058        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3059        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3060        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3061        cursor.seek(start_locator, Bias::Left, &());
3062        cursor
3063            .take_while(move |excerpt| excerpt.locator <= *end_locator)
3064            .flat_map(move |excerpt| {
3065                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3066                if excerpt.id == range.start.excerpt_id {
3067                    query_range.start = range.start.text_anchor;
3068                }
3069                if excerpt.id == range.end.excerpt_id {
3070                    query_range.end = range.end.text_anchor;
3071                }
3072
3073                excerpt
3074                    .buffer
3075                    .remote_selections_in_range(query_range)
3076                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3077                        selections.map(move |selection| {
3078                            let mut start = Anchor {
3079                                buffer_id: Some(excerpt.buffer_id),
3080                                excerpt_id: excerpt.id.clone(),
3081                                text_anchor: selection.start,
3082                            };
3083                            let mut end = Anchor {
3084                                buffer_id: Some(excerpt.buffer_id),
3085                                excerpt_id: excerpt.id.clone(),
3086                                text_anchor: selection.end,
3087                            };
3088                            if range.start.cmp(&start, self).is_gt() {
3089                                start = range.start.clone();
3090                            }
3091                            if range.end.cmp(&end, self).is_lt() {
3092                                end = range.end.clone();
3093                            }
3094
3095                            (
3096                                replica_id,
3097                                line_mode,
3098                                cursor_shape,
3099                                Selection {
3100                                    id: selection.id,
3101                                    start,
3102                                    end,
3103                                    reversed: selection.reversed,
3104                                    goal: selection.goal,
3105                                },
3106                            )
3107                        })
3108                    })
3109            })
3110    }
3111}
3112
3113#[cfg(any(test, feature = "test-support"))]
3114impl MultiBufferSnapshot {
3115    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3116        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3117        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3118        start..end
3119    }
3120}
3121
3122impl History {
3123    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3124        self.transaction_depth += 1;
3125        if self.transaction_depth == 1 {
3126            let id = self.next_transaction_id.tick();
3127            self.undo_stack.push(Transaction {
3128                id,
3129                buffer_transactions: Default::default(),
3130                first_edit_at: now,
3131                last_edit_at: now,
3132                suppress_grouping: false,
3133            });
3134            Some(id)
3135        } else {
3136            None
3137        }
3138    }
3139
3140    fn end_transaction(
3141        &mut self,
3142        now: Instant,
3143        buffer_transactions: HashMap<u64, TransactionId>,
3144    ) -> bool {
3145        assert_ne!(self.transaction_depth, 0);
3146        self.transaction_depth -= 1;
3147        if self.transaction_depth == 0 {
3148            if buffer_transactions.is_empty() {
3149                self.undo_stack.pop();
3150                false
3151            } else {
3152                self.redo_stack.clear();
3153                let transaction = self.undo_stack.last_mut().unwrap();
3154                transaction.last_edit_at = now;
3155                for (buffer_id, transaction_id) in buffer_transactions {
3156                    transaction
3157                        .buffer_transactions
3158                        .entry(buffer_id)
3159                        .or_insert(transaction_id);
3160                }
3161                true
3162            }
3163        } else {
3164            false
3165        }
3166    }
3167
3168    fn push_transaction<'a, T>(
3169        &mut self,
3170        buffer_transactions: T,
3171        now: Instant,
3172        cx: &mut ModelContext<MultiBuffer>,
3173    ) where
3174        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3175    {
3176        assert_eq!(self.transaction_depth, 0);
3177        let transaction = Transaction {
3178            id: self.next_transaction_id.tick(),
3179            buffer_transactions: buffer_transactions
3180                .into_iter()
3181                .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3182                .collect(),
3183            first_edit_at: now,
3184            last_edit_at: now,
3185            suppress_grouping: false,
3186        };
3187        if !transaction.buffer_transactions.is_empty() {
3188            self.undo_stack.push(transaction);
3189            self.redo_stack.clear();
3190        }
3191    }
3192
3193    fn finalize_last_transaction(&mut self) {
3194        if let Some(transaction) = self.undo_stack.last_mut() {
3195            transaction.suppress_grouping = true;
3196        }
3197    }
3198
3199    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3200        assert_eq!(self.transaction_depth, 0);
3201        if let Some(transaction) = self.undo_stack.pop() {
3202            self.redo_stack.push(transaction);
3203            self.redo_stack.last_mut()
3204        } else {
3205            None
3206        }
3207    }
3208
3209    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3210        assert_eq!(self.transaction_depth, 0);
3211        if let Some(transaction) = self.redo_stack.pop() {
3212            self.undo_stack.push(transaction);
3213            self.undo_stack.last_mut()
3214        } else {
3215            None
3216        }
3217    }
3218
3219    fn group(&mut self) -> Option<TransactionId> {
3220        let mut count = 0;
3221        let mut transactions = self.undo_stack.iter();
3222        if let Some(mut transaction) = transactions.next_back() {
3223            while let Some(prev_transaction) = transactions.next_back() {
3224                if !prev_transaction.suppress_grouping
3225                    && transaction.first_edit_at - prev_transaction.last_edit_at
3226                        <= self.group_interval
3227                {
3228                    transaction = prev_transaction;
3229                    count += 1;
3230                } else {
3231                    break;
3232                }
3233            }
3234        }
3235        self.group_trailing(count)
3236    }
3237
3238    fn group_until(&mut self, transaction_id: TransactionId) {
3239        let mut count = 0;
3240        for transaction in self.undo_stack.iter().rev() {
3241            if transaction.id == transaction_id {
3242                self.group_trailing(count);
3243                break;
3244            } else if transaction.suppress_grouping {
3245                break;
3246            } else {
3247                count += 1;
3248            }
3249        }
3250    }
3251
3252    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3253        let new_len = self.undo_stack.len() - n;
3254        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3255        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3256            if let Some(transaction) = transactions_to_merge.last() {
3257                last_transaction.last_edit_at = transaction.last_edit_at;
3258            }
3259            for to_merge in transactions_to_merge {
3260                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3261                    last_transaction
3262                        .buffer_transactions
3263                        .entry(*buffer_id)
3264                        .or_insert(*transaction_id);
3265                }
3266            }
3267        }
3268
3269        self.undo_stack.truncate(new_len);
3270        self.undo_stack.last().map(|t| t.id)
3271    }
3272}
3273
3274impl Excerpt {
3275    fn new(
3276        id: ExcerptId,
3277        locator: Locator,
3278        buffer_id: u64,
3279        buffer: BufferSnapshot,
3280        range: ExcerptRange<text::Anchor>,
3281        has_trailing_newline: bool,
3282    ) -> Self {
3283        Excerpt {
3284            id,
3285            locator,
3286            max_buffer_row: range.context.end.to_point(&buffer).row,
3287            text_summary: buffer
3288                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3289            buffer_id,
3290            buffer,
3291            range,
3292            has_trailing_newline,
3293        }
3294    }
3295
3296    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3297        let content_start = self.range.context.start.to_offset(&self.buffer);
3298        let chunks_start = content_start + range.start;
3299        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3300
3301        let footer_height = if self.has_trailing_newline
3302            && range.start <= self.text_summary.len
3303            && range.end > self.text_summary.len
3304        {
3305            1
3306        } else {
3307            0
3308        };
3309
3310        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3311
3312        ExcerptChunks {
3313            content_chunks,
3314            footer_height,
3315        }
3316    }
3317
3318    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3319        let content_start = self.range.context.start.to_offset(&self.buffer);
3320        let bytes_start = content_start + range.start;
3321        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3322        let footer_height = if self.has_trailing_newline
3323            && range.start <= self.text_summary.len
3324            && range.end > self.text_summary.len
3325        {
3326            1
3327        } else {
3328            0
3329        };
3330        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3331
3332        ExcerptBytes {
3333            content_bytes,
3334            footer_height,
3335        }
3336    }
3337
3338    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3339        if text_anchor
3340            .cmp(&self.range.context.start, &self.buffer)
3341            .is_lt()
3342        {
3343            self.range.context.start
3344        } else if text_anchor
3345            .cmp(&self.range.context.end, &self.buffer)
3346            .is_gt()
3347        {
3348            self.range.context.end
3349        } else {
3350            text_anchor
3351        }
3352    }
3353
3354    fn contains(&self, anchor: &Anchor) -> bool {
3355        Some(self.buffer_id) == anchor.buffer_id
3356            && self
3357                .range
3358                .context
3359                .start
3360                .cmp(&anchor.text_anchor, &self.buffer)
3361                .is_le()
3362            && self
3363                .range
3364                .context
3365                .end
3366                .cmp(&anchor.text_anchor, &self.buffer)
3367                .is_ge()
3368    }
3369}
3370
3371impl ExcerptId {
3372    pub fn min() -> Self {
3373        Self(0)
3374    }
3375
3376    pub fn max() -> Self {
3377        Self(usize::MAX)
3378    }
3379
3380    pub fn to_proto(&self) -> u64 {
3381        self.0 as _
3382    }
3383
3384    pub fn from_proto(proto: u64) -> Self {
3385        Self(proto as _)
3386    }
3387
3388    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3389        let a = snapshot.excerpt_locator_for_id(*self);
3390        let b = snapshot.excerpt_locator_for_id(*other);
3391        a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3392    }
3393}
3394
3395impl Into<usize> for ExcerptId {
3396    fn into(self) -> usize {
3397        self.0
3398    }
3399}
3400
3401impl fmt::Debug for Excerpt {
3402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3403        f.debug_struct("Excerpt")
3404            .field("id", &self.id)
3405            .field("locator", &self.locator)
3406            .field("buffer_id", &self.buffer_id)
3407            .field("range", &self.range)
3408            .field("text_summary", &self.text_summary)
3409            .field("has_trailing_newline", &self.has_trailing_newline)
3410            .finish()
3411    }
3412}
3413
3414impl sum_tree::Item for Excerpt {
3415    type Summary = ExcerptSummary;
3416
3417    fn summary(&self) -> Self::Summary {
3418        let mut text = self.text_summary.clone();
3419        if self.has_trailing_newline {
3420            text += TextSummary::from("\n");
3421        }
3422        ExcerptSummary {
3423            excerpt_id: self.id,
3424            excerpt_locator: self.locator.clone(),
3425            max_buffer_row: self.max_buffer_row,
3426            text,
3427        }
3428    }
3429}
3430
3431impl sum_tree::Item for ExcerptIdMapping {
3432    type Summary = ExcerptId;
3433
3434    fn summary(&self) -> Self::Summary {
3435        self.id
3436    }
3437}
3438
3439impl sum_tree::KeyedItem for ExcerptIdMapping {
3440    type Key = ExcerptId;
3441
3442    fn key(&self) -> Self::Key {
3443        self.id
3444    }
3445}
3446
3447impl sum_tree::Summary for ExcerptId {
3448    type Context = ();
3449
3450    fn add_summary(&mut self, other: &Self, _: &()) {
3451        *self = *other;
3452    }
3453}
3454
3455impl sum_tree::Summary for ExcerptSummary {
3456    type Context = ();
3457
3458    fn add_summary(&mut self, summary: &Self, _: &()) {
3459        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3460        self.excerpt_locator = summary.excerpt_locator.clone();
3461        self.text.add_summary(&summary.text, &());
3462        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3463    }
3464}
3465
3466impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3467    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3468        *self += &summary.text;
3469    }
3470}
3471
3472impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3473    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3474        *self += summary.text.len;
3475    }
3476}
3477
3478impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3479    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3480        Ord::cmp(self, &cursor_location.text.len)
3481    }
3482}
3483
3484impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3485    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3486        Ord::cmp(&Some(self), cursor_location)
3487    }
3488}
3489
3490impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3491    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3492        Ord::cmp(self, &cursor_location.excerpt_locator)
3493    }
3494}
3495
3496impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3497    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3498        *self += summary.text.len_utf16;
3499    }
3500}
3501
3502impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3503    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3504        *self += summary.text.lines;
3505    }
3506}
3507
3508impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3509    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3510        *self += summary.text.lines_utf16()
3511    }
3512}
3513
3514impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3515    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3516        *self = Some(&summary.excerpt_locator);
3517    }
3518}
3519
3520impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3521    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3522        *self = Some(summary.excerpt_id);
3523    }
3524}
3525
3526impl<'a> MultiBufferRows<'a> {
3527    pub fn seek(&mut self, row: u32) {
3528        self.buffer_row_range = 0..0;
3529
3530        self.excerpts
3531            .seek_forward(&Point::new(row, 0), Bias::Right, &());
3532        if self.excerpts.item().is_none() {
3533            self.excerpts.prev(&());
3534
3535            if self.excerpts.item().is_none() && row == 0 {
3536                self.buffer_row_range = 0..1;
3537                return;
3538            }
3539        }
3540
3541        if let Some(excerpt) = self.excerpts.item() {
3542            let overshoot = row - self.excerpts.start().row;
3543            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3544            self.buffer_row_range.start = excerpt_start + overshoot;
3545            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3546        }
3547    }
3548}
3549
3550impl<'a> Iterator for MultiBufferRows<'a> {
3551    type Item = Option<u32>;
3552
3553    fn next(&mut self) -> Option<Self::Item> {
3554        loop {
3555            if !self.buffer_row_range.is_empty() {
3556                let row = Some(self.buffer_row_range.start);
3557                self.buffer_row_range.start += 1;
3558                return Some(row);
3559            }
3560            self.excerpts.item()?;
3561            self.excerpts.next(&());
3562            let excerpt = self.excerpts.item()?;
3563            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3564            self.buffer_row_range.end =
3565                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3566        }
3567    }
3568}
3569
3570impl<'a> MultiBufferChunks<'a> {
3571    pub fn offset(&self) -> usize {
3572        self.range.start
3573    }
3574
3575    pub fn seek(&mut self, offset: usize) {
3576        self.range.start = offset;
3577        self.excerpts.seek(&offset, Bias::Right, &());
3578        if let Some(excerpt) = self.excerpts.item() {
3579            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3580                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3581                self.language_aware,
3582            ));
3583        } else {
3584            self.excerpt_chunks = None;
3585        }
3586    }
3587}
3588
3589impl<'a> Iterator for MultiBufferChunks<'a> {
3590    type Item = Chunk<'a>;
3591
3592    fn next(&mut self) -> Option<Self::Item> {
3593        if self.range.is_empty() {
3594            None
3595        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3596            self.range.start += chunk.text.len();
3597            Some(chunk)
3598        } else {
3599            self.excerpts.next(&());
3600            let excerpt = self.excerpts.item()?;
3601            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3602                0..self.range.end - self.excerpts.start(),
3603                self.language_aware,
3604            ));
3605            self.next()
3606        }
3607    }
3608}
3609
3610impl<'a> MultiBufferBytes<'a> {
3611    fn consume(&mut self, len: usize) {
3612        self.range.start += len;
3613        self.chunk = &self.chunk[len..];
3614
3615        if !self.range.is_empty() && self.chunk.is_empty() {
3616            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3617                self.chunk = chunk;
3618            } else {
3619                self.excerpts.next(&());
3620                if let Some(excerpt) = self.excerpts.item() {
3621                    let mut excerpt_bytes =
3622                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3623                    self.chunk = excerpt_bytes.next().unwrap();
3624                    self.excerpt_bytes = Some(excerpt_bytes);
3625                }
3626            }
3627        }
3628    }
3629}
3630
3631impl<'a> Iterator for MultiBufferBytes<'a> {
3632    type Item = &'a [u8];
3633
3634    fn next(&mut self) -> Option<Self::Item> {
3635        let chunk = self.chunk;
3636        if chunk.is_empty() {
3637            None
3638        } else {
3639            self.consume(chunk.len());
3640            Some(chunk)
3641        }
3642    }
3643}
3644
3645impl<'a> io::Read for MultiBufferBytes<'a> {
3646    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3647        let len = cmp::min(buf.len(), self.chunk.len());
3648        buf[..len].copy_from_slice(&self.chunk[..len]);
3649        if len > 0 {
3650            self.consume(len);
3651        }
3652        Ok(len)
3653    }
3654}
3655
3656impl<'a> Iterator for ExcerptBytes<'a> {
3657    type Item = &'a [u8];
3658
3659    fn next(&mut self) -> Option<Self::Item> {
3660        if let Some(chunk) = self.content_bytes.next() {
3661            if !chunk.is_empty() {
3662                return Some(chunk);
3663            }
3664        }
3665
3666        if self.footer_height > 0 {
3667            let result = &NEWLINES[..self.footer_height];
3668            self.footer_height = 0;
3669            return Some(result);
3670        }
3671
3672        None
3673    }
3674}
3675
3676impl<'a> Iterator for ExcerptChunks<'a> {
3677    type Item = Chunk<'a>;
3678
3679    fn next(&mut self) -> Option<Self::Item> {
3680        if let Some(chunk) = self.content_chunks.next() {
3681            return Some(chunk);
3682        }
3683
3684        if self.footer_height > 0 {
3685            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3686            self.footer_height = 0;
3687            return Some(Chunk {
3688                text,
3689                ..Default::default()
3690            });
3691        }
3692
3693        None
3694    }
3695}
3696
3697impl ToOffset for Point {
3698    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3699        snapshot.point_to_offset(*self)
3700    }
3701}
3702
3703impl ToOffset for usize {
3704    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3705        assert!(*self <= snapshot.len(), "offset is out of range");
3706        *self
3707    }
3708}
3709
3710impl ToOffset for OffsetUtf16 {
3711    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3712        snapshot.offset_utf16_to_offset(*self)
3713    }
3714}
3715
3716impl ToOffset for PointUtf16 {
3717    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3718        snapshot.point_utf16_to_offset(*self)
3719    }
3720}
3721
3722impl ToOffsetUtf16 for OffsetUtf16 {
3723    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3724        *self
3725    }
3726}
3727
3728impl ToOffsetUtf16 for usize {
3729    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3730        snapshot.offset_to_offset_utf16(*self)
3731    }
3732}
3733
3734impl ToPoint for usize {
3735    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3736        snapshot.offset_to_point(*self)
3737    }
3738}
3739
3740impl ToPoint for Point {
3741    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3742        *self
3743    }
3744}
3745
3746impl ToPointUtf16 for usize {
3747    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3748        snapshot.offset_to_point_utf16(*self)
3749    }
3750}
3751
3752impl ToPointUtf16 for Point {
3753    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3754        snapshot.point_to_point_utf16(*self)
3755    }
3756}
3757
3758impl ToPointUtf16 for PointUtf16 {
3759    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3760        *self
3761    }
3762}
3763
3764fn build_excerpt_ranges<T>(
3765    buffer: &BufferSnapshot,
3766    ranges: &[Range<T>],
3767    context_line_count: u32,
3768) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3769where
3770    T: text::ToPoint,
3771{
3772    let max_point = buffer.max_point();
3773    let mut range_counts = Vec::new();
3774    let mut excerpt_ranges = Vec::new();
3775    let mut range_iter = ranges
3776        .iter()
3777        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3778        .peekable();
3779    while let Some(range) = range_iter.next() {
3780        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3781        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3782        let mut ranges_in_excerpt = 1;
3783
3784        while let Some(next_range) = range_iter.peek() {
3785            if next_range.start.row <= excerpt_end.row + context_line_count {
3786                excerpt_end =
3787                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3788                ranges_in_excerpt += 1;
3789                range_iter.next();
3790            } else {
3791                break;
3792            }
3793        }
3794
3795        excerpt_ranges.push(ExcerptRange {
3796            context: excerpt_start..excerpt_end,
3797            primary: Some(range),
3798        });
3799        range_counts.push(ranges_in_excerpt);
3800    }
3801
3802    (excerpt_ranges, range_counts)
3803}
3804
3805#[cfg(test)]
3806mod tests {
3807    use super::*;
3808    use futures::StreamExt;
3809    use gpui::{AppContext, TestAppContext};
3810    use language::{Buffer, Rope};
3811    use rand::prelude::*;
3812    use settings::SettingsStore;
3813    use std::{env, rc::Rc};
3814    use unindent::Unindent;
3815    use util::test::sample_text;
3816
3817    #[gpui::test]
3818    fn test_singleton(cx: &mut AppContext) {
3819        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3820        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3821
3822        let snapshot = multibuffer.read(cx).snapshot(cx);
3823        assert_eq!(snapshot.text(), buffer.read(cx).text());
3824
3825        assert_eq!(
3826            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3827            (0..buffer.read(cx).row_count())
3828                .map(Some)
3829                .collect::<Vec<_>>()
3830        );
3831
3832        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
3833        let snapshot = multibuffer.read(cx).snapshot(cx);
3834
3835        assert_eq!(snapshot.text(), buffer.read(cx).text());
3836        assert_eq!(
3837            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3838            (0..buffer.read(cx).row_count())
3839                .map(Some)
3840                .collect::<Vec<_>>()
3841        );
3842    }
3843
3844    #[gpui::test]
3845    fn test_remote(cx: &mut AppContext) {
3846        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3847        let guest_buffer = cx.add_model(|cx| {
3848            let state = host_buffer.read(cx).to_proto();
3849            let ops = cx
3850                .background()
3851                .block(host_buffer.read(cx).serialize_ops(None, cx));
3852            let mut buffer = Buffer::from_proto(1, state, None).unwrap();
3853            buffer
3854                .apply_ops(
3855                    ops.into_iter()
3856                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
3857                    cx,
3858                )
3859                .unwrap();
3860            buffer
3861        });
3862        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3863        let snapshot = multibuffer.read(cx).snapshot(cx);
3864        assert_eq!(snapshot.text(), "a");
3865
3866        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
3867        let snapshot = multibuffer.read(cx).snapshot(cx);
3868        assert_eq!(snapshot.text(), "ab");
3869
3870        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
3871        let snapshot = multibuffer.read(cx).snapshot(cx);
3872        assert_eq!(snapshot.text(), "abc");
3873    }
3874
3875    #[gpui::test]
3876    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
3877        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3878        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3879        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3880
3881        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3882        multibuffer.update(cx, |_, cx| {
3883            let events = events.clone();
3884            cx.subscribe(&multibuffer, move |_, _, event, _| {
3885                if let Event::Edited = event {
3886                    events.borrow_mut().push(event.clone())
3887                }
3888            })
3889            .detach();
3890        });
3891
3892        let subscription = multibuffer.update(cx, |multibuffer, cx| {
3893            let subscription = multibuffer.subscribe();
3894            multibuffer.push_excerpts(
3895                buffer_1.clone(),
3896                [ExcerptRange {
3897                    context: Point::new(1, 2)..Point::new(2, 5),
3898                    primary: None,
3899                }],
3900                cx,
3901            );
3902            assert_eq!(
3903                subscription.consume().into_inner(),
3904                [Edit {
3905                    old: 0..0,
3906                    new: 0..10
3907                }]
3908            );
3909
3910            multibuffer.push_excerpts(
3911                buffer_1.clone(),
3912                [ExcerptRange {
3913                    context: Point::new(3, 3)..Point::new(4, 4),
3914                    primary: None,
3915                }],
3916                cx,
3917            );
3918            multibuffer.push_excerpts(
3919                buffer_2.clone(),
3920                [ExcerptRange {
3921                    context: Point::new(3, 1)..Point::new(3, 3),
3922                    primary: None,
3923                }],
3924                cx,
3925            );
3926            assert_eq!(
3927                subscription.consume().into_inner(),
3928                [Edit {
3929                    old: 10..10,
3930                    new: 10..22
3931                }]
3932            );
3933
3934            subscription
3935        });
3936
3937        // Adding excerpts emits an edited event.
3938        assert_eq!(
3939            events.borrow().as_slice(),
3940            &[Event::Edited, Event::Edited, Event::Edited]
3941        );
3942
3943        let snapshot = multibuffer.read(cx).snapshot(cx);
3944        assert_eq!(
3945            snapshot.text(),
3946            concat!(
3947                "bbbb\n",  // Preserve newlines
3948                "ccccc\n", //
3949                "ddd\n",   //
3950                "eeee\n",  //
3951                "jj"       //
3952            )
3953        );
3954        assert_eq!(
3955            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3956            [Some(1), Some(2), Some(3), Some(4), Some(3)]
3957        );
3958        assert_eq!(
3959            snapshot.buffer_rows(2).collect::<Vec<_>>(),
3960            [Some(3), Some(4), Some(3)]
3961        );
3962        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3963        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3964
3965        assert_eq!(
3966            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3967            &[
3968                (0, "bbbb\nccccc".to_string(), true),
3969                (2, "ddd\neeee".to_string(), false),
3970                (4, "jj".to_string(), true),
3971            ]
3972        );
3973        assert_eq!(
3974            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3975            &[(0, "bbbb\nccccc".to_string(), true)]
3976        );
3977        assert_eq!(
3978            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3979            &[]
3980        );
3981        assert_eq!(
3982            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3983            &[]
3984        );
3985        assert_eq!(
3986            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3987            &[(2, "ddd\neeee".to_string(), false)]
3988        );
3989        assert_eq!(
3990            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3991            &[(2, "ddd\neeee".to_string(), false)]
3992        );
3993        assert_eq!(
3994            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3995            &[(2, "ddd\neeee".to_string(), false)]
3996        );
3997        assert_eq!(
3998            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3999            &[(4, "jj".to_string(), true)]
4000        );
4001        assert_eq!(
4002            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4003            &[]
4004        );
4005
4006        buffer_1.update(cx, |buffer, cx| {
4007            let text = "\n";
4008            buffer.edit(
4009                [
4010                    (Point::new(0, 0)..Point::new(0, 0), text),
4011                    (Point::new(2, 1)..Point::new(2, 3), text),
4012                ],
4013                None,
4014                cx,
4015            );
4016        });
4017
4018        let snapshot = multibuffer.read(cx).snapshot(cx);
4019        assert_eq!(
4020            snapshot.text(),
4021            concat!(
4022                "bbbb\n", // Preserve newlines
4023                "c\n",    //
4024                "cc\n",   //
4025                "ddd\n",  //
4026                "eeee\n", //
4027                "jj"      //
4028            )
4029        );
4030
4031        assert_eq!(
4032            subscription.consume().into_inner(),
4033            [Edit {
4034                old: 6..8,
4035                new: 6..7
4036            }]
4037        );
4038
4039        let snapshot = multibuffer.read(cx).snapshot(cx);
4040        assert_eq!(
4041            snapshot.clip_point(Point::new(0, 5), Bias::Left),
4042            Point::new(0, 4)
4043        );
4044        assert_eq!(
4045            snapshot.clip_point(Point::new(0, 5), Bias::Right),
4046            Point::new(0, 4)
4047        );
4048        assert_eq!(
4049            snapshot.clip_point(Point::new(5, 1), Bias::Right),
4050            Point::new(5, 1)
4051        );
4052        assert_eq!(
4053            snapshot.clip_point(Point::new(5, 2), Bias::Right),
4054            Point::new(5, 2)
4055        );
4056        assert_eq!(
4057            snapshot.clip_point(Point::new(5, 3), Bias::Right),
4058            Point::new(5, 2)
4059        );
4060
4061        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4062            let (buffer_2_excerpt_id, _) =
4063                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4064            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4065            multibuffer.snapshot(cx)
4066        });
4067
4068        assert_eq!(
4069            snapshot.text(),
4070            concat!(
4071                "bbbb\n", // Preserve newlines
4072                "c\n",    //
4073                "cc\n",   //
4074                "ddd\n",  //
4075                "eeee",   //
4076            )
4077        );
4078
4079        fn boundaries_in_range(
4080            range: Range<Point>,
4081            snapshot: &MultiBufferSnapshot,
4082        ) -> Vec<(u32, String, bool)> {
4083            snapshot
4084                .excerpt_boundaries_in_range(range)
4085                .map(|boundary| {
4086                    (
4087                        boundary.row,
4088                        boundary
4089                            .buffer
4090                            .text_for_range(boundary.range.context)
4091                            .collect::<String>(),
4092                        boundary.starts_new_buffer,
4093                    )
4094                })
4095                .collect::<Vec<_>>()
4096        }
4097    }
4098
4099    #[gpui::test]
4100    fn test_excerpt_events(cx: &mut AppContext) {
4101        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4102        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4103
4104        let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4105        let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4106        let follower_edit_event_count = Rc::new(RefCell::new(0));
4107
4108        follower_multibuffer.update(cx, |_, cx| {
4109            let follower_edit_event_count = follower_edit_event_count.clone();
4110            cx.subscribe(
4111                &leader_multibuffer,
4112                move |follower, _, event, cx| match event.clone() {
4113                    Event::ExcerptsAdded {
4114                        buffer,
4115                        predecessor,
4116                        excerpts,
4117                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4118                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4119                    Event::Edited => {
4120                        *follower_edit_event_count.borrow_mut() += 1;
4121                    }
4122                    _ => {}
4123                },
4124            )
4125            .detach();
4126        });
4127
4128        leader_multibuffer.update(cx, |leader, cx| {
4129            leader.push_excerpts(
4130                buffer_1.clone(),
4131                [
4132                    ExcerptRange {
4133                        context: 0..8,
4134                        primary: None,
4135                    },
4136                    ExcerptRange {
4137                        context: 12..16,
4138                        primary: None,
4139                    },
4140                ],
4141                cx,
4142            );
4143            leader.insert_excerpts_after(
4144                leader.excerpt_ids()[0],
4145                buffer_2.clone(),
4146                [
4147                    ExcerptRange {
4148                        context: 0..5,
4149                        primary: None,
4150                    },
4151                    ExcerptRange {
4152                        context: 10..15,
4153                        primary: None,
4154                    },
4155                ],
4156                cx,
4157            )
4158        });
4159        assert_eq!(
4160            leader_multibuffer.read(cx).snapshot(cx).text(),
4161            follower_multibuffer.read(cx).snapshot(cx).text(),
4162        );
4163        assert_eq!(*follower_edit_event_count.borrow(), 2);
4164
4165        leader_multibuffer.update(cx, |leader, cx| {
4166            let excerpt_ids = leader.excerpt_ids();
4167            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4168        });
4169        assert_eq!(
4170            leader_multibuffer.read(cx).snapshot(cx).text(),
4171            follower_multibuffer.read(cx).snapshot(cx).text(),
4172        );
4173        assert_eq!(*follower_edit_event_count.borrow(), 3);
4174
4175        // Removing an empty set of excerpts is a noop.
4176        leader_multibuffer.update(cx, |leader, cx| {
4177            leader.remove_excerpts([], cx);
4178        });
4179        assert_eq!(
4180            leader_multibuffer.read(cx).snapshot(cx).text(),
4181            follower_multibuffer.read(cx).snapshot(cx).text(),
4182        );
4183        assert_eq!(*follower_edit_event_count.borrow(), 3);
4184
4185        // Adding an empty set of excerpts is a noop.
4186        leader_multibuffer.update(cx, |leader, cx| {
4187            leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4188        });
4189        assert_eq!(
4190            leader_multibuffer.read(cx).snapshot(cx).text(),
4191            follower_multibuffer.read(cx).snapshot(cx).text(),
4192        );
4193        assert_eq!(*follower_edit_event_count.borrow(), 3);
4194
4195        leader_multibuffer.update(cx, |leader, cx| {
4196            leader.clear(cx);
4197        });
4198        assert_eq!(
4199            leader_multibuffer.read(cx).snapshot(cx).text(),
4200            follower_multibuffer.read(cx).snapshot(cx).text(),
4201        );
4202        assert_eq!(*follower_edit_event_count.borrow(), 4);
4203    }
4204
4205    #[gpui::test]
4206    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4207        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4208        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4209        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4210            multibuffer.push_excerpts_with_context_lines(
4211                buffer.clone(),
4212                vec![
4213                    Point::new(3, 2)..Point::new(4, 2),
4214                    Point::new(7, 1)..Point::new(7, 3),
4215                    Point::new(15, 0)..Point::new(15, 0),
4216                ],
4217                2,
4218                cx,
4219            )
4220        });
4221
4222        let snapshot = multibuffer.read(cx).snapshot(cx);
4223        assert_eq!(
4224            snapshot.text(),
4225            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4226        );
4227
4228        assert_eq!(
4229            anchor_ranges
4230                .iter()
4231                .map(|range| range.to_point(&snapshot))
4232                .collect::<Vec<_>>(),
4233            vec![
4234                Point::new(2, 2)..Point::new(3, 2),
4235                Point::new(6, 1)..Point::new(6, 3),
4236                Point::new(12, 0)..Point::new(12, 0)
4237            ]
4238        );
4239    }
4240
4241    #[gpui::test]
4242    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4243        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4244        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4245        let (task, anchor_ranges) = multibuffer.update(cx, |multibuffer, cx| {
4246            let snapshot = buffer.read(cx);
4247            let ranges = vec![
4248                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4249                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4250                snapshot.anchor_before(Point::new(15, 0))
4251                    ..snapshot.anchor_before(Point::new(15, 0)),
4252            ];
4253            multibuffer.stream_excerpts_with_context_lines(vec![(buffer.clone(), ranges)], 2, cx)
4254        });
4255
4256        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4257        // Ensure task is finished when stream completes.
4258        task.await;
4259
4260        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4261        assert_eq!(
4262            snapshot.text(),
4263            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4264        );
4265
4266        assert_eq!(
4267            anchor_ranges
4268                .iter()
4269                .map(|range| range.to_point(&snapshot))
4270                .collect::<Vec<_>>(),
4271            vec![
4272                Point::new(2, 2)..Point::new(3, 2),
4273                Point::new(6, 1)..Point::new(6, 3),
4274                Point::new(12, 0)..Point::new(12, 0)
4275            ]
4276        );
4277    }
4278
4279    #[gpui::test]
4280    fn test_empty_multibuffer(cx: &mut AppContext) {
4281        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4282
4283        let snapshot = multibuffer.read(cx).snapshot(cx);
4284        assert_eq!(snapshot.text(), "");
4285        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4286        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4287    }
4288
4289    #[gpui::test]
4290    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
4291        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4292        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4293        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4294        buffer.update(cx, |buffer, cx| {
4295            buffer.edit([(0..0, "X")], None, cx);
4296            buffer.edit([(5..5, "Y")], None, cx);
4297        });
4298        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4299
4300        assert_eq!(old_snapshot.text(), "abcd");
4301        assert_eq!(new_snapshot.text(), "XabcdY");
4302
4303        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4304        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4305        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4306        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4307    }
4308
4309    #[gpui::test]
4310    fn test_multibuffer_anchors(cx: &mut AppContext) {
4311        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4312        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4313        let multibuffer = cx.add_model(|cx| {
4314            let mut multibuffer = MultiBuffer::new(0);
4315            multibuffer.push_excerpts(
4316                buffer_1.clone(),
4317                [ExcerptRange {
4318                    context: 0..4,
4319                    primary: None,
4320                }],
4321                cx,
4322            );
4323            multibuffer.push_excerpts(
4324                buffer_2.clone(),
4325                [ExcerptRange {
4326                    context: 0..5,
4327                    primary: None,
4328                }],
4329                cx,
4330            );
4331            multibuffer
4332        });
4333        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4334
4335        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4336        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4337        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4338        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4339        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4340        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4341
4342        buffer_1.update(cx, |buffer, cx| {
4343            buffer.edit([(0..0, "W")], None, cx);
4344            buffer.edit([(5..5, "X")], None, cx);
4345        });
4346        buffer_2.update(cx, |buffer, cx| {
4347            buffer.edit([(0..0, "Y")], None, cx);
4348            buffer.edit([(6..6, "Z")], None, cx);
4349        });
4350        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4351
4352        assert_eq!(old_snapshot.text(), "abcd\nefghi");
4353        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4354
4355        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4356        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4357        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4358        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4359        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4360        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4361        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4362        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4363        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4364        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4365    }
4366
4367    #[gpui::test]
4368    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
4369        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4370        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4371        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4372
4373        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4374        // Add an excerpt from buffer 1 that spans this new insertion.
4375        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4376        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4377            multibuffer
4378                .push_excerpts(
4379                    buffer_1.clone(),
4380                    [ExcerptRange {
4381                        context: 0..7,
4382                        primary: None,
4383                    }],
4384                    cx,
4385                )
4386                .pop()
4387                .unwrap()
4388        });
4389
4390        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4391        assert_eq!(snapshot_1.text(), "abcd123");
4392
4393        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4394        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4395            multibuffer.remove_excerpts([excerpt_id_1], cx);
4396            let mut ids = multibuffer
4397                .push_excerpts(
4398                    buffer_2.clone(),
4399                    [
4400                        ExcerptRange {
4401                            context: 0..4,
4402                            primary: None,
4403                        },
4404                        ExcerptRange {
4405                            context: 6..10,
4406                            primary: None,
4407                        },
4408                        ExcerptRange {
4409                            context: 12..16,
4410                            primary: None,
4411                        },
4412                    ],
4413                    cx,
4414                )
4415                .into_iter();
4416            (ids.next().unwrap(), ids.next().unwrap())
4417        });
4418        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4419        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4420
4421        // The old excerpt id doesn't get reused.
4422        assert_ne!(excerpt_id_2, excerpt_id_1);
4423
4424        // Resolve some anchors from the previous snapshot in the new snapshot.
4425        // The current excerpts are from a different buffer, so we don't attempt to
4426        // resolve the old text anchor in the new buffer.
4427        assert_eq!(
4428            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4429            0
4430        );
4431        assert_eq!(
4432            snapshot_2.summaries_for_anchors::<usize, _>(&[
4433                snapshot_1.anchor_before(2),
4434                snapshot_1.anchor_after(3)
4435            ]),
4436            vec![0, 0]
4437        );
4438
4439        // Refresh anchors from the old snapshot. The return value indicates that both
4440        // anchors lost their original excerpt.
4441        let refresh =
4442            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4443        assert_eq!(
4444            refresh,
4445            &[
4446                (0, snapshot_2.anchor_before(0), false),
4447                (1, snapshot_2.anchor_after(0), false),
4448            ]
4449        );
4450
4451        // Replace the middle excerpt with a smaller excerpt in buffer 2,
4452        // that intersects the old excerpt.
4453        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4454            multibuffer.remove_excerpts([excerpt_id_3], cx);
4455            multibuffer
4456                .insert_excerpts_after(
4457                    excerpt_id_2,
4458                    buffer_2.clone(),
4459                    [ExcerptRange {
4460                        context: 5..8,
4461                        primary: None,
4462                    }],
4463                    cx,
4464                )
4465                .pop()
4466                .unwrap()
4467        });
4468
4469        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4470        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4471        assert_ne!(excerpt_id_5, excerpt_id_3);
4472
4473        // Resolve some anchors from the previous snapshot in the new snapshot.
4474        // The third anchor can't be resolved, since its excerpt has been removed,
4475        // so it resolves to the same position as its predecessor.
4476        let anchors = [
4477            snapshot_2.anchor_before(0),
4478            snapshot_2.anchor_after(2),
4479            snapshot_2.anchor_after(6),
4480            snapshot_2.anchor_after(14),
4481        ];
4482        assert_eq!(
4483            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4484            &[0, 2, 9, 13]
4485        );
4486
4487        let new_anchors = snapshot_3.refresh_anchors(&anchors);
4488        assert_eq!(
4489            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4490            &[(0, true), (1, true), (2, true), (3, true)]
4491        );
4492        assert_eq!(
4493            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4494            &[0, 2, 7, 13]
4495        );
4496    }
4497
4498    #[gpui::test]
4499    async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4500        use git::diff::DiffHunkStatus;
4501
4502        // buffer has two modified hunks with two rows each
4503        let buffer_1 = cx.add_model(|cx| {
4504            let mut buffer = Buffer::new(
4505                0,
4506                "
4507                1.zero
4508                1.ONE
4509                1.TWO
4510                1.three
4511                1.FOUR
4512                1.FIVE
4513                1.six
4514            "
4515                .unindent(),
4516                cx,
4517            );
4518            buffer.set_diff_base(
4519                Some(
4520                    "
4521                1.zero
4522                1.one
4523                1.two
4524                1.three
4525                1.four
4526                1.five
4527                1.six
4528            "
4529                    .unindent(),
4530                ),
4531                cx,
4532            );
4533            buffer
4534        });
4535
4536        // buffer has a deletion hunk and an insertion hunk
4537        let buffer_2 = cx.add_model(|cx| {
4538            let mut buffer = Buffer::new(
4539                0,
4540                "
4541                2.zero
4542                2.one
4543                2.two
4544                2.three
4545                2.four
4546                2.five
4547                2.six
4548            "
4549                .unindent(),
4550                cx,
4551            );
4552            buffer.set_diff_base(
4553                Some(
4554                    "
4555                2.zero
4556                2.one
4557                2.one-and-a-half
4558                2.two
4559                2.three
4560                2.four
4561                2.six
4562            "
4563                    .unindent(),
4564                ),
4565                cx,
4566            );
4567            buffer
4568        });
4569
4570        cx.foreground().run_until_parked();
4571
4572        let multibuffer = cx.add_model(|cx| {
4573            let mut multibuffer = MultiBuffer::new(0);
4574            multibuffer.push_excerpts(
4575                buffer_1.clone(),
4576                [
4577                    // excerpt ends in the middle of a modified hunk
4578                    ExcerptRange {
4579                        context: Point::new(0, 0)..Point::new(1, 5),
4580                        primary: Default::default(),
4581                    },
4582                    // excerpt begins in the middle of a modified hunk
4583                    ExcerptRange {
4584                        context: Point::new(5, 0)..Point::new(6, 5),
4585                        primary: Default::default(),
4586                    },
4587                ],
4588                cx,
4589            );
4590            multibuffer.push_excerpts(
4591                buffer_2.clone(),
4592                [
4593                    // excerpt ends at a deletion
4594                    ExcerptRange {
4595                        context: Point::new(0, 0)..Point::new(1, 5),
4596                        primary: Default::default(),
4597                    },
4598                    // excerpt starts at a deletion
4599                    ExcerptRange {
4600                        context: Point::new(2, 0)..Point::new(2, 5),
4601                        primary: Default::default(),
4602                    },
4603                    // excerpt fully contains a deletion hunk
4604                    ExcerptRange {
4605                        context: Point::new(1, 0)..Point::new(2, 5),
4606                        primary: Default::default(),
4607                    },
4608                    // excerpt fully contains an insertion hunk
4609                    ExcerptRange {
4610                        context: Point::new(4, 0)..Point::new(6, 5),
4611                        primary: Default::default(),
4612                    },
4613                ],
4614                cx,
4615            );
4616            multibuffer
4617        });
4618
4619        let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4620
4621        assert_eq!(
4622            snapshot.text(),
4623            "
4624                1.zero
4625                1.ONE
4626                1.FIVE
4627                1.six
4628                2.zero
4629                2.one
4630                2.two
4631                2.one
4632                2.two
4633                2.four
4634                2.five
4635                2.six"
4636                .unindent()
4637        );
4638
4639        let expected = [
4640            (DiffHunkStatus::Modified, 1..2),
4641            (DiffHunkStatus::Modified, 2..3),
4642            //TODO: Define better when and where removed hunks show up at range extremities
4643            (DiffHunkStatus::Removed, 6..6),
4644            (DiffHunkStatus::Removed, 8..8),
4645            (DiffHunkStatus::Added, 10..11),
4646        ];
4647
4648        assert_eq!(
4649            snapshot
4650                .git_diff_hunks_in_range(0..12, false)
4651                .map(|hunk| (hunk.status(), hunk.buffer_range))
4652                .collect::<Vec<_>>(),
4653            &expected,
4654        );
4655
4656        assert_eq!(
4657            snapshot
4658                .git_diff_hunks_in_range(0..12, true)
4659                .map(|hunk| (hunk.status(), hunk.buffer_range))
4660                .collect::<Vec<_>>(),
4661            expected
4662                .iter()
4663                .rev()
4664                .cloned()
4665                .collect::<Vec<_>>()
4666                .as_slice(),
4667        );
4668    }
4669
4670    #[gpui::test(iterations = 100)]
4671    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
4672        let operations = env::var("OPERATIONS")
4673            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4674            .unwrap_or(10);
4675
4676        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4677        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4678        let mut excerpt_ids = Vec::<ExcerptId>::new();
4679        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4680        let mut anchors = Vec::new();
4681        let mut old_versions = Vec::new();
4682
4683        for _ in 0..operations {
4684            match rng.gen_range(0..100) {
4685                0..=19 if !buffers.is_empty() => {
4686                    let buffer = buffers.choose(&mut rng).unwrap();
4687                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4688                }
4689                20..=29 if !expected_excerpts.is_empty() => {
4690                    let mut ids_to_remove = vec![];
4691                    for _ in 0..rng.gen_range(1..=3) {
4692                        if expected_excerpts.is_empty() {
4693                            break;
4694                        }
4695
4696                        let ix = rng.gen_range(0..expected_excerpts.len());
4697                        ids_to_remove.push(excerpt_ids.remove(ix));
4698                        let (buffer, range) = expected_excerpts.remove(ix);
4699                        let buffer = buffer.read(cx);
4700                        log::info!(
4701                            "Removing excerpt {}: {:?}",
4702                            ix,
4703                            buffer
4704                                .text_for_range(range.to_offset(buffer))
4705                                .collect::<String>(),
4706                        );
4707                    }
4708                    let snapshot = multibuffer.read(cx).read(cx);
4709                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4710                    drop(snapshot);
4711                    multibuffer.update(cx, |multibuffer, cx| {
4712                        multibuffer.remove_excerpts(ids_to_remove, cx)
4713                    });
4714                }
4715                30..=39 if !expected_excerpts.is_empty() => {
4716                    let multibuffer = multibuffer.read(cx).read(cx);
4717                    let offset =
4718                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4719                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4720                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4721                    anchors.push(multibuffer.anchor_at(offset, bias));
4722                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4723                }
4724                40..=44 if !anchors.is_empty() => {
4725                    let multibuffer = multibuffer.read(cx).read(cx);
4726                    let prev_len = anchors.len();
4727                    anchors = multibuffer
4728                        .refresh_anchors(&anchors)
4729                        .into_iter()
4730                        .map(|a| a.1)
4731                        .collect();
4732
4733                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4734                    // overshoot its boundaries.
4735                    assert_eq!(anchors.len(), prev_len);
4736                    for anchor in &anchors {
4737                        if anchor.excerpt_id == ExcerptId::min()
4738                            || anchor.excerpt_id == ExcerptId::max()
4739                        {
4740                            continue;
4741                        }
4742
4743                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4744                        assert_eq!(excerpt.id, anchor.excerpt_id);
4745                        assert!(excerpt.contains(anchor));
4746                    }
4747                }
4748                _ => {
4749                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4750                        let base_text = util::RandomCharIter::new(&mut rng)
4751                            .take(10)
4752                            .collect::<String>();
4753                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4754                        buffers.last().unwrap()
4755                    } else {
4756                        buffers.choose(&mut rng).unwrap()
4757                    };
4758
4759                    let buffer = buffer_handle.read(cx);
4760                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4761                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4762                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4763                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4764                    let prev_excerpt_id = excerpt_ids
4765                        .get(prev_excerpt_ix)
4766                        .cloned()
4767                        .unwrap_or_else(ExcerptId::max);
4768                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4769
4770                    log::info!(
4771                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4772                        excerpt_ix,
4773                        expected_excerpts.len(),
4774                        buffer_handle.read(cx).remote_id(),
4775                        buffer.text(),
4776                        start_ix..end_ix,
4777                        &buffer.text()[start_ix..end_ix]
4778                    );
4779
4780                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4781                        multibuffer
4782                            .insert_excerpts_after(
4783                                prev_excerpt_id,
4784                                buffer_handle.clone(),
4785                                [ExcerptRange {
4786                                    context: start_ix..end_ix,
4787                                    primary: None,
4788                                }],
4789                                cx,
4790                            )
4791                            .pop()
4792                            .unwrap()
4793                    });
4794
4795                    excerpt_ids.insert(excerpt_ix, excerpt_id);
4796                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
4797                }
4798            }
4799
4800            if rng.gen_bool(0.3) {
4801                multibuffer.update(cx, |multibuffer, cx| {
4802                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
4803                })
4804            }
4805
4806            let snapshot = multibuffer.read(cx).snapshot(cx);
4807
4808            let mut excerpt_starts = Vec::new();
4809            let mut expected_text = String::new();
4810            let mut expected_buffer_rows = Vec::new();
4811            for (buffer, range) in &expected_excerpts {
4812                let buffer = buffer.read(cx);
4813                let buffer_range = range.to_offset(buffer);
4814
4815                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
4816                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
4817                expected_text.push('\n');
4818
4819                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
4820                    ..=buffer.offset_to_point(buffer_range.end).row;
4821                for row in buffer_row_range {
4822                    expected_buffer_rows.push(Some(row));
4823                }
4824            }
4825            // Remove final trailing newline.
4826            if !expected_excerpts.is_empty() {
4827                expected_text.pop();
4828            }
4829
4830            // Always report one buffer row
4831            if expected_buffer_rows.is_empty() {
4832                expected_buffer_rows.push(Some(0));
4833            }
4834
4835            assert_eq!(snapshot.text(), expected_text);
4836            log::info!("MultiBuffer text: {:?}", expected_text);
4837
4838            assert_eq!(
4839                snapshot.buffer_rows(0).collect::<Vec<_>>(),
4840                expected_buffer_rows,
4841            );
4842
4843            for _ in 0..5 {
4844                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
4845                assert_eq!(
4846                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
4847                    &expected_buffer_rows[start_row..],
4848                    "buffer_rows({})",
4849                    start_row
4850                );
4851            }
4852
4853            assert_eq!(
4854                snapshot.max_buffer_row(),
4855                expected_buffer_rows.into_iter().flatten().max().unwrap()
4856            );
4857
4858            let mut excerpt_starts = excerpt_starts.into_iter();
4859            for (buffer, range) in &expected_excerpts {
4860                let buffer = buffer.read(cx);
4861                let buffer_id = buffer.remote_id();
4862                let buffer_range = range.to_offset(buffer);
4863                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
4864                let buffer_start_point_utf16 =
4865                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
4866
4867                let excerpt_start = excerpt_starts.next().unwrap();
4868                let mut offset = excerpt_start.len;
4869                let mut buffer_offset = buffer_range.start;
4870                let mut point = excerpt_start.lines;
4871                let mut buffer_point = buffer_start_point;
4872                let mut point_utf16 = excerpt_start.lines_utf16();
4873                let mut buffer_point_utf16 = buffer_start_point_utf16;
4874                for ch in buffer
4875                    .snapshot()
4876                    .chunks(buffer_range.clone(), false)
4877                    .flat_map(|c| c.text.chars())
4878                {
4879                    for _ in 0..ch.len_utf8() {
4880                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
4881                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
4882                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
4883                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
4884                        assert_eq!(
4885                            left_offset,
4886                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
4887                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
4888                            offset,
4889                            buffer_id,
4890                            buffer_offset,
4891                        );
4892                        assert_eq!(
4893                            right_offset,
4894                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
4895                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
4896                            offset,
4897                            buffer_id,
4898                            buffer_offset,
4899                        );
4900
4901                        let left_point = snapshot.clip_point(point, Bias::Left);
4902                        let right_point = snapshot.clip_point(point, Bias::Right);
4903                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
4904                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
4905                        assert_eq!(
4906                            left_point,
4907                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
4908                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
4909                            point,
4910                            buffer_id,
4911                            buffer_point,
4912                        );
4913                        assert_eq!(
4914                            right_point,
4915                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
4916                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
4917                            point,
4918                            buffer_id,
4919                            buffer_point,
4920                        );
4921
4922                        assert_eq!(
4923                            snapshot.point_to_offset(left_point),
4924                            left_offset,
4925                            "point_to_offset({:?})",
4926                            left_point,
4927                        );
4928                        assert_eq!(
4929                            snapshot.offset_to_point(left_offset),
4930                            left_point,
4931                            "offset_to_point({:?})",
4932                            left_offset,
4933                        );
4934
4935                        offset += 1;
4936                        buffer_offset += 1;
4937                        if ch == '\n' {
4938                            point += Point::new(1, 0);
4939                            buffer_point += Point::new(1, 0);
4940                        } else {
4941                            point += Point::new(0, 1);
4942                            buffer_point += Point::new(0, 1);
4943                        }
4944                    }
4945
4946                    for _ in 0..ch.len_utf16() {
4947                        let left_point_utf16 =
4948                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
4949                        let right_point_utf16 =
4950                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
4951                        let buffer_left_point_utf16 =
4952                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
4953                        let buffer_right_point_utf16 =
4954                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
4955                        assert_eq!(
4956                            left_point_utf16,
4957                            excerpt_start.lines_utf16()
4958                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
4959                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4960                            point_utf16,
4961                            buffer_id,
4962                            buffer_point_utf16,
4963                        );
4964                        assert_eq!(
4965                            right_point_utf16,
4966                            excerpt_start.lines_utf16()
4967                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
4968                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4969                            point_utf16,
4970                            buffer_id,
4971                            buffer_point_utf16,
4972                        );
4973
4974                        if ch == '\n' {
4975                            point_utf16 += PointUtf16::new(1, 0);
4976                            buffer_point_utf16 += PointUtf16::new(1, 0);
4977                        } else {
4978                            point_utf16 += PointUtf16::new(0, 1);
4979                            buffer_point_utf16 += PointUtf16::new(0, 1);
4980                        }
4981                    }
4982                }
4983            }
4984
4985            for (row, line) in expected_text.split('\n').enumerate() {
4986                assert_eq!(
4987                    snapshot.line_len(row as u32),
4988                    line.len() as u32,
4989                    "line_len({}).",
4990                    row
4991                );
4992            }
4993
4994            let text_rope = Rope::from(expected_text.as_str());
4995            for _ in 0..10 {
4996                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4997                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4998
4999                let text_for_range = snapshot
5000                    .text_for_range(start_ix..end_ix)
5001                    .collect::<String>();
5002                assert_eq!(
5003                    text_for_range,
5004                    &expected_text[start_ix..end_ix],
5005                    "incorrect text for range {:?}",
5006                    start_ix..end_ix
5007                );
5008
5009                let excerpted_buffer_ranges = multibuffer
5010                    .read(cx)
5011                    .range_to_buffer_ranges(start_ix..end_ix, cx);
5012                let excerpted_buffers_text = excerpted_buffer_ranges
5013                    .into_iter()
5014                    .map(|(buffer, buffer_range)| {
5015                        buffer
5016                            .read(cx)
5017                            .text_for_range(buffer_range)
5018                            .collect::<String>()
5019                    })
5020                    .collect::<Vec<_>>()
5021                    .join("\n");
5022                assert_eq!(excerpted_buffers_text, text_for_range);
5023
5024                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5025                assert_eq!(
5026                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5027                    expected_summary,
5028                    "incorrect summary for range {:?}",
5029                    start_ix..end_ix
5030                );
5031            }
5032
5033            // Anchor resolution
5034            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5035            assert_eq!(anchors.len(), summaries.len());
5036            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5037                assert!(resolved_offset <= snapshot.len());
5038                assert_eq!(
5039                    snapshot.summary_for_anchor::<usize>(anchor),
5040                    resolved_offset
5041                );
5042            }
5043
5044            for _ in 0..10 {
5045                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5046                assert_eq!(
5047                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
5048                    expected_text[..end_ix].chars().rev().collect::<String>(),
5049                );
5050            }
5051
5052            for _ in 0..10 {
5053                let end_ix = rng.gen_range(0..=text_rope.len());
5054                let start_ix = rng.gen_range(0..=end_ix);
5055                assert_eq!(
5056                    snapshot
5057                        .bytes_in_range(start_ix..end_ix)
5058                        .flatten()
5059                        .copied()
5060                        .collect::<Vec<_>>(),
5061                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5062                    "bytes_in_range({:?})",
5063                    start_ix..end_ix,
5064                );
5065            }
5066        }
5067
5068        let snapshot = multibuffer.read(cx).snapshot(cx);
5069        for (old_snapshot, subscription) in old_versions {
5070            let edits = subscription.consume().into_inner();
5071
5072            log::info!(
5073                "applying subscription edits to old text: {:?}: {:?}",
5074                old_snapshot.text(),
5075                edits,
5076            );
5077
5078            let mut text = old_snapshot.text();
5079            for edit in edits {
5080                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5081                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5082            }
5083            assert_eq!(text.to_string(), snapshot.text());
5084        }
5085    }
5086
5087    #[gpui::test]
5088    fn test_history(cx: &mut AppContext) {
5089        cx.set_global(SettingsStore::test(cx));
5090
5091        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
5092        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
5093        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
5094        let group_interval = multibuffer.read(cx).history.group_interval;
5095        multibuffer.update(cx, |multibuffer, cx| {
5096            multibuffer.push_excerpts(
5097                buffer_1.clone(),
5098                [ExcerptRange {
5099                    context: 0..buffer_1.read(cx).len(),
5100                    primary: None,
5101                }],
5102                cx,
5103            );
5104            multibuffer.push_excerpts(
5105                buffer_2.clone(),
5106                [ExcerptRange {
5107                    context: 0..buffer_2.read(cx).len(),
5108                    primary: None,
5109                }],
5110                cx,
5111            );
5112        });
5113
5114        let mut now = Instant::now();
5115
5116        multibuffer.update(cx, |multibuffer, cx| {
5117            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5118            multibuffer.edit(
5119                [
5120                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5121                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5122                ],
5123                None,
5124                cx,
5125            );
5126            multibuffer.edit(
5127                [
5128                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5129                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5130                ],
5131                None,
5132                cx,
5133            );
5134            multibuffer.end_transaction_at(now, cx);
5135            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5136
5137            // Edit buffer 1 through the multibuffer
5138            now += 2 * group_interval;
5139            multibuffer.start_transaction_at(now, cx);
5140            multibuffer.edit([(2..2, "C")], None, cx);
5141            multibuffer.end_transaction_at(now, cx);
5142            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5143
5144            // Edit buffer 1 independently
5145            buffer_1.update(cx, |buffer_1, cx| {
5146                buffer_1.start_transaction_at(now);
5147                buffer_1.edit([(3..3, "D")], None, cx);
5148                buffer_1.end_transaction_at(now, cx);
5149
5150                now += 2 * group_interval;
5151                buffer_1.start_transaction_at(now);
5152                buffer_1.edit([(4..4, "E")], None, cx);
5153                buffer_1.end_transaction_at(now, cx);
5154            });
5155            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5156
5157            // An undo in the multibuffer undoes the multibuffer transaction
5158            // and also any individual buffer edits that have occured since
5159            // that transaction.
5160            multibuffer.undo(cx);
5161            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5162
5163            multibuffer.undo(cx);
5164            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5165
5166            multibuffer.redo(cx);
5167            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5168
5169            multibuffer.redo(cx);
5170            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5171
5172            // Undo buffer 2 independently.
5173            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5174            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5175
5176            // An undo in the multibuffer undoes the components of the
5177            // the last multibuffer transaction that are not already undone.
5178            multibuffer.undo(cx);
5179            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5180
5181            multibuffer.undo(cx);
5182            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5183
5184            multibuffer.redo(cx);
5185            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5186
5187            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5188            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5189
5190            // Redo stack gets cleared after an edit.
5191            now += 2 * group_interval;
5192            multibuffer.start_transaction_at(now, cx);
5193            multibuffer.edit([(0..0, "X")], None, cx);
5194            multibuffer.end_transaction_at(now, cx);
5195            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5196            multibuffer.redo(cx);
5197            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5198            multibuffer.undo(cx);
5199            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5200            multibuffer.undo(cx);
5201            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5202
5203            // Transactions can be grouped manually.
5204            multibuffer.redo(cx);
5205            multibuffer.redo(cx);
5206            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5207            multibuffer.group_until_transaction(transaction_1, cx);
5208            multibuffer.undo(cx);
5209            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5210            multibuffer.redo(cx);
5211            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5212        });
5213    }
5214}