multi_buffer.rs

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