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_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
1696        if let Some((_, _, buffer)) = self.as_singleton() {
1697            return buffer.clip_offset_utf16(offset, bias);
1698        }
1699
1700        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
1701        cursor.seek(&offset, Bias::Right, &());
1702        let overshoot = if let Some(excerpt) = cursor.item() {
1703            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1704            let buffer_offset = excerpt
1705                .buffer
1706                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
1707            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
1708        } else {
1709            OffsetUtf16(0)
1710        };
1711        *cursor.start() + overshoot
1712    }
1713
1714    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1715        if let Some((_, _, buffer)) = self.as_singleton() {
1716            return buffer.clip_point_utf16(point, bias);
1717        }
1718
1719        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1720        cursor.seek(&point, Bias::Right, &());
1721        let overshoot = if let Some(excerpt) = cursor.item() {
1722            let excerpt_start = excerpt
1723                .buffer
1724                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1725            let buffer_point = excerpt
1726                .buffer
1727                .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1728            buffer_point.saturating_sub(excerpt_start)
1729        } else {
1730            PointUtf16::zero()
1731        };
1732        *cursor.start() + overshoot
1733    }
1734
1735    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1736        let range = range.start.to_offset(self)..range.end.to_offset(self);
1737        let mut excerpts = self.excerpts.cursor::<usize>();
1738        excerpts.seek(&range.start, Bias::Right, &());
1739
1740        let mut chunk = &[][..];
1741        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1742            let mut excerpt_bytes = excerpt
1743                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1744            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1745            Some(excerpt_bytes)
1746        } else {
1747            None
1748        };
1749
1750        MultiBufferBytes {
1751            range,
1752            excerpts,
1753            excerpt_bytes,
1754            chunk,
1755        }
1756    }
1757
1758    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1759        let mut result = MultiBufferRows {
1760            buffer_row_range: 0..0,
1761            excerpts: self.excerpts.cursor(),
1762        };
1763        result.seek(start_row);
1764        result
1765    }
1766
1767    pub fn chunks<'a, T: ToOffset>(
1768        &'a self,
1769        range: Range<T>,
1770        language_aware: bool,
1771    ) -> MultiBufferChunks<'a> {
1772        let range = range.start.to_offset(self)..range.end.to_offset(self);
1773        let mut chunks = MultiBufferChunks {
1774            range: range.clone(),
1775            excerpts: self.excerpts.cursor(),
1776            excerpt_chunks: None,
1777            language_aware,
1778        };
1779        chunks.seek(range.start);
1780        chunks
1781    }
1782
1783    pub fn offset_to_point(&self, offset: usize) -> Point {
1784        if let Some((_, _, buffer)) = self.as_singleton() {
1785            return buffer.offset_to_point(offset);
1786        }
1787
1788        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1789        cursor.seek(&offset, Bias::Right, &());
1790        if let Some(excerpt) = cursor.item() {
1791            let (start_offset, start_point) = cursor.start();
1792            let overshoot = offset - start_offset;
1793            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1794            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1795            let buffer_point = excerpt
1796                .buffer
1797                .offset_to_point(excerpt_start_offset + overshoot);
1798            *start_point + (buffer_point - excerpt_start_point)
1799        } else {
1800            self.excerpts.summary().text.lines
1801        }
1802    }
1803
1804    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1805        if let Some((_, _, buffer)) = self.as_singleton() {
1806            return buffer.offset_to_point_utf16(offset);
1807        }
1808
1809        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
1810        cursor.seek(&offset, Bias::Right, &());
1811        if let Some(excerpt) = cursor.item() {
1812            let (start_offset, start_point) = cursor.start();
1813            let overshoot = offset - start_offset;
1814            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1815            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1816            let buffer_point = excerpt
1817                .buffer
1818                .offset_to_point_utf16(excerpt_start_offset + overshoot);
1819            *start_point + (buffer_point - excerpt_start_point)
1820        } else {
1821            self.excerpts.summary().text.lines_utf16
1822        }
1823    }
1824
1825    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1826        if let Some((_, _, buffer)) = self.as_singleton() {
1827            return buffer.point_to_point_utf16(point);
1828        }
1829
1830        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
1831        cursor.seek(&point, Bias::Right, &());
1832        if let Some(excerpt) = cursor.item() {
1833            let (start_offset, start_point) = cursor.start();
1834            let overshoot = point - start_offset;
1835            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1836            let excerpt_start_point_utf16 =
1837                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
1838            let buffer_point = excerpt
1839                .buffer
1840                .point_to_point_utf16(excerpt_start_point + overshoot);
1841            *start_point + (buffer_point - excerpt_start_point_utf16)
1842        } else {
1843            self.excerpts.summary().text.lines_utf16
1844        }
1845    }
1846
1847    pub fn point_to_offset(&self, point: Point) -> usize {
1848        if let Some((_, _, buffer)) = self.as_singleton() {
1849            return buffer.point_to_offset(point);
1850        }
1851
1852        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1853        cursor.seek(&point, Bias::Right, &());
1854        if let Some(excerpt) = cursor.item() {
1855            let (start_point, start_offset) = cursor.start();
1856            let overshoot = point - start_point;
1857            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1858            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
1859            let buffer_offset = excerpt
1860                .buffer
1861                .point_to_offset(excerpt_start_point + overshoot);
1862            *start_offset + buffer_offset - excerpt_start_offset
1863        } else {
1864            self.excerpts.summary().text.len
1865        }
1866    }
1867
1868    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
1869        if let Some((_, _, buffer)) = self.as_singleton() {
1870            return buffer.offset_utf16_to_offset(offset_utf16);
1871        }
1872
1873        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
1874        cursor.seek(&offset_utf16, Bias::Right, &());
1875        if let Some(excerpt) = cursor.item() {
1876            let (start_offset_utf16, start_offset) = cursor.start();
1877            let overshoot = offset_utf16 - start_offset_utf16;
1878            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1879            let excerpt_start_offset_utf16 =
1880                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
1881            let buffer_offset = excerpt
1882                .buffer
1883                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
1884            *start_offset + (buffer_offset - excerpt_start_offset)
1885        } else {
1886            self.excerpts.summary().text.len
1887        }
1888    }
1889
1890    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
1891        if let Some((_, _, buffer)) = self.as_singleton() {
1892            return buffer.offset_to_offset_utf16(offset);
1893        }
1894
1895        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
1896        cursor.seek(&offset, Bias::Right, &());
1897        if let Some(excerpt) = cursor.item() {
1898            let (start_offset, start_offset_utf16) = cursor.start();
1899            let overshoot = offset - start_offset;
1900            let excerpt_start_offset_utf16 =
1901                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1902            let excerpt_start_offset = excerpt
1903                .buffer
1904                .offset_utf16_to_offset(excerpt_start_offset_utf16);
1905            let buffer_offset_utf16 = excerpt
1906                .buffer
1907                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
1908            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
1909        } else {
1910            self.excerpts.summary().text.len_utf16
1911        }
1912    }
1913
1914    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1915        if let Some((_, _, buffer)) = self.as_singleton() {
1916            return buffer.point_utf16_to_offset(point);
1917        }
1918
1919        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1920        cursor.seek(&point, Bias::Right, &());
1921        if let Some(excerpt) = cursor.item() {
1922            let (start_point, start_offset) = cursor.start();
1923            let overshoot = point - start_point;
1924            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
1925            let excerpt_start_point = excerpt
1926                .buffer
1927                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1928            let buffer_offset = excerpt
1929                .buffer
1930                .point_utf16_to_offset(excerpt_start_point + overshoot);
1931            *start_offset + (buffer_offset - excerpt_start_offset)
1932        } else {
1933            self.excerpts.summary().text.len
1934        }
1935    }
1936
1937    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
1938        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1939            let mut size = buffer.indent_size_for_line(range.start.row);
1940            size.len = size
1941                .len
1942                .min(range.end.column)
1943                .saturating_sub(range.start.column);
1944            size
1945        } else {
1946            IndentSize::spaces(0)
1947        }
1948    }
1949
1950    pub fn line_len(&self, row: u32) -> u32 {
1951        if let Some((_, range)) = self.buffer_line_for_row(row) {
1952            range.end.column - range.start.column
1953        } else {
1954            0
1955        }
1956    }
1957
1958    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1959        let mut cursor = self.excerpts.cursor::<Point>();
1960        cursor.seek(&Point::new(row, 0), Bias::Right, &());
1961        if let Some(excerpt) = cursor.item() {
1962            let overshoot = row - cursor.start().row;
1963            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1964            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
1965            let buffer_row = excerpt_start.row + overshoot;
1966            let line_start = Point::new(buffer_row, 0);
1967            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1968            return Some((
1969                &excerpt.buffer,
1970                line_start.max(excerpt_start)..line_end.min(excerpt_end),
1971            ));
1972        }
1973        None
1974    }
1975
1976    pub fn max_point(&self) -> Point {
1977        self.text_summary().lines
1978    }
1979
1980    pub fn text_summary(&self) -> TextSummary {
1981        self.excerpts.summary().text.clone()
1982    }
1983
1984    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1985    where
1986        D: TextDimension,
1987        O: ToOffset,
1988    {
1989        let mut summary = D::default();
1990        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1991        let mut cursor = self.excerpts.cursor::<usize>();
1992        cursor.seek(&range.start, Bias::Right, &());
1993        if let Some(excerpt) = cursor.item() {
1994            let mut end_before_newline = cursor.end(&());
1995            if excerpt.has_trailing_newline {
1996                end_before_newline -= 1;
1997            }
1998
1999            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2000            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2001            let end_in_excerpt =
2002                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2003            summary.add_assign(
2004                &excerpt
2005                    .buffer
2006                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2007            );
2008
2009            if range.end > end_before_newline {
2010                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2011            }
2012
2013            cursor.next(&());
2014        }
2015
2016        if range.end > *cursor.start() {
2017            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2018                &range.end,
2019                Bias::Right,
2020                &(),
2021            )));
2022            if let Some(excerpt) = cursor.item() {
2023                range.end = cmp::max(*cursor.start(), range.end);
2024
2025                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2026                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2027                summary.add_assign(
2028                    &excerpt
2029                        .buffer
2030                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2031                );
2032            }
2033        }
2034
2035        summary
2036    }
2037
2038    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2039    where
2040        D: TextDimension + Ord + Sub<D, Output = D>,
2041    {
2042        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2043        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
2044        if cursor.item().is_none() {
2045            cursor.next(&());
2046        }
2047
2048        let mut position = D::from_text_summary(&cursor.start().text);
2049        if let Some(excerpt) = cursor.item() {
2050            if excerpt.id == anchor.excerpt_id {
2051                let excerpt_buffer_start =
2052                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2053                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2054                let buffer_position = cmp::min(
2055                    excerpt_buffer_end,
2056                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2057                );
2058                if buffer_position > excerpt_buffer_start {
2059                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2060                }
2061            }
2062        }
2063        position
2064    }
2065
2066    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2067    where
2068        D: TextDimension + Ord + Sub<D, Output = D>,
2069        I: 'a + IntoIterator<Item = &'a Anchor>,
2070    {
2071        if let Some((_, _, buffer)) = self.as_singleton() {
2072            return buffer
2073                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2074                .collect();
2075        }
2076
2077        let mut anchors = anchors.into_iter().peekable();
2078        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2079        let mut summaries = Vec::new();
2080        while let Some(anchor) = anchors.peek() {
2081            let excerpt_id = &anchor.excerpt_id;
2082            let excerpt_anchors = iter::from_fn(|| {
2083                let anchor = anchors.peek()?;
2084                if anchor.excerpt_id == *excerpt_id {
2085                    Some(&anchors.next().unwrap().text_anchor)
2086                } else {
2087                    None
2088                }
2089            });
2090
2091            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
2092            if cursor.item().is_none() {
2093                cursor.next(&());
2094            }
2095
2096            let position = D::from_text_summary(&cursor.start().text);
2097            if let Some(excerpt) = cursor.item() {
2098                if excerpt.id == *excerpt_id {
2099                    let excerpt_buffer_start =
2100                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2101                    let excerpt_buffer_end =
2102                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2103                    summaries.extend(
2104                        excerpt
2105                            .buffer
2106                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2107                            .map(move |summary| {
2108                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2109                                let mut position = position.clone();
2110                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2111                                if summary > excerpt_buffer_start {
2112                                    position.add_assign(&(summary - excerpt_buffer_start));
2113                                }
2114                                position
2115                            }),
2116                    );
2117                    continue;
2118                }
2119            }
2120
2121            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2122        }
2123
2124        summaries
2125    }
2126
2127    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2128    where
2129        I: 'a + IntoIterator<Item = &'a Anchor>,
2130    {
2131        let mut anchors = anchors.into_iter().enumerate().peekable();
2132        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2133        let mut result = Vec::new();
2134        while let Some((_, anchor)) = anchors.peek() {
2135            let old_excerpt_id = &anchor.excerpt_id;
2136
2137            // Find the location where this anchor's excerpt should be.
2138            cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
2139            if cursor.item().is_none() {
2140                cursor.next(&());
2141            }
2142
2143            let next_excerpt = cursor.item();
2144            let prev_excerpt = cursor.prev_item();
2145
2146            // Process all of the anchors for this excerpt.
2147            while let Some((_, anchor)) = anchors.peek() {
2148                if anchor.excerpt_id != *old_excerpt_id {
2149                    break;
2150                }
2151                let mut kept_position = false;
2152                let (anchor_ix, anchor) = anchors.next().unwrap();
2153                let mut anchor = anchor.clone();
2154
2155                // Leave min and max anchors unchanged.
2156                if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
2157                    kept_position = true;
2158                }
2159                // If the old excerpt still exists at this location, then leave
2160                // the anchor unchanged.
2161                else if next_excerpt.map_or(false, |excerpt| {
2162                    excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
2163                }) {
2164                    kept_position = true;
2165                }
2166                // If the old excerpt no longer exists at this location, then attempt to
2167                // find an equivalent position for this anchor in an adjacent excerpt.
2168                else {
2169                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2170                        if excerpt.contains(&anchor) {
2171                            anchor.excerpt_id = excerpt.id.clone();
2172                            kept_position = true;
2173                            break;
2174                        }
2175                    }
2176                }
2177                // If there's no adjacent excerpt that contains the anchor's position,
2178                // then report that the anchor has lost its position.
2179                if !kept_position {
2180                    anchor = if let Some(excerpt) = next_excerpt {
2181                        let mut text_anchor = excerpt
2182                            .range
2183                            .context
2184                            .start
2185                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2186                        if text_anchor
2187                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2188                            .is_gt()
2189                        {
2190                            text_anchor = excerpt.range.context.end.clone();
2191                        }
2192                        Anchor {
2193                            buffer_id: Some(excerpt.buffer_id),
2194                            excerpt_id: excerpt.id.clone(),
2195                            text_anchor,
2196                        }
2197                    } else if let Some(excerpt) = prev_excerpt {
2198                        let mut text_anchor = excerpt
2199                            .range
2200                            .context
2201                            .end
2202                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2203                        if text_anchor
2204                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2205                            .is_lt()
2206                        {
2207                            text_anchor = excerpt.range.context.start.clone();
2208                        }
2209                        Anchor {
2210                            buffer_id: Some(excerpt.buffer_id),
2211                            excerpt_id: excerpt.id.clone(),
2212                            text_anchor,
2213                        }
2214                    } else if anchor.text_anchor.bias == Bias::Left {
2215                        Anchor::min()
2216                    } else {
2217                        Anchor::max()
2218                    };
2219                }
2220
2221                result.push((anchor_ix, anchor, kept_position));
2222            }
2223        }
2224        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2225        result
2226    }
2227
2228    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2229        self.anchor_at(position, Bias::Left)
2230    }
2231
2232    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2233        self.anchor_at(position, Bias::Right)
2234    }
2235
2236    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2237        let offset = position.to_offset(self);
2238        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2239            return Anchor {
2240                buffer_id: Some(buffer_id),
2241                excerpt_id: excerpt_id.clone(),
2242                text_anchor: buffer.anchor_at(offset, bias),
2243            };
2244        }
2245
2246        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
2247        cursor.seek(&offset, Bias::Right, &());
2248        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2249            cursor.prev(&());
2250        }
2251        if let Some(excerpt) = cursor.item() {
2252            let mut overshoot = offset.saturating_sub(cursor.start().0);
2253            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2254                overshoot -= 1;
2255                bias = Bias::Right;
2256            }
2257
2258            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2259            let text_anchor =
2260                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2261            Anchor {
2262                buffer_id: Some(excerpt.buffer_id),
2263                excerpt_id: excerpt.id.clone(),
2264                text_anchor,
2265            }
2266        } else if offset == 0 && bias == Bias::Left {
2267            Anchor::min()
2268        } else {
2269            Anchor::max()
2270        }
2271    }
2272
2273    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2274        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2275        cursor.seek(&Some(&excerpt_id), Bias::Left, &());
2276        if let Some(excerpt) = cursor.item() {
2277            if excerpt.id == excerpt_id {
2278                let text_anchor = excerpt.clip_anchor(text_anchor);
2279                drop(cursor);
2280                return Anchor {
2281                    buffer_id: Some(excerpt.buffer_id),
2282                    excerpt_id,
2283                    text_anchor,
2284                };
2285            }
2286        }
2287        panic!("excerpt not found");
2288    }
2289
2290    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2291        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2292            true
2293        } else if let Some(excerpt) = self.excerpt(&anchor.excerpt_id) {
2294            excerpt.buffer.can_resolve(&anchor.text_anchor)
2295        } else {
2296            false
2297        }
2298    }
2299
2300    pub fn excerpt_boundaries_in_range<'a, R, T>(
2301        &'a self,
2302        range: R,
2303    ) -> impl Iterator<Item = ExcerptBoundary> + 'a
2304    where
2305        R: RangeBounds<T>,
2306        T: ToOffset,
2307    {
2308        let start_offset;
2309        let start = match range.start_bound() {
2310            Bound::Included(start) => {
2311                start_offset = start.to_offset(self);
2312                Bound::Included(start_offset)
2313            }
2314            Bound::Excluded(start) => {
2315                start_offset = start.to_offset(self);
2316                Bound::Excluded(start_offset)
2317            }
2318            Bound::Unbounded => {
2319                start_offset = 0;
2320                Bound::Unbounded
2321            }
2322        };
2323        let end = match range.end_bound() {
2324            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2325            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2326            Bound::Unbounded => Bound::Unbounded,
2327        };
2328        let bounds = (start, end);
2329
2330        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2331        cursor.seek(&start_offset, Bias::Right, &());
2332        if cursor.item().is_none() {
2333            cursor.prev(&());
2334        }
2335        if !bounds.contains(&cursor.start().0) {
2336            cursor.next(&());
2337        }
2338
2339        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2340        std::iter::from_fn(move || {
2341            if self.singleton {
2342                None
2343            } else if bounds.contains(&cursor.start().0) {
2344                let excerpt = cursor.item()?;
2345                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2346                let boundary = ExcerptBoundary {
2347                    id: excerpt.id.clone(),
2348                    key: excerpt.key,
2349                    row: cursor.start().1.row,
2350                    buffer: excerpt.buffer.clone(),
2351                    range: excerpt.range.clone(),
2352                    starts_new_buffer,
2353                };
2354
2355                prev_buffer_id = Some(excerpt.buffer_id);
2356                cursor.next(&());
2357                Some(boundary)
2358            } else {
2359                None
2360            }
2361        })
2362    }
2363
2364    pub fn edit_count(&self) -> usize {
2365        self.edit_count
2366    }
2367
2368    pub fn parse_count(&self) -> usize {
2369        self.parse_count
2370    }
2371
2372    pub fn enclosing_bracket_ranges<T: ToOffset>(
2373        &self,
2374        range: Range<T>,
2375    ) -> Option<(Range<usize>, Range<usize>)> {
2376        let range = range.start.to_offset(self)..range.end.to_offset(self);
2377
2378        let mut cursor = self.excerpts.cursor::<usize>();
2379        cursor.seek(&range.start, Bias::Right, &());
2380        let start_excerpt = cursor.item();
2381
2382        cursor.seek(&range.end, Bias::Right, &());
2383        let end_excerpt = cursor.item();
2384
2385        start_excerpt
2386            .zip(end_excerpt)
2387            .and_then(|(start_excerpt, end_excerpt)| {
2388                if start_excerpt.id != end_excerpt.id {
2389                    return None;
2390                }
2391
2392                let excerpt_buffer_start = start_excerpt
2393                    .range
2394                    .context
2395                    .start
2396                    .to_offset(&start_excerpt.buffer);
2397                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2398
2399                let start_in_buffer =
2400                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2401                let end_in_buffer =
2402                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2403                let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
2404                    .buffer
2405                    .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
2406
2407                if start_bracket_range.start >= excerpt_buffer_start
2408                    && end_bracket_range.end <= excerpt_buffer_end
2409                {
2410                    start_bracket_range.start =
2411                        cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
2412                    start_bracket_range.end =
2413                        cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
2414                    end_bracket_range.start =
2415                        cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
2416                    end_bracket_range.end =
2417                        cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
2418                    Some((start_bracket_range, end_bracket_range))
2419                } else {
2420                    None
2421                }
2422            })
2423    }
2424
2425    pub fn diagnostics_update_count(&self) -> usize {
2426        self.diagnostics_update_count
2427    }
2428
2429    pub fn trailing_excerpt_update_count(&self) -> usize {
2430        self.trailing_excerpt_update_count
2431    }
2432
2433    pub fn language(&self) -> Option<&Arc<Language>> {
2434        self.excerpts
2435            .iter()
2436            .next()
2437            .and_then(|excerpt| excerpt.buffer.language())
2438    }
2439
2440    pub fn is_dirty(&self) -> bool {
2441        self.is_dirty
2442    }
2443
2444    pub fn has_conflict(&self) -> bool {
2445        self.has_conflict
2446    }
2447
2448    pub fn diagnostic_group<'a, O>(
2449        &'a self,
2450        group_id: usize,
2451    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2452    where
2453        O: text::FromAnchor + 'a,
2454    {
2455        self.as_singleton()
2456            .into_iter()
2457            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2458    }
2459
2460    pub fn diagnostics_in_range<'a, T, O>(
2461        &'a self,
2462        range: Range<T>,
2463        reversed: bool,
2464    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2465    where
2466        T: 'a + ToOffset,
2467        O: 'a + text::FromAnchor,
2468    {
2469        self.as_singleton()
2470            .into_iter()
2471            .flat_map(move |(_, _, buffer)| {
2472                buffer.diagnostics_in_range(
2473                    range.start.to_offset(self)..range.end.to_offset(self),
2474                    reversed,
2475                )
2476            })
2477    }
2478
2479    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2480        let range = range.start.to_offset(self)..range.end.to_offset(self);
2481
2482        let mut cursor = self.excerpts.cursor::<usize>();
2483        cursor.seek(&range.start, Bias::Right, &());
2484        let start_excerpt = cursor.item();
2485
2486        cursor.seek(&range.end, Bias::Right, &());
2487        let end_excerpt = cursor.item();
2488
2489        start_excerpt
2490            .zip(end_excerpt)
2491            .and_then(|(start_excerpt, end_excerpt)| {
2492                if start_excerpt.id != end_excerpt.id {
2493                    return None;
2494                }
2495
2496                let excerpt_buffer_start = start_excerpt
2497                    .range
2498                    .context
2499                    .start
2500                    .to_offset(&start_excerpt.buffer);
2501                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2502
2503                let start_in_buffer =
2504                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2505                let end_in_buffer =
2506                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2507                let mut ancestor_buffer_range = start_excerpt
2508                    .buffer
2509                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2510                ancestor_buffer_range.start =
2511                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2512                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2513
2514                let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
2515                let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
2516                Some(start..end)
2517            })
2518    }
2519
2520    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2521        let (excerpt_id, _, buffer) = self.as_singleton()?;
2522        let outline = buffer.outline(theme)?;
2523        Some(Outline::new(
2524            outline
2525                .items
2526                .into_iter()
2527                .map(|item| OutlineItem {
2528                    depth: item.depth,
2529                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2530                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2531                    text: item.text,
2532                    highlight_ranges: item.highlight_ranges,
2533                    name_ranges: item.name_ranges,
2534                })
2535                .collect(),
2536        ))
2537    }
2538
2539    pub fn symbols_containing<T: ToOffset>(
2540        &self,
2541        offset: T,
2542        theme: Option<&SyntaxTheme>,
2543    ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
2544        let anchor = self.anchor_before(offset);
2545        let excerpt_id = anchor.excerpt_id();
2546        let excerpt = self.excerpt(excerpt_id)?;
2547        Some((
2548            excerpt.buffer_id,
2549            excerpt
2550                .buffer
2551                .symbols_containing(anchor.text_anchor, theme)
2552                .into_iter()
2553                .flatten()
2554                .map(|item| OutlineItem {
2555                    depth: item.depth,
2556                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2557                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2558                    text: item.text,
2559                    highlight_ranges: item.highlight_ranges,
2560                    name_ranges: item.name_ranges,
2561                })
2562                .collect(),
2563        ))
2564    }
2565
2566    fn excerpt<'a>(&'a self, excerpt_id: &'a ExcerptId) -> Option<&'a Excerpt> {
2567        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2568        cursor.seek(&Some(excerpt_id), Bias::Left, &());
2569        if let Some(excerpt) = cursor.item() {
2570            if excerpt.id == *excerpt_id {
2571                return Some(excerpt);
2572            }
2573        }
2574        None
2575    }
2576
2577    pub fn remote_selections_in_range<'a>(
2578        &'a self,
2579        range: &'a Range<Anchor>,
2580    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, Selection<Anchor>)> {
2581        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2582        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
2583        cursor
2584            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
2585            .flat_map(move |excerpt| {
2586                let mut query_range =
2587                    excerpt.range.context.start.clone()..excerpt.range.context.end.clone();
2588                if excerpt.id == range.start.excerpt_id {
2589                    query_range.start = range.start.text_anchor.clone();
2590                }
2591                if excerpt.id == range.end.excerpt_id {
2592                    query_range.end = range.end.text_anchor.clone();
2593                }
2594
2595                excerpt
2596                    .buffer
2597                    .remote_selections_in_range(query_range)
2598                    .flat_map(move |(replica_id, line_mode, selections)| {
2599                        selections.map(move |selection| {
2600                            let mut start = Anchor {
2601                                buffer_id: Some(excerpt.buffer_id),
2602                                excerpt_id: excerpt.id.clone(),
2603                                text_anchor: selection.start.clone(),
2604                            };
2605                            let mut end = Anchor {
2606                                buffer_id: Some(excerpt.buffer_id),
2607                                excerpt_id: excerpt.id.clone(),
2608                                text_anchor: selection.end.clone(),
2609                            };
2610                            if range.start.cmp(&start, self).is_gt() {
2611                                start = range.start.clone();
2612                            }
2613                            if range.end.cmp(&end, self).is_lt() {
2614                                end = range.end.clone();
2615                            }
2616
2617                            (
2618                                replica_id,
2619                                line_mode,
2620                                Selection {
2621                                    id: selection.id,
2622                                    start,
2623                                    end,
2624                                    reversed: selection.reversed,
2625                                    goal: selection.goal,
2626                                },
2627                            )
2628                        })
2629                    })
2630            })
2631    }
2632}
2633
2634#[cfg(any(test, feature = "test-support"))]
2635impl MultiBufferSnapshot {
2636    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
2637        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
2638        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
2639        start..end
2640    }
2641}
2642
2643impl History {
2644    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2645        self.transaction_depth += 1;
2646        if self.transaction_depth == 1 {
2647            let id = self.next_transaction_id.tick();
2648            self.undo_stack.push(Transaction {
2649                id,
2650                buffer_transactions: Default::default(),
2651                first_edit_at: now,
2652                last_edit_at: now,
2653                suppress_grouping: false,
2654            });
2655            Some(id)
2656        } else {
2657            None
2658        }
2659    }
2660
2661    fn end_transaction(
2662        &mut self,
2663        now: Instant,
2664        buffer_transactions: HashMap<usize, TransactionId>,
2665    ) -> bool {
2666        assert_ne!(self.transaction_depth, 0);
2667        self.transaction_depth -= 1;
2668        if self.transaction_depth == 0 {
2669            if buffer_transactions.is_empty() {
2670                self.undo_stack.pop();
2671                false
2672            } else {
2673                self.redo_stack.clear();
2674                let transaction = self.undo_stack.last_mut().unwrap();
2675                transaction.last_edit_at = now;
2676                for (buffer_id, transaction_id) in buffer_transactions {
2677                    transaction
2678                        .buffer_transactions
2679                        .entry(buffer_id)
2680                        .or_insert(transaction_id);
2681                }
2682                true
2683            }
2684        } else {
2685            false
2686        }
2687    }
2688
2689    fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
2690    where
2691        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
2692    {
2693        assert_eq!(self.transaction_depth, 0);
2694        let transaction = Transaction {
2695            id: self.next_transaction_id.tick(),
2696            buffer_transactions: buffer_transactions
2697                .into_iter()
2698                .map(|(buffer, transaction)| (buffer.id(), transaction.id))
2699                .collect(),
2700            first_edit_at: now,
2701            last_edit_at: now,
2702            suppress_grouping: false,
2703        };
2704        if !transaction.buffer_transactions.is_empty() {
2705            self.undo_stack.push(transaction);
2706            self.redo_stack.clear();
2707        }
2708    }
2709
2710    fn finalize_last_transaction(&mut self) {
2711        if let Some(transaction) = self.undo_stack.last_mut() {
2712            transaction.suppress_grouping = true;
2713        }
2714    }
2715
2716    fn pop_undo(&mut self) -> Option<&mut Transaction> {
2717        assert_eq!(self.transaction_depth, 0);
2718        if let Some(transaction) = self.undo_stack.pop() {
2719            self.redo_stack.push(transaction);
2720            self.redo_stack.last_mut()
2721        } else {
2722            None
2723        }
2724    }
2725
2726    fn pop_redo(&mut self) -> Option<&mut Transaction> {
2727        assert_eq!(self.transaction_depth, 0);
2728        if let Some(transaction) = self.redo_stack.pop() {
2729            self.undo_stack.push(transaction);
2730            self.undo_stack.last_mut()
2731        } else {
2732            None
2733        }
2734    }
2735
2736    fn group(&mut self) -> Option<TransactionId> {
2737        let mut count = 0;
2738        let mut transactions = self.undo_stack.iter();
2739        if let Some(mut transaction) = transactions.next_back() {
2740            while let Some(prev_transaction) = transactions.next_back() {
2741                if !prev_transaction.suppress_grouping
2742                    && transaction.first_edit_at - prev_transaction.last_edit_at
2743                        <= self.group_interval
2744                {
2745                    transaction = prev_transaction;
2746                    count += 1;
2747                } else {
2748                    break;
2749                }
2750            }
2751        }
2752        self.group_trailing(count)
2753    }
2754
2755    fn group_until(&mut self, transaction_id: TransactionId) {
2756        let mut count = 0;
2757        for transaction in self.undo_stack.iter().rev() {
2758            if transaction.id == transaction_id {
2759                self.group_trailing(count);
2760                break;
2761            } else if transaction.suppress_grouping {
2762                break;
2763            } else {
2764                count += 1;
2765            }
2766        }
2767    }
2768
2769    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
2770        let new_len = self.undo_stack.len() - n;
2771        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2772        if let Some(last_transaction) = transactions_to_keep.last_mut() {
2773            if let Some(transaction) = transactions_to_merge.last() {
2774                last_transaction.last_edit_at = transaction.last_edit_at;
2775            }
2776            for to_merge in transactions_to_merge {
2777                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
2778                    last_transaction
2779                        .buffer_transactions
2780                        .entry(*buffer_id)
2781                        .or_insert(*transaction_id);
2782                }
2783            }
2784        }
2785
2786        self.undo_stack.truncate(new_len);
2787        self.undo_stack.last().map(|t| t.id)
2788    }
2789}
2790
2791impl Excerpt {
2792    fn new(
2793        id: ExcerptId,
2794        key: usize,
2795        buffer_id: usize,
2796        buffer: BufferSnapshot,
2797        range: ExcerptRange<text::Anchor>,
2798        has_trailing_newline: bool,
2799    ) -> Self {
2800        Excerpt {
2801            id,
2802            key,
2803            max_buffer_row: range.context.end.to_point(&buffer).row,
2804            text_summary: buffer
2805                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
2806            buffer_id,
2807            buffer,
2808            range,
2809            has_trailing_newline,
2810        }
2811    }
2812
2813    fn chunks_in_range<'a>(
2814        &'a self,
2815        range: Range<usize>,
2816        language_aware: bool,
2817    ) -> ExcerptChunks<'a> {
2818        let content_start = self.range.context.start.to_offset(&self.buffer);
2819        let chunks_start = content_start + range.start;
2820        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
2821
2822        let footer_height = if self.has_trailing_newline
2823            && range.start <= self.text_summary.len
2824            && range.end > self.text_summary.len
2825        {
2826            1
2827        } else {
2828            0
2829        };
2830
2831        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2832
2833        ExcerptChunks {
2834            content_chunks,
2835            footer_height,
2836        }
2837    }
2838
2839    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2840        let content_start = self.range.context.start.to_offset(&self.buffer);
2841        let bytes_start = content_start + range.start;
2842        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
2843        let footer_height = if self.has_trailing_newline
2844            && range.start <= self.text_summary.len
2845            && range.end > self.text_summary.len
2846        {
2847            1
2848        } else {
2849            0
2850        };
2851        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2852
2853        ExcerptBytes {
2854            content_bytes,
2855            footer_height,
2856        }
2857    }
2858
2859    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2860        if text_anchor
2861            .cmp(&self.range.context.start, &self.buffer)
2862            .is_lt()
2863        {
2864            self.range.context.start.clone()
2865        } else if text_anchor
2866            .cmp(&self.range.context.end, &self.buffer)
2867            .is_gt()
2868        {
2869            self.range.context.end.clone()
2870        } else {
2871            text_anchor
2872        }
2873    }
2874
2875    fn contains(&self, anchor: &Anchor) -> bool {
2876        Some(self.buffer_id) == anchor.buffer_id
2877            && self
2878                .range
2879                .context
2880                .start
2881                .cmp(&anchor.text_anchor, &self.buffer)
2882                .is_le()
2883            && self
2884                .range
2885                .context
2886                .end
2887                .cmp(&anchor.text_anchor, &self.buffer)
2888                .is_ge()
2889    }
2890}
2891
2892impl fmt::Debug for Excerpt {
2893    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2894        f.debug_struct("Excerpt")
2895            .field("id", &self.id)
2896            .field("buffer_id", &self.buffer_id)
2897            .field("range", &self.range)
2898            .field("text_summary", &self.text_summary)
2899            .field("has_trailing_newline", &self.has_trailing_newline)
2900            .finish()
2901    }
2902}
2903
2904impl sum_tree::Item for Excerpt {
2905    type Summary = ExcerptSummary;
2906
2907    fn summary(&self) -> Self::Summary {
2908        let mut text = self.text_summary.clone();
2909        if self.has_trailing_newline {
2910            text += TextSummary::from("\n");
2911        }
2912        ExcerptSummary {
2913            excerpt_id: self.id.clone(),
2914            max_buffer_row: self.max_buffer_row,
2915            text,
2916        }
2917    }
2918}
2919
2920impl sum_tree::Summary for ExcerptSummary {
2921    type Context = ();
2922
2923    fn add_summary(&mut self, summary: &Self, _: &()) {
2924        debug_assert!(summary.excerpt_id > self.excerpt_id);
2925        self.excerpt_id = summary.excerpt_id.clone();
2926        self.text.add_summary(&summary.text, &());
2927        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2928    }
2929}
2930
2931impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2932    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2933        *self += &summary.text;
2934    }
2935}
2936
2937impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2938    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2939        *self += summary.text.len;
2940    }
2941}
2942
2943impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2944    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2945        Ord::cmp(self, &cursor_location.text.len)
2946    }
2947}
2948
2949impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2950    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2951        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2952    }
2953}
2954
2955impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
2956    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2957        *self += summary.text.len_utf16;
2958    }
2959}
2960
2961impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2962    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2963        *self += summary.text.lines;
2964    }
2965}
2966
2967impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2968    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2969        *self += summary.text.lines_utf16
2970    }
2971}
2972
2973impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2974    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2975        *self = Some(&summary.excerpt_id);
2976    }
2977}
2978
2979impl<'a> MultiBufferRows<'a> {
2980    pub fn seek(&mut self, row: u32) {
2981        self.buffer_row_range = 0..0;
2982
2983        self.excerpts
2984            .seek_forward(&Point::new(row, 0), Bias::Right, &());
2985        if self.excerpts.item().is_none() {
2986            self.excerpts.prev(&());
2987
2988            if self.excerpts.item().is_none() && row == 0 {
2989                self.buffer_row_range = 0..1;
2990                return;
2991            }
2992        }
2993
2994        if let Some(excerpt) = self.excerpts.item() {
2995            let overshoot = row - self.excerpts.start().row;
2996            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2997            self.buffer_row_range.start = excerpt_start + overshoot;
2998            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2999        }
3000    }
3001}
3002
3003impl<'a> Iterator for MultiBufferRows<'a> {
3004    type Item = Option<u32>;
3005
3006    fn next(&mut self) -> Option<Self::Item> {
3007        loop {
3008            if !self.buffer_row_range.is_empty() {
3009                let row = Some(self.buffer_row_range.start);
3010                self.buffer_row_range.start += 1;
3011                return Some(row);
3012            }
3013            self.excerpts.item()?;
3014            self.excerpts.next(&());
3015            let excerpt = self.excerpts.item()?;
3016            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3017            self.buffer_row_range.end =
3018                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3019        }
3020    }
3021}
3022
3023impl<'a> MultiBufferChunks<'a> {
3024    pub fn offset(&self) -> usize {
3025        self.range.start
3026    }
3027
3028    pub fn seek(&mut self, offset: usize) {
3029        self.range.start = offset;
3030        self.excerpts.seek(&offset, Bias::Right, &());
3031        if let Some(excerpt) = self.excerpts.item() {
3032            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3033                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3034                self.language_aware,
3035            ));
3036        } else {
3037            self.excerpt_chunks = None;
3038        }
3039    }
3040}
3041
3042impl<'a> Iterator for MultiBufferChunks<'a> {
3043    type Item = Chunk<'a>;
3044
3045    fn next(&mut self) -> Option<Self::Item> {
3046        if self.range.is_empty() {
3047            None
3048        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3049            self.range.start += chunk.text.len();
3050            Some(chunk)
3051        } else {
3052            self.excerpts.next(&());
3053            let excerpt = self.excerpts.item()?;
3054            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3055                0..self.range.end - self.excerpts.start(),
3056                self.language_aware,
3057            ));
3058            self.next()
3059        }
3060    }
3061}
3062
3063impl<'a> MultiBufferBytes<'a> {
3064    fn consume(&mut self, len: usize) {
3065        self.range.start += len;
3066        self.chunk = &self.chunk[len..];
3067
3068        if !self.range.is_empty() && self.chunk.is_empty() {
3069            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3070                self.chunk = chunk;
3071            } else {
3072                self.excerpts.next(&());
3073                if let Some(excerpt) = self.excerpts.item() {
3074                    let mut excerpt_bytes =
3075                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3076                    self.chunk = excerpt_bytes.next().unwrap();
3077                    self.excerpt_bytes = Some(excerpt_bytes);
3078                }
3079            }
3080        }
3081    }
3082}
3083
3084impl<'a> Iterator for MultiBufferBytes<'a> {
3085    type Item = &'a [u8];
3086
3087    fn next(&mut self) -> Option<Self::Item> {
3088        let chunk = self.chunk;
3089        if chunk.is_empty() {
3090            None
3091        } else {
3092            self.consume(chunk.len());
3093            Some(chunk)
3094        }
3095    }
3096}
3097
3098impl<'a> io::Read for MultiBufferBytes<'a> {
3099    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3100        let len = cmp::min(buf.len(), self.chunk.len());
3101        buf[..len].copy_from_slice(&self.chunk[..len]);
3102        if len > 0 {
3103            self.consume(len);
3104        }
3105        Ok(len)
3106    }
3107}
3108
3109impl<'a> Iterator for ExcerptBytes<'a> {
3110    type Item = &'a [u8];
3111
3112    fn next(&mut self) -> Option<Self::Item> {
3113        if let Some(chunk) = self.content_bytes.next() {
3114            if !chunk.is_empty() {
3115                return Some(chunk);
3116            }
3117        }
3118
3119        if self.footer_height > 0 {
3120            let result = &NEWLINES[..self.footer_height];
3121            self.footer_height = 0;
3122            return Some(result);
3123        }
3124
3125        None
3126    }
3127}
3128
3129impl<'a> Iterator for ExcerptChunks<'a> {
3130    type Item = Chunk<'a>;
3131
3132    fn next(&mut self) -> Option<Self::Item> {
3133        if let Some(chunk) = self.content_chunks.next() {
3134            return Some(chunk);
3135        }
3136
3137        if self.footer_height > 0 {
3138            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3139            self.footer_height = 0;
3140            return Some(Chunk {
3141                text,
3142                ..Default::default()
3143            });
3144        }
3145
3146        None
3147    }
3148}
3149
3150impl ToOffset for Point {
3151    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3152        snapshot.point_to_offset(*self)
3153    }
3154}
3155
3156impl ToOffset for PointUtf16 {
3157    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3158        snapshot.point_utf16_to_offset(*self)
3159    }
3160}
3161
3162impl ToOffset for usize {
3163    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3164        assert!(*self <= snapshot.len(), "offset is out of range");
3165        *self
3166    }
3167}
3168
3169impl ToOffset for OffsetUtf16 {
3170    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3171        snapshot.offset_utf16_to_offset(*self)
3172    }
3173}
3174
3175impl ToOffsetUtf16 for OffsetUtf16 {
3176    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3177        *self
3178    }
3179}
3180
3181impl ToOffsetUtf16 for usize {
3182    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3183        snapshot.offset_to_offset_utf16(*self)
3184    }
3185}
3186
3187impl ToPoint for usize {
3188    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3189        snapshot.offset_to_point(*self)
3190    }
3191}
3192
3193impl ToPoint for Point {
3194    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3195        *self
3196    }
3197}
3198
3199impl ToPointUtf16 for usize {
3200    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3201        snapshot.offset_to_point_utf16(*self)
3202    }
3203}
3204
3205impl ToPointUtf16 for Point {
3206    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3207        snapshot.point_to_point_utf16(*self)
3208    }
3209}
3210
3211impl ToPointUtf16 for PointUtf16 {
3212    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3213        *self
3214    }
3215}
3216
3217#[cfg(test)]
3218mod tests {
3219    use super::*;
3220    use gpui::MutableAppContext;
3221    use language::{Buffer, Rope};
3222    use rand::prelude::*;
3223    use std::{env, rc::Rc};
3224    use text::{Point, RandomCharIter};
3225    use util::test::sample_text;
3226
3227    #[gpui::test]
3228    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
3229        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3230        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3231
3232        let snapshot = multibuffer.read(cx).snapshot(cx);
3233        assert_eq!(snapshot.text(), buffer.read(cx).text());
3234
3235        assert_eq!(
3236            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3237            (0..buffer.read(cx).row_count())
3238                .map(Some)
3239                .collect::<Vec<_>>()
3240        );
3241
3242        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], cx));
3243        let snapshot = multibuffer.read(cx).snapshot(cx);
3244
3245        assert_eq!(snapshot.text(), buffer.read(cx).text());
3246        assert_eq!(
3247            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3248            (0..buffer.read(cx).row_count())
3249                .map(Some)
3250                .collect::<Vec<_>>()
3251        );
3252    }
3253
3254    #[gpui::test]
3255    fn test_remote_multibuffer(cx: &mut MutableAppContext) {
3256        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3257        let guest_buffer = cx.add_model(|cx| {
3258            let message = host_buffer.read(cx).to_proto();
3259            Buffer::from_proto(1, message, None, cx).unwrap()
3260        });
3261        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3262        let snapshot = multibuffer.read(cx).snapshot(cx);
3263        assert_eq!(snapshot.text(), "a");
3264
3265        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], cx));
3266        let snapshot = multibuffer.read(cx).snapshot(cx);
3267        assert_eq!(snapshot.text(), "ab");
3268
3269        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], cx));
3270        let snapshot = multibuffer.read(cx).snapshot(cx);
3271        assert_eq!(snapshot.text(), "abc");
3272    }
3273
3274    #[gpui::test]
3275    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
3276        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3277        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3278        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3279
3280        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3281        multibuffer.update(cx, |_, cx| {
3282            let events = events.clone();
3283            cx.subscribe(&multibuffer, move |_, _, event, _| {
3284                events.borrow_mut().push(event.clone())
3285            })
3286            .detach();
3287        });
3288
3289        let subscription = multibuffer.update(cx, |multibuffer, cx| {
3290            let subscription = multibuffer.subscribe();
3291            multibuffer.push_excerpts(
3292                buffer_1.clone(),
3293                [ExcerptRange {
3294                    context: Point::new(1, 2)..Point::new(2, 5),
3295                    primary: None,
3296                }],
3297                cx,
3298            );
3299            assert_eq!(
3300                subscription.consume().into_inner(),
3301                [Edit {
3302                    old: 0..0,
3303                    new: 0..10
3304                }]
3305            );
3306
3307            multibuffer.push_excerpts(
3308                buffer_1.clone(),
3309                [ExcerptRange {
3310                    context: Point::new(3, 3)..Point::new(4, 4),
3311                    primary: None,
3312                }],
3313                cx,
3314            );
3315            multibuffer.push_excerpts(
3316                buffer_2.clone(),
3317                [ExcerptRange {
3318                    context: Point::new(3, 1)..Point::new(3, 3),
3319                    primary: None,
3320                }],
3321                cx,
3322            );
3323            assert_eq!(
3324                subscription.consume().into_inner(),
3325                [Edit {
3326                    old: 10..10,
3327                    new: 10..22
3328                }]
3329            );
3330
3331            subscription
3332        });
3333
3334        // Adding excerpts emits an edited event.
3335        assert_eq!(
3336            events.borrow().as_slice(),
3337            &[Event::Edited, Event::Edited, Event::Edited]
3338        );
3339
3340        let snapshot = multibuffer.read(cx).snapshot(cx);
3341        assert_eq!(
3342            snapshot.text(),
3343            concat!(
3344                "bbbb\n",  // Preserve newlines
3345                "ccccc\n", //
3346                "ddd\n",   //
3347                "eeee\n",  //
3348                "jj"       //
3349            )
3350        );
3351        assert_eq!(
3352            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3353            [Some(1), Some(2), Some(3), Some(4), Some(3)]
3354        );
3355        assert_eq!(
3356            snapshot.buffer_rows(2).collect::<Vec<_>>(),
3357            [Some(3), Some(4), Some(3)]
3358        );
3359        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3360        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3361
3362        assert_eq!(
3363            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3364            &[
3365                (0, "bbbb\nccccc".to_string(), true),
3366                (2, "ddd\neeee".to_string(), false),
3367                (4, "jj".to_string(), true),
3368            ]
3369        );
3370        assert_eq!(
3371            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3372            &[(0, "bbbb\nccccc".to_string(), true)]
3373        );
3374        assert_eq!(
3375            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3376            &[]
3377        );
3378        assert_eq!(
3379            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3380            &[]
3381        );
3382        assert_eq!(
3383            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3384            &[(2, "ddd\neeee".to_string(), false)]
3385        );
3386        assert_eq!(
3387            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3388            &[(2, "ddd\neeee".to_string(), false)]
3389        );
3390        assert_eq!(
3391            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3392            &[(2, "ddd\neeee".to_string(), false)]
3393        );
3394        assert_eq!(
3395            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3396            &[(4, "jj".to_string(), true)]
3397        );
3398        assert_eq!(
3399            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
3400            &[]
3401        );
3402
3403        buffer_1.update(cx, |buffer, cx| {
3404            let text = "\n";
3405            buffer.edit(
3406                [
3407                    (Point::new(0, 0)..Point::new(0, 0), text),
3408                    (Point::new(2, 1)..Point::new(2, 3), text),
3409                ],
3410                cx,
3411            );
3412        });
3413
3414        let snapshot = multibuffer.read(cx).snapshot(cx);
3415        assert_eq!(
3416            snapshot.text(),
3417            concat!(
3418                "bbbb\n", // Preserve newlines
3419                "c\n",    //
3420                "cc\n",   //
3421                "ddd\n",  //
3422                "eeee\n", //
3423                "jj"      //
3424            )
3425        );
3426
3427        assert_eq!(
3428            subscription.consume().into_inner(),
3429            [Edit {
3430                old: 6..8,
3431                new: 6..7
3432            }]
3433        );
3434
3435        let snapshot = multibuffer.read(cx).snapshot(cx);
3436        assert_eq!(
3437            snapshot.clip_point(Point::new(0, 5), Bias::Left),
3438            Point::new(0, 4)
3439        );
3440        assert_eq!(
3441            snapshot.clip_point(Point::new(0, 5), Bias::Right),
3442            Point::new(0, 4)
3443        );
3444        assert_eq!(
3445            snapshot.clip_point(Point::new(5, 1), Bias::Right),
3446            Point::new(5, 1)
3447        );
3448        assert_eq!(
3449            snapshot.clip_point(Point::new(5, 2), Bias::Right),
3450            Point::new(5, 2)
3451        );
3452        assert_eq!(
3453            snapshot.clip_point(Point::new(5, 3), Bias::Right),
3454            Point::new(5, 2)
3455        );
3456
3457        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
3458            let (buffer_2_excerpt_id, _) =
3459                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
3460            multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
3461            multibuffer.snapshot(cx)
3462        });
3463
3464        assert_eq!(
3465            snapshot.text(),
3466            concat!(
3467                "bbbb\n", // Preserve newlines
3468                "c\n",    //
3469                "cc\n",   //
3470                "ddd\n",  //
3471                "eeee",   //
3472            )
3473        );
3474
3475        fn boundaries_in_range(
3476            range: Range<Point>,
3477            snapshot: &MultiBufferSnapshot,
3478        ) -> Vec<(u32, String, bool)> {
3479            snapshot
3480                .excerpt_boundaries_in_range(range)
3481                .map(|boundary| {
3482                    (
3483                        boundary.row,
3484                        boundary
3485                            .buffer
3486                            .text_for_range(boundary.range.context)
3487                            .collect::<String>(),
3488                        boundary.starts_new_buffer,
3489                    )
3490                })
3491                .collect::<Vec<_>>()
3492        }
3493    }
3494
3495    #[gpui::test]
3496    fn test_excerpts_with_context_lines(cx: &mut MutableAppContext) {
3497        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
3498        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3499        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
3500            multibuffer.push_excerpts_with_context_lines(
3501                buffer.clone(),
3502                vec![
3503                    Point::new(3, 2)..Point::new(4, 2),
3504                    Point::new(7, 1)..Point::new(7, 3),
3505                    Point::new(15, 0)..Point::new(15, 0),
3506                ],
3507                2,
3508                cx,
3509            )
3510        });
3511
3512        let snapshot = multibuffer.read(cx).snapshot(cx);
3513        assert_eq!(
3514            snapshot.text(),
3515            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
3516        );
3517
3518        assert_eq!(
3519            anchor_ranges
3520                .iter()
3521                .map(|range| range.to_point(&snapshot))
3522                .collect::<Vec<_>>(),
3523            vec![
3524                Point::new(2, 2)..Point::new(3, 2),
3525                Point::new(6, 1)..Point::new(6, 3),
3526                Point::new(12, 0)..Point::new(12, 0)
3527            ]
3528        );
3529    }
3530
3531    #[gpui::test]
3532    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
3533        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3534
3535        let snapshot = multibuffer.read(cx).snapshot(cx);
3536        assert_eq!(snapshot.text(), "");
3537        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
3538        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
3539    }
3540
3541    #[gpui::test]
3542    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
3543        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3544        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3545        let old_snapshot = multibuffer.read(cx).snapshot(cx);
3546        buffer.update(cx, |buffer, cx| {
3547            buffer.edit([(0..0, "X")], cx);
3548            buffer.edit([(5..5, "Y")], cx);
3549        });
3550        let new_snapshot = multibuffer.read(cx).snapshot(cx);
3551
3552        assert_eq!(old_snapshot.text(), "abcd");
3553        assert_eq!(new_snapshot.text(), "XabcdY");
3554
3555        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3556        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3557        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
3558        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
3559    }
3560
3561    #[gpui::test]
3562    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
3563        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3564        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
3565        let multibuffer = cx.add_model(|cx| {
3566            let mut multibuffer = MultiBuffer::new(0);
3567            multibuffer.push_excerpts(
3568                buffer_1.clone(),
3569                [ExcerptRange {
3570                    context: 0..4,
3571                    primary: None,
3572                }],
3573                cx,
3574            );
3575            multibuffer.push_excerpts(
3576                buffer_2.clone(),
3577                [ExcerptRange {
3578                    context: 0..5,
3579                    primary: None,
3580                }],
3581                cx,
3582            );
3583            multibuffer
3584        });
3585        let old_snapshot = multibuffer.read(cx).snapshot(cx);
3586
3587        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
3588        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
3589        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3590        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3591        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3592        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3593
3594        buffer_1.update(cx, |buffer, cx| {
3595            buffer.edit([(0..0, "W")], cx);
3596            buffer.edit([(5..5, "X")], cx);
3597        });
3598        buffer_2.update(cx, |buffer, cx| {
3599            buffer.edit([(0..0, "Y")], cx);
3600            buffer.edit([(6..6, "Z")], cx);
3601        });
3602        let new_snapshot = multibuffer.read(cx).snapshot(cx);
3603
3604        assert_eq!(old_snapshot.text(), "abcd\nefghi");
3605        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
3606
3607        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3608        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3609        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
3610        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
3611        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
3612        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
3613        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
3614        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
3615        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
3616        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
3617    }
3618
3619    #[gpui::test]
3620    fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
3621        cx: &mut MutableAppContext,
3622    ) {
3623        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3624        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
3625        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3626
3627        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
3628        // Add an excerpt from buffer 1 that spans this new insertion.
3629        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], cx));
3630        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
3631            multibuffer
3632                .push_excerpts(
3633                    buffer_1.clone(),
3634                    [ExcerptRange {
3635                        context: 0..7,
3636                        primary: None,
3637                    }],
3638                    cx,
3639                )
3640                .pop()
3641                .unwrap()
3642        });
3643
3644        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
3645        assert_eq!(snapshot_1.text(), "abcd123");
3646
3647        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
3648        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
3649            multibuffer.remove_excerpts([&excerpt_id_1], cx);
3650            let mut ids = multibuffer
3651                .push_excerpts(
3652                    buffer_2.clone(),
3653                    [
3654                        ExcerptRange {
3655                            context: 0..4,
3656                            primary: None,
3657                        },
3658                        ExcerptRange {
3659                            context: 6..10,
3660                            primary: None,
3661                        },
3662                        ExcerptRange {
3663                            context: 12..16,
3664                            primary: None,
3665                        },
3666                    ],
3667                    cx,
3668                )
3669                .into_iter();
3670            (ids.next().unwrap(), ids.next().unwrap())
3671        });
3672        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
3673        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
3674
3675        // The old excerpt id doesn't get reused.
3676        assert_ne!(excerpt_id_2, excerpt_id_1);
3677
3678        // Resolve some anchors from the previous snapshot in the new snapshot.
3679        // Although there is still an excerpt with the same id, it is for
3680        // a different buffer, so we don't attempt to resolve the old text
3681        // anchor in the new buffer.
3682        assert_eq!(
3683            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
3684            0
3685        );
3686        assert_eq!(
3687            snapshot_2.summaries_for_anchors::<usize, _>(&[
3688                snapshot_1.anchor_before(2),
3689                snapshot_1.anchor_after(3)
3690            ]),
3691            vec![0, 0]
3692        );
3693        let refresh =
3694            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
3695        assert_eq!(
3696            refresh,
3697            &[
3698                (0, snapshot_2.anchor_before(0), false),
3699                (1, snapshot_2.anchor_after(0), false),
3700            ]
3701        );
3702
3703        // Replace the middle excerpt with a smaller excerpt in buffer 2,
3704        // that intersects the old excerpt.
3705        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
3706            multibuffer.remove_excerpts([&excerpt_id_3], cx);
3707            multibuffer
3708                .insert_excerpts_after(
3709                    &excerpt_id_3,
3710                    buffer_2.clone(),
3711                    [ExcerptRange {
3712                        context: 5..8,
3713                        primary: None,
3714                    }],
3715                    cx,
3716                )
3717                .pop()
3718                .unwrap()
3719        });
3720
3721        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
3722        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
3723        assert_ne!(excerpt_id_5, excerpt_id_3);
3724
3725        // Resolve some anchors from the previous snapshot in the new snapshot.
3726        // The anchor in the middle excerpt snaps to the beginning of the
3727        // excerpt, since it is not
3728        let anchors = [
3729            snapshot_2.anchor_before(0),
3730            snapshot_2.anchor_after(2),
3731            snapshot_2.anchor_after(6),
3732            snapshot_2.anchor_after(14),
3733        ];
3734        assert_eq!(
3735            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
3736            &[0, 2, 5, 13]
3737        );
3738
3739        let new_anchors = snapshot_3.refresh_anchors(&anchors);
3740        assert_eq!(
3741            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
3742            &[(0, true), (1, true), (2, true), (3, true)]
3743        );
3744        assert_eq!(
3745            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
3746            &[0, 2, 7, 13]
3747        );
3748    }
3749
3750    #[gpui::test(iterations = 100)]
3751    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
3752        let operations = env::var("OPERATIONS")
3753            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3754            .unwrap_or(10);
3755
3756        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
3757        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3758        let mut excerpt_ids = Vec::new();
3759        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
3760        let mut anchors = Vec::new();
3761        let mut old_versions = Vec::new();
3762
3763        for _ in 0..operations {
3764            match rng.gen_range(0..100) {
3765                0..=19 if !buffers.is_empty() => {
3766                    let buffer = buffers.choose(&mut rng).unwrap();
3767                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
3768                }
3769                20..=29 if !expected_excerpts.is_empty() => {
3770                    let mut ids_to_remove = vec![];
3771                    for _ in 0..rng.gen_range(1..=3) {
3772                        if expected_excerpts.is_empty() {
3773                            break;
3774                        }
3775
3776                        let ix = rng.gen_range(0..expected_excerpts.len());
3777                        ids_to_remove.push(excerpt_ids.remove(ix));
3778                        let (buffer, range) = expected_excerpts.remove(ix);
3779                        let buffer = buffer.read(cx);
3780                        log::info!(
3781                            "Removing excerpt {}: {:?}",
3782                            ix,
3783                            buffer
3784                                .text_for_range(range.to_offset(&buffer))
3785                                .collect::<String>(),
3786                        );
3787                    }
3788                    ids_to_remove.sort_unstable();
3789                    multibuffer.update(cx, |multibuffer, cx| {
3790                        multibuffer.remove_excerpts(&ids_to_remove, cx)
3791                    });
3792                }
3793                30..=39 if !expected_excerpts.is_empty() => {
3794                    let multibuffer = multibuffer.read(cx).read(cx);
3795                    let offset =
3796                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
3797                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
3798                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
3799                    anchors.push(multibuffer.anchor_at(offset, bias));
3800                    anchors.sort_by(|a, b| a.cmp(&b, &multibuffer));
3801                }
3802                40..=44 if !anchors.is_empty() => {
3803                    let multibuffer = multibuffer.read(cx).read(cx);
3804                    let prev_len = anchors.len();
3805                    anchors = multibuffer
3806                        .refresh_anchors(&anchors)
3807                        .into_iter()
3808                        .map(|a| a.1)
3809                        .collect();
3810
3811                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
3812                    // overshoot its boundaries.
3813                    assert_eq!(anchors.len(), prev_len);
3814                    let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
3815                    for anchor in &anchors {
3816                        if anchor.excerpt_id == ExcerptId::min()
3817                            || anchor.excerpt_id == ExcerptId::max()
3818                        {
3819                            continue;
3820                        }
3821
3822                        cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
3823                        let excerpt = cursor.item().unwrap();
3824                        assert_eq!(excerpt.id, anchor.excerpt_id);
3825                        assert!(excerpt.contains(anchor));
3826                    }
3827                }
3828                _ => {
3829                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
3830                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
3831                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
3832                        buffers.last().unwrap()
3833                    } else {
3834                        buffers.choose(&mut rng).unwrap()
3835                    };
3836
3837                    let buffer = buffer_handle.read(cx);
3838                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3839                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3840                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3841                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3842                    let prev_excerpt_id = excerpt_ids
3843                        .get(prev_excerpt_ix)
3844                        .cloned()
3845                        .unwrap_or(ExcerptId::max());
3846                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3847
3848                    log::info!(
3849                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3850                        excerpt_ix,
3851                        expected_excerpts.len(),
3852                        buffer_handle.id(),
3853                        buffer.text(),
3854                        start_ix..end_ix,
3855                        &buffer.text()[start_ix..end_ix]
3856                    );
3857
3858                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3859                        multibuffer
3860                            .insert_excerpts_after(
3861                                &prev_excerpt_id,
3862                                buffer_handle.clone(),
3863                                [ExcerptRange {
3864                                    context: start_ix..end_ix,
3865                                    primary: None,
3866                                }],
3867                                cx,
3868                            )
3869                            .pop()
3870                            .unwrap()
3871                    });
3872
3873                    excerpt_ids.insert(excerpt_ix, excerpt_id);
3874                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3875                }
3876            }
3877
3878            if rng.gen_bool(0.3) {
3879                multibuffer.update(cx, |multibuffer, cx| {
3880                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3881                })
3882            }
3883
3884            let snapshot = multibuffer.read(cx).snapshot(cx);
3885
3886            let mut excerpt_starts = Vec::new();
3887            let mut expected_text = String::new();
3888            let mut expected_buffer_rows = Vec::new();
3889            for (buffer, range) in &expected_excerpts {
3890                let buffer = buffer.read(cx);
3891                let buffer_range = range.to_offset(buffer);
3892
3893                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3894                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3895                expected_text.push('\n');
3896
3897                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3898                    ..=buffer.offset_to_point(buffer_range.end).row;
3899                for row in buffer_row_range {
3900                    expected_buffer_rows.push(Some(row));
3901                }
3902            }
3903            // Remove final trailing newline.
3904            if !expected_excerpts.is_empty() {
3905                expected_text.pop();
3906            }
3907
3908            // Always report one buffer row
3909            if expected_buffer_rows.is_empty() {
3910                expected_buffer_rows.push(Some(0));
3911            }
3912
3913            assert_eq!(snapshot.text(), expected_text);
3914            log::info!("MultiBuffer text: {:?}", expected_text);
3915
3916            assert_eq!(
3917                snapshot.buffer_rows(0).collect::<Vec<_>>(),
3918                expected_buffer_rows,
3919            );
3920
3921            for _ in 0..5 {
3922                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3923                assert_eq!(
3924                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3925                    &expected_buffer_rows[start_row..],
3926                    "buffer_rows({})",
3927                    start_row
3928                );
3929            }
3930
3931            assert_eq!(
3932                snapshot.max_buffer_row(),
3933                expected_buffer_rows
3934                    .into_iter()
3935                    .filter_map(|r| r)
3936                    .max()
3937                    .unwrap()
3938            );
3939
3940            let mut excerpt_starts = excerpt_starts.into_iter();
3941            for (buffer, range) in &expected_excerpts {
3942                let buffer_id = buffer.id();
3943                let buffer = buffer.read(cx);
3944                let buffer_range = range.to_offset(buffer);
3945                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3946                let buffer_start_point_utf16 =
3947                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3948
3949                let excerpt_start = excerpt_starts.next().unwrap();
3950                let mut offset = excerpt_start.len;
3951                let mut buffer_offset = buffer_range.start;
3952                let mut point = excerpt_start.lines;
3953                let mut buffer_point = buffer_start_point;
3954                let mut point_utf16 = excerpt_start.lines_utf16;
3955                let mut buffer_point_utf16 = buffer_start_point_utf16;
3956                for ch in buffer
3957                    .snapshot()
3958                    .chunks(buffer_range.clone(), false)
3959                    .flat_map(|c| c.text.chars())
3960                {
3961                    for _ in 0..ch.len_utf8() {
3962                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
3963                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
3964                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3965                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3966                        assert_eq!(
3967                            left_offset,
3968                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
3969                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3970                            offset,
3971                            buffer_id,
3972                            buffer_offset,
3973                        );
3974                        assert_eq!(
3975                            right_offset,
3976                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
3977                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3978                            offset,
3979                            buffer_id,
3980                            buffer_offset,
3981                        );
3982
3983                        let left_point = snapshot.clip_point(point, Bias::Left);
3984                        let right_point = snapshot.clip_point(point, Bias::Right);
3985                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3986                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3987                        assert_eq!(
3988                            left_point,
3989                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
3990                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3991                            point,
3992                            buffer_id,
3993                            buffer_point,
3994                        );
3995                        assert_eq!(
3996                            right_point,
3997                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
3998                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
3999                            point,
4000                            buffer_id,
4001                            buffer_point,
4002                        );
4003
4004                        assert_eq!(
4005                            snapshot.point_to_offset(left_point),
4006                            left_offset,
4007                            "point_to_offset({:?})",
4008                            left_point,
4009                        );
4010                        assert_eq!(
4011                            snapshot.offset_to_point(left_offset),
4012                            left_point,
4013                            "offset_to_point({:?})",
4014                            left_offset,
4015                        );
4016
4017                        offset += 1;
4018                        buffer_offset += 1;
4019                        if ch == '\n' {
4020                            point += Point::new(1, 0);
4021                            buffer_point += Point::new(1, 0);
4022                        } else {
4023                            point += Point::new(0, 1);
4024                            buffer_point += Point::new(0, 1);
4025                        }
4026                    }
4027
4028                    for _ in 0..ch.len_utf16() {
4029                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
4030                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
4031                        let buffer_left_point_utf16 =
4032                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
4033                        let buffer_right_point_utf16 =
4034                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
4035                        assert_eq!(
4036                            left_point_utf16,
4037                            excerpt_start.lines_utf16
4038                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
4039                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4040                            point_utf16,
4041                            buffer_id,
4042                            buffer_point_utf16,
4043                        );
4044                        assert_eq!(
4045                            right_point_utf16,
4046                            excerpt_start.lines_utf16
4047                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
4048                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4049                            point_utf16,
4050                            buffer_id,
4051                            buffer_point_utf16,
4052                        );
4053
4054                        if ch == '\n' {
4055                            point_utf16 += PointUtf16::new(1, 0);
4056                            buffer_point_utf16 += PointUtf16::new(1, 0);
4057                        } else {
4058                            point_utf16 += PointUtf16::new(0, 1);
4059                            buffer_point_utf16 += PointUtf16::new(0, 1);
4060                        }
4061                    }
4062                }
4063            }
4064
4065            for (row, line) in expected_text.split('\n').enumerate() {
4066                assert_eq!(
4067                    snapshot.line_len(row as u32),
4068                    line.len() as u32,
4069                    "line_len({}).",
4070                    row
4071                );
4072            }
4073
4074            let text_rope = Rope::from(expected_text.as_str());
4075            for _ in 0..10 {
4076                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4077                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4078
4079                let text_for_range = snapshot
4080                    .text_for_range(start_ix..end_ix)
4081                    .collect::<String>();
4082                assert_eq!(
4083                    text_for_range,
4084                    &expected_text[start_ix..end_ix],
4085                    "incorrect text for range {:?}",
4086                    start_ix..end_ix
4087                );
4088
4089                let excerpted_buffer_ranges = multibuffer
4090                    .read(cx)
4091                    .range_to_buffer_ranges(start_ix..end_ix, cx);
4092                let excerpted_buffers_text = excerpted_buffer_ranges
4093                    .into_iter()
4094                    .map(|(buffer, buffer_range)| {
4095                        buffer
4096                            .read(cx)
4097                            .text_for_range(buffer_range)
4098                            .collect::<String>()
4099                    })
4100                    .collect::<Vec<_>>()
4101                    .join("\n");
4102                assert_eq!(excerpted_buffers_text, text_for_range);
4103
4104                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
4105                assert_eq!(
4106                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
4107                    expected_summary,
4108                    "incorrect summary for range {:?}",
4109                    start_ix..end_ix
4110                );
4111            }
4112
4113            // Anchor resolution
4114            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
4115            assert_eq!(anchors.len(), summaries.len());
4116            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
4117                assert!(resolved_offset <= snapshot.len());
4118                assert_eq!(
4119                    snapshot.summary_for_anchor::<usize>(anchor),
4120                    resolved_offset
4121                );
4122            }
4123
4124            for _ in 0..10 {
4125                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4126                assert_eq!(
4127                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
4128                    expected_text[..end_ix].chars().rev().collect::<String>(),
4129                );
4130            }
4131
4132            for _ in 0..10 {
4133                let end_ix = rng.gen_range(0..=text_rope.len());
4134                let start_ix = rng.gen_range(0..=end_ix);
4135                assert_eq!(
4136                    snapshot
4137                        .bytes_in_range(start_ix..end_ix)
4138                        .flatten()
4139                        .copied()
4140                        .collect::<Vec<_>>(),
4141                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
4142                    "bytes_in_range({:?})",
4143                    start_ix..end_ix,
4144                );
4145            }
4146        }
4147
4148        let snapshot = multibuffer.read(cx).snapshot(cx);
4149        for (old_snapshot, subscription) in old_versions {
4150            let edits = subscription.consume().into_inner();
4151
4152            log::info!(
4153                "applying subscription edits to old text: {:?}: {:?}",
4154                old_snapshot.text(),
4155                edits,
4156            );
4157
4158            let mut text = old_snapshot.text();
4159            for edit in edits {
4160                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
4161                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
4162            }
4163            assert_eq!(text.to_string(), snapshot.text());
4164        }
4165    }
4166
4167    #[gpui::test]
4168    fn test_history(cx: &mut MutableAppContext) {
4169        cx.set_global(Settings::test(cx));
4170        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
4171        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
4172        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4173        let group_interval = multibuffer.read(cx).history.group_interval;
4174        multibuffer.update(cx, |multibuffer, cx| {
4175            multibuffer.push_excerpts(
4176                buffer_1.clone(),
4177                [ExcerptRange {
4178                    context: 0..buffer_1.read(cx).len(),
4179                    primary: None,
4180                }],
4181                cx,
4182            );
4183            multibuffer.push_excerpts(
4184                buffer_2.clone(),
4185                [ExcerptRange {
4186                    context: 0..buffer_2.read(cx).len(),
4187                    primary: None,
4188                }],
4189                cx,
4190            );
4191        });
4192
4193        let mut now = Instant::now();
4194
4195        multibuffer.update(cx, |multibuffer, cx| {
4196            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
4197            multibuffer.edit(
4198                [
4199                    (Point::new(0, 0)..Point::new(0, 0), "A"),
4200                    (Point::new(1, 0)..Point::new(1, 0), "A"),
4201                ],
4202                cx,
4203            );
4204            multibuffer.edit(
4205                [
4206                    (Point::new(0, 1)..Point::new(0, 1), "B"),
4207                    (Point::new(1, 1)..Point::new(1, 1), "B"),
4208                ],
4209                cx,
4210            );
4211            multibuffer.end_transaction_at(now, cx);
4212            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4213
4214            // Edit buffer 1 through the multibuffer
4215            now += 2 * group_interval;
4216            multibuffer.start_transaction_at(now, cx);
4217            multibuffer.edit([(2..2, "C")], cx);
4218            multibuffer.end_transaction_at(now, cx);
4219            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
4220
4221            // Edit buffer 1 independently
4222            buffer_1.update(cx, |buffer_1, cx| {
4223                buffer_1.start_transaction_at(now);
4224                buffer_1.edit([(3..3, "D")], cx);
4225                buffer_1.end_transaction_at(now, cx);
4226
4227                now += 2 * group_interval;
4228                buffer_1.start_transaction_at(now);
4229                buffer_1.edit([(4..4, "E")], cx);
4230                buffer_1.end_transaction_at(now, cx);
4231            });
4232            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4233
4234            // An undo in the multibuffer undoes the multibuffer transaction
4235            // and also any individual buffer edits that have occured since
4236            // that transaction.
4237            multibuffer.undo(cx);
4238            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4239
4240            multibuffer.undo(cx);
4241            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4242
4243            multibuffer.redo(cx);
4244            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4245
4246            multibuffer.redo(cx);
4247            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4248
4249            // Undo buffer 2 independently.
4250            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
4251            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
4252
4253            // An undo in the multibuffer undoes the components of the
4254            // the last multibuffer transaction that are not already undone.
4255            multibuffer.undo(cx);
4256            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
4257
4258            multibuffer.undo(cx);
4259            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4260
4261            multibuffer.redo(cx);
4262            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4263
4264            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
4265            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4266
4267            // Redo stack gets cleared after an edit.
4268            now += 2 * group_interval;
4269            multibuffer.start_transaction_at(now, cx);
4270            multibuffer.edit([(0..0, "X")], cx);
4271            multibuffer.end_transaction_at(now, cx);
4272            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4273            multibuffer.redo(cx);
4274            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4275            multibuffer.undo(cx);
4276            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4277            multibuffer.undo(cx);
4278            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4279
4280            // Transactions can be grouped manually.
4281            multibuffer.redo(cx);
4282            multibuffer.redo(cx);
4283            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4284            multibuffer.group_until_transaction(transaction_1, cx);
4285            multibuffer.undo(cx);
4286            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4287            multibuffer.redo(cx);
4288            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4289        });
4290    }
4291}