multi_buffer.rs

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