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