multi_buffer.rs

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