multi_buffer.rs

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