multi_buffer.rs

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