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