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