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        reversed: bool,
2596    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2597        self.as_singleton()
2598            .into_iter()
2599            .flat_map(move |(_, _, buffer)| {
2600                buffer.git_diff_hunks_in_range(row_range.clone(), reversed)
2601            })
2602    }
2603
2604    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2605        let range = range.start.to_offset(self)..range.end.to_offset(self);
2606
2607        let mut cursor = self.excerpts.cursor::<usize>();
2608        cursor.seek(&range.start, Bias::Right, &());
2609        let start_excerpt = cursor.item();
2610
2611        cursor.seek(&range.end, Bias::Right, &());
2612        let end_excerpt = cursor.item();
2613
2614        start_excerpt
2615            .zip(end_excerpt)
2616            .and_then(|(start_excerpt, end_excerpt)| {
2617                if start_excerpt.id != end_excerpt.id {
2618                    return None;
2619                }
2620
2621                let excerpt_buffer_start = start_excerpt
2622                    .range
2623                    .context
2624                    .start
2625                    .to_offset(&start_excerpt.buffer);
2626                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2627
2628                let start_in_buffer =
2629                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2630                let end_in_buffer =
2631                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2632                let mut ancestor_buffer_range = start_excerpt
2633                    .buffer
2634                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2635                ancestor_buffer_range.start =
2636                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2637                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2638
2639                let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
2640                let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
2641                Some(start..end)
2642            })
2643    }
2644
2645    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2646        let (excerpt_id, _, buffer) = self.as_singleton()?;
2647        let outline = buffer.outline(theme)?;
2648        Some(Outline::new(
2649            outline
2650                .items
2651                .into_iter()
2652                .map(|item| OutlineItem {
2653                    depth: item.depth,
2654                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2655                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2656                    text: item.text,
2657                    highlight_ranges: item.highlight_ranges,
2658                    name_ranges: item.name_ranges,
2659                })
2660                .collect(),
2661        ))
2662    }
2663
2664    pub fn symbols_containing<T: ToOffset>(
2665        &self,
2666        offset: T,
2667        theme: Option<&SyntaxTheme>,
2668    ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
2669        let anchor = self.anchor_before(offset);
2670        let excerpt_id = anchor.excerpt_id();
2671        let excerpt = self.excerpt(excerpt_id)?;
2672        Some((
2673            excerpt.buffer_id,
2674            excerpt
2675                .buffer
2676                .symbols_containing(anchor.text_anchor, theme)
2677                .into_iter()
2678                .flatten()
2679                .map(|item| OutlineItem {
2680                    depth: item.depth,
2681                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2682                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2683                    text: item.text,
2684                    highlight_ranges: item.highlight_ranges,
2685                    name_ranges: item.name_ranges,
2686                })
2687                .collect(),
2688        ))
2689    }
2690
2691    fn excerpt<'a>(&'a self, excerpt_id: &'a ExcerptId) -> Option<&'a Excerpt> {
2692        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2693        cursor.seek(&Some(excerpt_id), Bias::Left, &());
2694        if let Some(excerpt) = cursor.item() {
2695            if excerpt.id == *excerpt_id {
2696                return Some(excerpt);
2697            }
2698        }
2699        None
2700    }
2701
2702    pub fn remote_selections_in_range<'a>(
2703        &'a self,
2704        range: &'a Range<Anchor>,
2705    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
2706        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2707        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
2708        cursor
2709            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
2710            .flat_map(move |excerpt| {
2711                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
2712                if excerpt.id == range.start.excerpt_id {
2713                    query_range.start = range.start.text_anchor;
2714                }
2715                if excerpt.id == range.end.excerpt_id {
2716                    query_range.end = range.end.text_anchor;
2717                }
2718
2719                excerpt
2720                    .buffer
2721                    .remote_selections_in_range(query_range)
2722                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
2723                        selections.map(move |selection| {
2724                            let mut start = Anchor {
2725                                buffer_id: Some(excerpt.buffer_id),
2726                                excerpt_id: excerpt.id.clone(),
2727                                text_anchor: selection.start,
2728                            };
2729                            let mut end = Anchor {
2730                                buffer_id: Some(excerpt.buffer_id),
2731                                excerpt_id: excerpt.id.clone(),
2732                                text_anchor: selection.end,
2733                            };
2734                            if range.start.cmp(&start, self).is_gt() {
2735                                start = range.start.clone();
2736                            }
2737                            if range.end.cmp(&end, self).is_lt() {
2738                                end = range.end.clone();
2739                            }
2740
2741                            (
2742                                replica_id,
2743                                line_mode,
2744                                cursor_shape,
2745                                Selection {
2746                                    id: selection.id,
2747                                    start,
2748                                    end,
2749                                    reversed: selection.reversed,
2750                                    goal: selection.goal,
2751                                },
2752                            )
2753                        })
2754                    })
2755            })
2756    }
2757}
2758
2759#[cfg(any(test, feature = "test-support"))]
2760impl MultiBufferSnapshot {
2761    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
2762        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
2763        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
2764        start..end
2765    }
2766}
2767
2768impl History {
2769    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2770        self.transaction_depth += 1;
2771        if self.transaction_depth == 1 {
2772            let id = self.next_transaction_id.tick();
2773            self.undo_stack.push(Transaction {
2774                id,
2775                buffer_transactions: Default::default(),
2776                first_edit_at: now,
2777                last_edit_at: now,
2778                suppress_grouping: false,
2779            });
2780            Some(id)
2781        } else {
2782            None
2783        }
2784    }
2785
2786    fn end_transaction(
2787        &mut self,
2788        now: Instant,
2789        buffer_transactions: HashMap<usize, TransactionId>,
2790    ) -> bool {
2791        assert_ne!(self.transaction_depth, 0);
2792        self.transaction_depth -= 1;
2793        if self.transaction_depth == 0 {
2794            if buffer_transactions.is_empty() {
2795                self.undo_stack.pop();
2796                false
2797            } else {
2798                self.redo_stack.clear();
2799                let transaction = self.undo_stack.last_mut().unwrap();
2800                transaction.last_edit_at = now;
2801                for (buffer_id, transaction_id) in buffer_transactions {
2802                    transaction
2803                        .buffer_transactions
2804                        .entry(buffer_id)
2805                        .or_insert(transaction_id);
2806                }
2807                true
2808            }
2809        } else {
2810            false
2811        }
2812    }
2813
2814    fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
2815    where
2816        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
2817    {
2818        assert_eq!(self.transaction_depth, 0);
2819        let transaction = Transaction {
2820            id: self.next_transaction_id.tick(),
2821            buffer_transactions: buffer_transactions
2822                .into_iter()
2823                .map(|(buffer, transaction)| (buffer.id(), transaction.id))
2824                .collect(),
2825            first_edit_at: now,
2826            last_edit_at: now,
2827            suppress_grouping: false,
2828        };
2829        if !transaction.buffer_transactions.is_empty() {
2830            self.undo_stack.push(transaction);
2831            self.redo_stack.clear();
2832        }
2833    }
2834
2835    fn finalize_last_transaction(&mut self) {
2836        if let Some(transaction) = self.undo_stack.last_mut() {
2837            transaction.suppress_grouping = true;
2838        }
2839    }
2840
2841    fn pop_undo(&mut self) -> Option<&mut Transaction> {
2842        assert_eq!(self.transaction_depth, 0);
2843        if let Some(transaction) = self.undo_stack.pop() {
2844            self.redo_stack.push(transaction);
2845            self.redo_stack.last_mut()
2846        } else {
2847            None
2848        }
2849    }
2850
2851    fn pop_redo(&mut self) -> Option<&mut Transaction> {
2852        assert_eq!(self.transaction_depth, 0);
2853        if let Some(transaction) = self.redo_stack.pop() {
2854            self.undo_stack.push(transaction);
2855            self.undo_stack.last_mut()
2856        } else {
2857            None
2858        }
2859    }
2860
2861    fn group(&mut self) -> Option<TransactionId> {
2862        let mut count = 0;
2863        let mut transactions = self.undo_stack.iter();
2864        if let Some(mut transaction) = transactions.next_back() {
2865            while let Some(prev_transaction) = transactions.next_back() {
2866                if !prev_transaction.suppress_grouping
2867                    && transaction.first_edit_at - prev_transaction.last_edit_at
2868                        <= self.group_interval
2869                {
2870                    transaction = prev_transaction;
2871                    count += 1;
2872                } else {
2873                    break;
2874                }
2875            }
2876        }
2877        self.group_trailing(count)
2878    }
2879
2880    fn group_until(&mut self, transaction_id: TransactionId) {
2881        let mut count = 0;
2882        for transaction in self.undo_stack.iter().rev() {
2883            if transaction.id == transaction_id {
2884                self.group_trailing(count);
2885                break;
2886            } else if transaction.suppress_grouping {
2887                break;
2888            } else {
2889                count += 1;
2890            }
2891        }
2892    }
2893
2894    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
2895        let new_len = self.undo_stack.len() - n;
2896        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2897        if let Some(last_transaction) = transactions_to_keep.last_mut() {
2898            if let Some(transaction) = transactions_to_merge.last() {
2899                last_transaction.last_edit_at = transaction.last_edit_at;
2900            }
2901            for to_merge in transactions_to_merge {
2902                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
2903                    last_transaction
2904                        .buffer_transactions
2905                        .entry(*buffer_id)
2906                        .or_insert(*transaction_id);
2907                }
2908            }
2909        }
2910
2911        self.undo_stack.truncate(new_len);
2912        self.undo_stack.last().map(|t| t.id)
2913    }
2914}
2915
2916impl Excerpt {
2917    fn new(
2918        id: ExcerptId,
2919        key: usize,
2920        buffer_id: usize,
2921        buffer: BufferSnapshot,
2922        range: ExcerptRange<text::Anchor>,
2923        has_trailing_newline: bool,
2924    ) -> Self {
2925        Excerpt {
2926            id,
2927            key,
2928            max_buffer_row: range.context.end.to_point(&buffer).row,
2929            text_summary: buffer
2930                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
2931            buffer_id,
2932            buffer,
2933            range,
2934            has_trailing_newline,
2935        }
2936    }
2937
2938    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
2939        let content_start = self.range.context.start.to_offset(&self.buffer);
2940        let chunks_start = content_start + range.start;
2941        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
2942
2943        let footer_height = if self.has_trailing_newline
2944            && range.start <= self.text_summary.len
2945            && range.end > self.text_summary.len
2946        {
2947            1
2948        } else {
2949            0
2950        };
2951
2952        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2953
2954        ExcerptChunks {
2955            content_chunks,
2956            footer_height,
2957        }
2958    }
2959
2960    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2961        let content_start = self.range.context.start.to_offset(&self.buffer);
2962        let bytes_start = content_start + range.start;
2963        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
2964        let footer_height = if self.has_trailing_newline
2965            && range.start <= self.text_summary.len
2966            && range.end > self.text_summary.len
2967        {
2968            1
2969        } else {
2970            0
2971        };
2972        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2973
2974        ExcerptBytes {
2975            content_bytes,
2976            footer_height,
2977        }
2978    }
2979
2980    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2981        if text_anchor
2982            .cmp(&self.range.context.start, &self.buffer)
2983            .is_lt()
2984        {
2985            self.range.context.start
2986        } else if text_anchor
2987            .cmp(&self.range.context.end, &self.buffer)
2988            .is_gt()
2989        {
2990            self.range.context.end
2991        } else {
2992            text_anchor
2993        }
2994    }
2995
2996    fn contains(&self, anchor: &Anchor) -> bool {
2997        Some(self.buffer_id) == anchor.buffer_id
2998            && self
2999                .range
3000                .context
3001                .start
3002                .cmp(&anchor.text_anchor, &self.buffer)
3003                .is_le()
3004            && self
3005                .range
3006                .context
3007                .end
3008                .cmp(&anchor.text_anchor, &self.buffer)
3009                .is_ge()
3010    }
3011}
3012
3013impl fmt::Debug for Excerpt {
3014    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3015        f.debug_struct("Excerpt")
3016            .field("id", &self.id)
3017            .field("buffer_id", &self.buffer_id)
3018            .field("range", &self.range)
3019            .field("text_summary", &self.text_summary)
3020            .field("has_trailing_newline", &self.has_trailing_newline)
3021            .finish()
3022    }
3023}
3024
3025impl sum_tree::Item for Excerpt {
3026    type Summary = ExcerptSummary;
3027
3028    fn summary(&self) -> Self::Summary {
3029        let mut text = self.text_summary.clone();
3030        if self.has_trailing_newline {
3031            text += TextSummary::from("\n");
3032        }
3033        ExcerptSummary {
3034            excerpt_id: self.id.clone(),
3035            max_buffer_row: self.max_buffer_row,
3036            text,
3037        }
3038    }
3039}
3040
3041impl sum_tree::Summary for ExcerptSummary {
3042    type Context = ();
3043
3044    fn add_summary(&mut self, summary: &Self, _: &()) {
3045        debug_assert!(summary.excerpt_id > self.excerpt_id);
3046        self.excerpt_id = summary.excerpt_id.clone();
3047        self.text.add_summary(&summary.text, &());
3048        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3049    }
3050}
3051
3052impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3053    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3054        *self += &summary.text;
3055    }
3056}
3057
3058impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3059    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3060        *self += summary.text.len;
3061    }
3062}
3063
3064impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3065    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3066        Ord::cmp(self, &cursor_location.text.len)
3067    }
3068}
3069
3070impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
3071    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3072        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
3073    }
3074}
3075
3076impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3077    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3078        *self += summary.text.len_utf16;
3079    }
3080}
3081
3082impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3083    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3084        *self += summary.text.lines;
3085    }
3086}
3087
3088impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3089    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3090        *self += summary.text.lines_utf16()
3091    }
3092}
3093
3094impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
3095    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3096        *self = Some(&summary.excerpt_id);
3097    }
3098}
3099
3100impl<'a> MultiBufferRows<'a> {
3101    pub fn seek(&mut self, row: u32) {
3102        self.buffer_row_range = 0..0;
3103
3104        self.excerpts
3105            .seek_forward(&Point::new(row, 0), Bias::Right, &());
3106        if self.excerpts.item().is_none() {
3107            self.excerpts.prev(&());
3108
3109            if self.excerpts.item().is_none() && row == 0 {
3110                self.buffer_row_range = 0..1;
3111                return;
3112            }
3113        }
3114
3115        if let Some(excerpt) = self.excerpts.item() {
3116            let overshoot = row - self.excerpts.start().row;
3117            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3118            self.buffer_row_range.start = excerpt_start + overshoot;
3119            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3120        }
3121    }
3122}
3123
3124impl<'a> Iterator for MultiBufferRows<'a> {
3125    type Item = Option<u32>;
3126
3127    fn next(&mut self) -> Option<Self::Item> {
3128        loop {
3129            if !self.buffer_row_range.is_empty() {
3130                let row = Some(self.buffer_row_range.start);
3131                self.buffer_row_range.start += 1;
3132                return Some(row);
3133            }
3134            self.excerpts.item()?;
3135            self.excerpts.next(&());
3136            let excerpt = self.excerpts.item()?;
3137            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3138            self.buffer_row_range.end =
3139                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3140        }
3141    }
3142}
3143
3144impl<'a> MultiBufferChunks<'a> {
3145    pub fn offset(&self) -> usize {
3146        self.range.start
3147    }
3148
3149    pub fn seek(&mut self, offset: usize) {
3150        self.range.start = offset;
3151        self.excerpts.seek(&offset, Bias::Right, &());
3152        if let Some(excerpt) = self.excerpts.item() {
3153            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3154                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3155                self.language_aware,
3156            ));
3157        } else {
3158            self.excerpt_chunks = None;
3159        }
3160    }
3161}
3162
3163impl<'a> Iterator for MultiBufferChunks<'a> {
3164    type Item = Chunk<'a>;
3165
3166    fn next(&mut self) -> Option<Self::Item> {
3167        if self.range.is_empty() {
3168            None
3169        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3170            self.range.start += chunk.text.len();
3171            Some(chunk)
3172        } else {
3173            self.excerpts.next(&());
3174            let excerpt = self.excerpts.item()?;
3175            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3176                0..self.range.end - self.excerpts.start(),
3177                self.language_aware,
3178            ));
3179            self.next()
3180        }
3181    }
3182}
3183
3184impl<'a> MultiBufferBytes<'a> {
3185    fn consume(&mut self, len: usize) {
3186        self.range.start += len;
3187        self.chunk = &self.chunk[len..];
3188
3189        if !self.range.is_empty() && self.chunk.is_empty() {
3190            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3191                self.chunk = chunk;
3192            } else {
3193                self.excerpts.next(&());
3194                if let Some(excerpt) = self.excerpts.item() {
3195                    let mut excerpt_bytes =
3196                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3197                    self.chunk = excerpt_bytes.next().unwrap();
3198                    self.excerpt_bytes = Some(excerpt_bytes);
3199                }
3200            }
3201        }
3202    }
3203}
3204
3205impl<'a> Iterator for MultiBufferBytes<'a> {
3206    type Item = &'a [u8];
3207
3208    fn next(&mut self) -> Option<Self::Item> {
3209        let chunk = self.chunk;
3210        if chunk.is_empty() {
3211            None
3212        } else {
3213            self.consume(chunk.len());
3214            Some(chunk)
3215        }
3216    }
3217}
3218
3219impl<'a> io::Read for MultiBufferBytes<'a> {
3220    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3221        let len = cmp::min(buf.len(), self.chunk.len());
3222        buf[..len].copy_from_slice(&self.chunk[..len]);
3223        if len > 0 {
3224            self.consume(len);
3225        }
3226        Ok(len)
3227    }
3228}
3229
3230impl<'a> Iterator for ExcerptBytes<'a> {
3231    type Item = &'a [u8];
3232
3233    fn next(&mut self) -> Option<Self::Item> {
3234        if let Some(chunk) = self.content_bytes.next() {
3235            if !chunk.is_empty() {
3236                return Some(chunk);
3237            }
3238        }
3239
3240        if self.footer_height > 0 {
3241            let result = &NEWLINES[..self.footer_height];
3242            self.footer_height = 0;
3243            return Some(result);
3244        }
3245
3246        None
3247    }
3248}
3249
3250impl<'a> Iterator for ExcerptChunks<'a> {
3251    type Item = Chunk<'a>;
3252
3253    fn next(&mut self) -> Option<Self::Item> {
3254        if let Some(chunk) = self.content_chunks.next() {
3255            return Some(chunk);
3256        }
3257
3258        if self.footer_height > 0 {
3259            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3260            self.footer_height = 0;
3261            return Some(Chunk {
3262                text,
3263                ..Default::default()
3264            });
3265        }
3266
3267        None
3268    }
3269}
3270
3271impl ToOffset for Point {
3272    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3273        snapshot.point_to_offset(*self)
3274    }
3275}
3276
3277impl ToOffset for PointUtf16 {
3278    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3279        snapshot.point_utf16_to_offset(*self)
3280    }
3281}
3282
3283impl ToOffset for usize {
3284    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3285        assert!(*self <= snapshot.len(), "offset is out of range");
3286        *self
3287    }
3288}
3289
3290impl ToOffset for OffsetUtf16 {
3291    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3292        snapshot.offset_utf16_to_offset(*self)
3293    }
3294}
3295
3296impl ToOffsetUtf16 for OffsetUtf16 {
3297    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3298        *self
3299    }
3300}
3301
3302impl ToOffsetUtf16 for usize {
3303    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3304        snapshot.offset_to_offset_utf16(*self)
3305    }
3306}
3307
3308impl ToPoint for usize {
3309    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3310        snapshot.offset_to_point(*self)
3311    }
3312}
3313
3314impl ToPoint for Point {
3315    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3316        *self
3317    }
3318}
3319
3320impl ToPointUtf16 for usize {
3321    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3322        snapshot.offset_to_point_utf16(*self)
3323    }
3324}
3325
3326impl ToPointUtf16 for Point {
3327    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3328        snapshot.point_to_point_utf16(*self)
3329    }
3330}
3331
3332impl ToPointUtf16 for PointUtf16 {
3333    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3334        *self
3335    }
3336}
3337
3338#[cfg(test)]
3339mod tests {
3340    use super::*;
3341    use gpui::MutableAppContext;
3342    use language::{Buffer, Rope};
3343    use rand::prelude::*;
3344    use settings::Settings;
3345    use std::{env, rc::Rc};
3346
3347    use util::test::sample_text;
3348
3349    #[gpui::test]
3350    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
3351        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3352        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3353
3354        let snapshot = multibuffer.read(cx).snapshot(cx);
3355        assert_eq!(snapshot.text(), buffer.read(cx).text());
3356
3357        assert_eq!(
3358            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3359            (0..buffer.read(cx).row_count())
3360                .map(Some)
3361                .collect::<Vec<_>>()
3362        );
3363
3364        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
3365        let snapshot = multibuffer.read(cx).snapshot(cx);
3366
3367        assert_eq!(snapshot.text(), buffer.read(cx).text());
3368        assert_eq!(
3369            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3370            (0..buffer.read(cx).row_count())
3371                .map(Some)
3372                .collect::<Vec<_>>()
3373        );
3374    }
3375
3376    #[gpui::test]
3377    fn test_remote_multibuffer(cx: &mut MutableAppContext) {
3378        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3379        let guest_buffer = cx.add_model(|cx| {
3380            let state = host_buffer.read(cx).to_proto();
3381            let ops = cx
3382                .background()
3383                .block(host_buffer.read(cx).serialize_ops(cx));
3384            let mut buffer = Buffer::from_proto(1, state, None).unwrap();
3385            buffer
3386                .apply_ops(
3387                    ops.into_iter()
3388                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
3389                    cx,
3390                )
3391                .unwrap();
3392            buffer
3393        });
3394        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3395        let snapshot = multibuffer.read(cx).snapshot(cx);
3396        assert_eq!(snapshot.text(), "a");
3397
3398        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
3399        let snapshot = multibuffer.read(cx).snapshot(cx);
3400        assert_eq!(snapshot.text(), "ab");
3401
3402        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
3403        let snapshot = multibuffer.read(cx).snapshot(cx);
3404        assert_eq!(snapshot.text(), "abc");
3405    }
3406
3407    #[gpui::test]
3408    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
3409        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3410        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3411        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3412
3413        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3414        multibuffer.update(cx, |_, cx| {
3415            let events = events.clone();
3416            cx.subscribe(&multibuffer, move |_, _, event, _| {
3417                events.borrow_mut().push(event.clone())
3418            })
3419            .detach();
3420        });
3421
3422        let subscription = multibuffer.update(cx, |multibuffer, cx| {
3423            let subscription = multibuffer.subscribe();
3424            multibuffer.push_excerpts(
3425                buffer_1.clone(),
3426                [ExcerptRange {
3427                    context: Point::new(1, 2)..Point::new(2, 5),
3428                    primary: None,
3429                }],
3430                cx,
3431            );
3432            assert_eq!(
3433                subscription.consume().into_inner(),
3434                [Edit {
3435                    old: 0..0,
3436                    new: 0..10
3437                }]
3438            );
3439
3440            multibuffer.push_excerpts(
3441                buffer_1.clone(),
3442                [ExcerptRange {
3443                    context: Point::new(3, 3)..Point::new(4, 4),
3444                    primary: None,
3445                }],
3446                cx,
3447            );
3448            multibuffer.push_excerpts(
3449                buffer_2.clone(),
3450                [ExcerptRange {
3451                    context: Point::new(3, 1)..Point::new(3, 3),
3452                    primary: None,
3453                }],
3454                cx,
3455            );
3456            assert_eq!(
3457                subscription.consume().into_inner(),
3458                [Edit {
3459                    old: 10..10,
3460                    new: 10..22
3461                }]
3462            );
3463
3464            subscription
3465        });
3466
3467        // Adding excerpts emits an edited event.
3468        assert_eq!(
3469            events.borrow().as_slice(),
3470            &[Event::Edited, Event::Edited, Event::Edited]
3471        );
3472
3473        let snapshot = multibuffer.read(cx).snapshot(cx);
3474        assert_eq!(
3475            snapshot.text(),
3476            concat!(
3477                "bbbb\n",  // Preserve newlines
3478                "ccccc\n", //
3479                "ddd\n",   //
3480                "eeee\n",  //
3481                "jj"       //
3482            )
3483        );
3484        assert_eq!(
3485            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3486            [Some(1), Some(2), Some(3), Some(4), Some(3)]
3487        );
3488        assert_eq!(
3489            snapshot.buffer_rows(2).collect::<Vec<_>>(),
3490            [Some(3), Some(4), Some(3)]
3491        );
3492        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3493        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3494
3495        assert_eq!(
3496            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3497            &[
3498                (0, "bbbb\nccccc".to_string(), true),
3499                (2, "ddd\neeee".to_string(), false),
3500                (4, "jj".to_string(), true),
3501            ]
3502        );
3503        assert_eq!(
3504            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3505            &[(0, "bbbb\nccccc".to_string(), true)]
3506        );
3507        assert_eq!(
3508            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3509            &[]
3510        );
3511        assert_eq!(
3512            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3513            &[]
3514        );
3515        assert_eq!(
3516            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3517            &[(2, "ddd\neeee".to_string(), false)]
3518        );
3519        assert_eq!(
3520            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3521            &[(2, "ddd\neeee".to_string(), false)]
3522        );
3523        assert_eq!(
3524            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3525            &[(2, "ddd\neeee".to_string(), false)]
3526        );
3527        assert_eq!(
3528            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3529            &[(4, "jj".to_string(), true)]
3530        );
3531        assert_eq!(
3532            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
3533            &[]
3534        );
3535
3536        buffer_1.update(cx, |buffer, cx| {
3537            let text = "\n";
3538            buffer.edit(
3539                [
3540                    (Point::new(0, 0)..Point::new(0, 0), text),
3541                    (Point::new(2, 1)..Point::new(2, 3), text),
3542                ],
3543                None,
3544                cx,
3545            );
3546        });
3547
3548        let snapshot = multibuffer.read(cx).snapshot(cx);
3549        assert_eq!(
3550            snapshot.text(),
3551            concat!(
3552                "bbbb\n", // Preserve newlines
3553                "c\n",    //
3554                "cc\n",   //
3555                "ddd\n",  //
3556                "eeee\n", //
3557                "jj"      //
3558            )
3559        );
3560
3561        assert_eq!(
3562            subscription.consume().into_inner(),
3563            [Edit {
3564                old: 6..8,
3565                new: 6..7
3566            }]
3567        );
3568
3569        let snapshot = multibuffer.read(cx).snapshot(cx);
3570        assert_eq!(
3571            snapshot.clip_point(Point::new(0, 5), Bias::Left),
3572            Point::new(0, 4)
3573        );
3574        assert_eq!(
3575            snapshot.clip_point(Point::new(0, 5), Bias::Right),
3576            Point::new(0, 4)
3577        );
3578        assert_eq!(
3579            snapshot.clip_point(Point::new(5, 1), Bias::Right),
3580            Point::new(5, 1)
3581        );
3582        assert_eq!(
3583            snapshot.clip_point(Point::new(5, 2), Bias::Right),
3584            Point::new(5, 2)
3585        );
3586        assert_eq!(
3587            snapshot.clip_point(Point::new(5, 3), Bias::Right),
3588            Point::new(5, 2)
3589        );
3590
3591        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
3592            let (buffer_2_excerpt_id, _) =
3593                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
3594            multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
3595            multibuffer.snapshot(cx)
3596        });
3597
3598        assert_eq!(
3599            snapshot.text(),
3600            concat!(
3601                "bbbb\n", // Preserve newlines
3602                "c\n",    //
3603                "cc\n",   //
3604                "ddd\n",  //
3605                "eeee",   //
3606            )
3607        );
3608
3609        fn boundaries_in_range(
3610            range: Range<Point>,
3611            snapshot: &MultiBufferSnapshot,
3612        ) -> Vec<(u32, String, bool)> {
3613            snapshot
3614                .excerpt_boundaries_in_range(range)
3615                .map(|boundary| {
3616                    (
3617                        boundary.row,
3618                        boundary
3619                            .buffer
3620                            .text_for_range(boundary.range.context)
3621                            .collect::<String>(),
3622                        boundary.starts_new_buffer,
3623                    )
3624                })
3625                .collect::<Vec<_>>()
3626        }
3627    }
3628
3629    #[gpui::test]
3630    fn test_excerpts_with_context_lines(cx: &mut MutableAppContext) {
3631        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
3632        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3633        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
3634            multibuffer.push_excerpts_with_context_lines(
3635                buffer.clone(),
3636                vec![
3637                    Point::new(3, 2)..Point::new(4, 2),
3638                    Point::new(7, 1)..Point::new(7, 3),
3639                    Point::new(15, 0)..Point::new(15, 0),
3640                ],
3641                2,
3642                cx,
3643            )
3644        });
3645
3646        let snapshot = multibuffer.read(cx).snapshot(cx);
3647        assert_eq!(
3648            snapshot.text(),
3649            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
3650        );
3651
3652        assert_eq!(
3653            anchor_ranges
3654                .iter()
3655                .map(|range| range.to_point(&snapshot))
3656                .collect::<Vec<_>>(),
3657            vec![
3658                Point::new(2, 2)..Point::new(3, 2),
3659                Point::new(6, 1)..Point::new(6, 3),
3660                Point::new(12, 0)..Point::new(12, 0)
3661            ]
3662        );
3663    }
3664
3665    #[gpui::test]
3666    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
3667        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3668
3669        let snapshot = multibuffer.read(cx).snapshot(cx);
3670        assert_eq!(snapshot.text(), "");
3671        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
3672        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
3673    }
3674
3675    #[gpui::test]
3676    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
3677        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3678        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3679        let old_snapshot = multibuffer.read(cx).snapshot(cx);
3680        buffer.update(cx, |buffer, cx| {
3681            buffer.edit([(0..0, "X")], None, cx);
3682            buffer.edit([(5..5, "Y")], None, cx);
3683        });
3684        let new_snapshot = multibuffer.read(cx).snapshot(cx);
3685
3686        assert_eq!(old_snapshot.text(), "abcd");
3687        assert_eq!(new_snapshot.text(), "XabcdY");
3688
3689        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3690        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3691        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
3692        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
3693    }
3694
3695    #[gpui::test]
3696    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
3697        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3698        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
3699        let multibuffer = cx.add_model(|cx| {
3700            let mut multibuffer = MultiBuffer::new(0);
3701            multibuffer.push_excerpts(
3702                buffer_1.clone(),
3703                [ExcerptRange {
3704                    context: 0..4,
3705                    primary: None,
3706                }],
3707                cx,
3708            );
3709            multibuffer.push_excerpts(
3710                buffer_2.clone(),
3711                [ExcerptRange {
3712                    context: 0..5,
3713                    primary: None,
3714                }],
3715                cx,
3716            );
3717            multibuffer
3718        });
3719        let old_snapshot = multibuffer.read(cx).snapshot(cx);
3720
3721        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
3722        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
3723        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3724        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3725        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3726        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3727
3728        buffer_1.update(cx, |buffer, cx| {
3729            buffer.edit([(0..0, "W")], None, cx);
3730            buffer.edit([(5..5, "X")], None, cx);
3731        });
3732        buffer_2.update(cx, |buffer, cx| {
3733            buffer.edit([(0..0, "Y")], None, cx);
3734            buffer.edit([(6..6, "Z")], None, cx);
3735        });
3736        let new_snapshot = multibuffer.read(cx).snapshot(cx);
3737
3738        assert_eq!(old_snapshot.text(), "abcd\nefghi");
3739        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
3740
3741        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3742        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3743        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
3744        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
3745        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
3746        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
3747        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
3748        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
3749        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
3750        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
3751    }
3752
3753    #[gpui::test]
3754    fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
3755        cx: &mut MutableAppContext,
3756    ) {
3757        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3758        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
3759        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3760
3761        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
3762        // Add an excerpt from buffer 1 that spans this new insertion.
3763        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
3764        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
3765            multibuffer
3766                .push_excerpts(
3767                    buffer_1.clone(),
3768                    [ExcerptRange {
3769                        context: 0..7,
3770                        primary: None,
3771                    }],
3772                    cx,
3773                )
3774                .pop()
3775                .unwrap()
3776        });
3777
3778        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
3779        assert_eq!(snapshot_1.text(), "abcd123");
3780
3781        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
3782        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
3783            multibuffer.remove_excerpts([&excerpt_id_1], cx);
3784            let mut ids = multibuffer
3785                .push_excerpts(
3786                    buffer_2.clone(),
3787                    [
3788                        ExcerptRange {
3789                            context: 0..4,
3790                            primary: None,
3791                        },
3792                        ExcerptRange {
3793                            context: 6..10,
3794                            primary: None,
3795                        },
3796                        ExcerptRange {
3797                            context: 12..16,
3798                            primary: None,
3799                        },
3800                    ],
3801                    cx,
3802                )
3803                .into_iter();
3804            (ids.next().unwrap(), ids.next().unwrap())
3805        });
3806        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
3807        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
3808
3809        // The old excerpt id doesn't get reused.
3810        assert_ne!(excerpt_id_2, excerpt_id_1);
3811
3812        // Resolve some anchors from the previous snapshot in the new snapshot.
3813        // Although there is still an excerpt with the same id, it is for
3814        // a different buffer, so we don't attempt to resolve the old text
3815        // anchor in the new buffer.
3816        assert_eq!(
3817            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
3818            0
3819        );
3820        assert_eq!(
3821            snapshot_2.summaries_for_anchors::<usize, _>(&[
3822                snapshot_1.anchor_before(2),
3823                snapshot_1.anchor_after(3)
3824            ]),
3825            vec![0, 0]
3826        );
3827        let refresh =
3828            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
3829        assert_eq!(
3830            refresh,
3831            &[
3832                (0, snapshot_2.anchor_before(0), false),
3833                (1, snapshot_2.anchor_after(0), false),
3834            ]
3835        );
3836
3837        // Replace the middle excerpt with a smaller excerpt in buffer 2,
3838        // that intersects the old excerpt.
3839        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
3840            multibuffer.remove_excerpts([&excerpt_id_3], cx);
3841            multibuffer
3842                .insert_excerpts_after(
3843                    &excerpt_id_3,
3844                    buffer_2.clone(),
3845                    [ExcerptRange {
3846                        context: 5..8,
3847                        primary: None,
3848                    }],
3849                    cx,
3850                )
3851                .pop()
3852                .unwrap()
3853        });
3854
3855        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
3856        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
3857        assert_ne!(excerpt_id_5, excerpt_id_3);
3858
3859        // Resolve some anchors from the previous snapshot in the new snapshot.
3860        // The anchor in the middle excerpt snaps to the beginning of the
3861        // excerpt, since it is not
3862        let anchors = [
3863            snapshot_2.anchor_before(0),
3864            snapshot_2.anchor_after(2),
3865            snapshot_2.anchor_after(6),
3866            snapshot_2.anchor_after(14),
3867        ];
3868        assert_eq!(
3869            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
3870            &[0, 2, 5, 13]
3871        );
3872
3873        let new_anchors = snapshot_3.refresh_anchors(&anchors);
3874        assert_eq!(
3875            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
3876            &[(0, true), (1, true), (2, true), (3, true)]
3877        );
3878        assert_eq!(
3879            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
3880            &[0, 2, 7, 13]
3881        );
3882    }
3883
3884    #[gpui::test(iterations = 100)]
3885    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
3886        let operations = env::var("OPERATIONS")
3887            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3888            .unwrap_or(10);
3889
3890        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
3891        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3892        let mut excerpt_ids = Vec::new();
3893        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
3894        let mut anchors = Vec::new();
3895        let mut old_versions = Vec::new();
3896
3897        for _ in 0..operations {
3898            match rng.gen_range(0..100) {
3899                0..=19 if !buffers.is_empty() => {
3900                    let buffer = buffers.choose(&mut rng).unwrap();
3901                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
3902                }
3903                20..=29 if !expected_excerpts.is_empty() => {
3904                    let mut ids_to_remove = vec![];
3905                    for _ in 0..rng.gen_range(1..=3) {
3906                        if expected_excerpts.is_empty() {
3907                            break;
3908                        }
3909
3910                        let ix = rng.gen_range(0..expected_excerpts.len());
3911                        ids_to_remove.push(excerpt_ids.remove(ix));
3912                        let (buffer, range) = expected_excerpts.remove(ix);
3913                        let buffer = buffer.read(cx);
3914                        log::info!(
3915                            "Removing excerpt {}: {:?}",
3916                            ix,
3917                            buffer
3918                                .text_for_range(range.to_offset(buffer))
3919                                .collect::<String>(),
3920                        );
3921                    }
3922                    ids_to_remove.sort_unstable();
3923                    multibuffer.update(cx, |multibuffer, cx| {
3924                        multibuffer.remove_excerpts(&ids_to_remove, cx)
3925                    });
3926                }
3927                30..=39 if !expected_excerpts.is_empty() => {
3928                    let multibuffer = multibuffer.read(cx).read(cx);
3929                    let offset =
3930                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
3931                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
3932                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
3933                    anchors.push(multibuffer.anchor_at(offset, bias));
3934                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
3935                }
3936                40..=44 if !anchors.is_empty() => {
3937                    let multibuffer = multibuffer.read(cx).read(cx);
3938                    let prev_len = anchors.len();
3939                    anchors = multibuffer
3940                        .refresh_anchors(&anchors)
3941                        .into_iter()
3942                        .map(|a| a.1)
3943                        .collect();
3944
3945                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
3946                    // overshoot its boundaries.
3947                    assert_eq!(anchors.len(), prev_len);
3948                    let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
3949                    for anchor in &anchors {
3950                        if anchor.excerpt_id == ExcerptId::min()
3951                            || anchor.excerpt_id == ExcerptId::max()
3952                        {
3953                            continue;
3954                        }
3955
3956                        cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
3957                        let excerpt = cursor.item().unwrap();
3958                        assert_eq!(excerpt.id, anchor.excerpt_id);
3959                        assert!(excerpt.contains(anchor));
3960                    }
3961                }
3962                _ => {
3963                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
3964                        let base_text = util::RandomCharIter::new(&mut rng)
3965                            .take(10)
3966                            .collect::<String>();
3967                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
3968                        buffers.last().unwrap()
3969                    } else {
3970                        buffers.choose(&mut rng).unwrap()
3971                    };
3972
3973                    let buffer = buffer_handle.read(cx);
3974                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3975                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3976                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3977                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3978                    let prev_excerpt_id = excerpt_ids
3979                        .get(prev_excerpt_ix)
3980                        .cloned()
3981                        .unwrap_or_else(ExcerptId::max);
3982                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3983
3984                    log::info!(
3985                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3986                        excerpt_ix,
3987                        expected_excerpts.len(),
3988                        buffer_handle.id(),
3989                        buffer.text(),
3990                        start_ix..end_ix,
3991                        &buffer.text()[start_ix..end_ix]
3992                    );
3993
3994                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3995                        multibuffer
3996                            .insert_excerpts_after(
3997                                &prev_excerpt_id,
3998                                buffer_handle.clone(),
3999                                [ExcerptRange {
4000                                    context: start_ix..end_ix,
4001                                    primary: None,
4002                                }],
4003                                cx,
4004                            )
4005                            .pop()
4006                            .unwrap()
4007                    });
4008
4009                    excerpt_ids.insert(excerpt_ix, excerpt_id);
4010                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
4011                }
4012            }
4013
4014            if rng.gen_bool(0.3) {
4015                multibuffer.update(cx, |multibuffer, cx| {
4016                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
4017                })
4018            }
4019
4020            let snapshot = multibuffer.read(cx).snapshot(cx);
4021
4022            let mut excerpt_starts = Vec::new();
4023            let mut expected_text = String::new();
4024            let mut expected_buffer_rows = Vec::new();
4025            for (buffer, range) in &expected_excerpts {
4026                let buffer = buffer.read(cx);
4027                let buffer_range = range.to_offset(buffer);
4028
4029                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
4030                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
4031                expected_text.push('\n');
4032
4033                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
4034                    ..=buffer.offset_to_point(buffer_range.end).row;
4035                for row in buffer_row_range {
4036                    expected_buffer_rows.push(Some(row));
4037                }
4038            }
4039            // Remove final trailing newline.
4040            if !expected_excerpts.is_empty() {
4041                expected_text.pop();
4042            }
4043
4044            // Always report one buffer row
4045            if expected_buffer_rows.is_empty() {
4046                expected_buffer_rows.push(Some(0));
4047            }
4048
4049            assert_eq!(snapshot.text(), expected_text);
4050            log::info!("MultiBuffer text: {:?}", expected_text);
4051
4052            assert_eq!(
4053                snapshot.buffer_rows(0).collect::<Vec<_>>(),
4054                expected_buffer_rows,
4055            );
4056
4057            for _ in 0..5 {
4058                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
4059                assert_eq!(
4060                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
4061                    &expected_buffer_rows[start_row..],
4062                    "buffer_rows({})",
4063                    start_row
4064                );
4065            }
4066
4067            assert_eq!(
4068                snapshot.max_buffer_row(),
4069                expected_buffer_rows.into_iter().flatten().max().unwrap()
4070            );
4071
4072            let mut excerpt_starts = excerpt_starts.into_iter();
4073            for (buffer, range) in &expected_excerpts {
4074                let buffer_id = buffer.id();
4075                let buffer = buffer.read(cx);
4076                let buffer_range = range.to_offset(buffer);
4077                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
4078                let buffer_start_point_utf16 =
4079                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
4080
4081                let excerpt_start = excerpt_starts.next().unwrap();
4082                let mut offset = excerpt_start.len;
4083                let mut buffer_offset = buffer_range.start;
4084                let mut point = excerpt_start.lines;
4085                let mut buffer_point = buffer_start_point;
4086                let mut point_utf16 = excerpt_start.lines_utf16();
4087                let mut buffer_point_utf16 = buffer_start_point_utf16;
4088                for ch in buffer
4089                    .snapshot()
4090                    .chunks(buffer_range.clone(), false)
4091                    .flat_map(|c| c.text.chars())
4092                {
4093                    for _ in 0..ch.len_utf8() {
4094                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
4095                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
4096                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
4097                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
4098                        assert_eq!(
4099                            left_offset,
4100                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
4101                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
4102                            offset,
4103                            buffer_id,
4104                            buffer_offset,
4105                        );
4106                        assert_eq!(
4107                            right_offset,
4108                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
4109                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
4110                            offset,
4111                            buffer_id,
4112                            buffer_offset,
4113                        );
4114
4115                        let left_point = snapshot.clip_point(point, Bias::Left);
4116                        let right_point = snapshot.clip_point(point, Bias::Right);
4117                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
4118                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
4119                        assert_eq!(
4120                            left_point,
4121                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
4122                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
4123                            point,
4124                            buffer_id,
4125                            buffer_point,
4126                        );
4127                        assert_eq!(
4128                            right_point,
4129                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
4130                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
4131                            point,
4132                            buffer_id,
4133                            buffer_point,
4134                        );
4135
4136                        assert_eq!(
4137                            snapshot.point_to_offset(left_point),
4138                            left_offset,
4139                            "point_to_offset({:?})",
4140                            left_point,
4141                        );
4142                        assert_eq!(
4143                            snapshot.offset_to_point(left_offset),
4144                            left_point,
4145                            "offset_to_point({:?})",
4146                            left_offset,
4147                        );
4148
4149                        offset += 1;
4150                        buffer_offset += 1;
4151                        if ch == '\n' {
4152                            point += Point::new(1, 0);
4153                            buffer_point += Point::new(1, 0);
4154                        } else {
4155                            point += Point::new(0, 1);
4156                            buffer_point += Point::new(0, 1);
4157                        }
4158                    }
4159
4160                    for _ in 0..ch.len_utf16() {
4161                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
4162                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
4163                        let buffer_left_point_utf16 =
4164                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
4165                        let buffer_right_point_utf16 =
4166                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
4167                        assert_eq!(
4168                            left_point_utf16,
4169                            excerpt_start.lines_utf16()
4170                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
4171                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4172                            point_utf16,
4173                            buffer_id,
4174                            buffer_point_utf16,
4175                        );
4176                        assert_eq!(
4177                            right_point_utf16,
4178                            excerpt_start.lines_utf16()
4179                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
4180                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4181                            point_utf16,
4182                            buffer_id,
4183                            buffer_point_utf16,
4184                        );
4185
4186                        if ch == '\n' {
4187                            point_utf16 += PointUtf16::new(1, 0);
4188                            buffer_point_utf16 += PointUtf16::new(1, 0);
4189                        } else {
4190                            point_utf16 += PointUtf16::new(0, 1);
4191                            buffer_point_utf16 += PointUtf16::new(0, 1);
4192                        }
4193                    }
4194                }
4195            }
4196
4197            for (row, line) in expected_text.split('\n').enumerate() {
4198                assert_eq!(
4199                    snapshot.line_len(row as u32),
4200                    line.len() as u32,
4201                    "line_len({}).",
4202                    row
4203                );
4204            }
4205
4206            let text_rope = Rope::from(expected_text.as_str());
4207            for _ in 0..10 {
4208                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4209                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4210
4211                let text_for_range = snapshot
4212                    .text_for_range(start_ix..end_ix)
4213                    .collect::<String>();
4214                assert_eq!(
4215                    text_for_range,
4216                    &expected_text[start_ix..end_ix],
4217                    "incorrect text for range {:?}",
4218                    start_ix..end_ix
4219                );
4220
4221                let excerpted_buffer_ranges = multibuffer
4222                    .read(cx)
4223                    .range_to_buffer_ranges(start_ix..end_ix, cx);
4224                let excerpted_buffers_text = excerpted_buffer_ranges
4225                    .into_iter()
4226                    .map(|(buffer, buffer_range)| {
4227                        buffer
4228                            .read(cx)
4229                            .text_for_range(buffer_range)
4230                            .collect::<String>()
4231                    })
4232                    .collect::<Vec<_>>()
4233                    .join("\n");
4234                assert_eq!(excerpted_buffers_text, text_for_range);
4235
4236                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
4237                assert_eq!(
4238                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
4239                    expected_summary,
4240                    "incorrect summary for range {:?}",
4241                    start_ix..end_ix
4242                );
4243            }
4244
4245            // Anchor resolution
4246            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
4247            assert_eq!(anchors.len(), summaries.len());
4248            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
4249                assert!(resolved_offset <= snapshot.len());
4250                assert_eq!(
4251                    snapshot.summary_for_anchor::<usize>(anchor),
4252                    resolved_offset
4253                );
4254            }
4255
4256            for _ in 0..10 {
4257                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4258                assert_eq!(
4259                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
4260                    expected_text[..end_ix].chars().rev().collect::<String>(),
4261                );
4262            }
4263
4264            for _ in 0..10 {
4265                let end_ix = rng.gen_range(0..=text_rope.len());
4266                let start_ix = rng.gen_range(0..=end_ix);
4267                assert_eq!(
4268                    snapshot
4269                        .bytes_in_range(start_ix..end_ix)
4270                        .flatten()
4271                        .copied()
4272                        .collect::<Vec<_>>(),
4273                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
4274                    "bytes_in_range({:?})",
4275                    start_ix..end_ix,
4276                );
4277            }
4278        }
4279
4280        let snapshot = multibuffer.read(cx).snapshot(cx);
4281        for (old_snapshot, subscription) in old_versions {
4282            let edits = subscription.consume().into_inner();
4283
4284            log::info!(
4285                "applying subscription edits to old text: {:?}: {:?}",
4286                old_snapshot.text(),
4287                edits,
4288            );
4289
4290            let mut text = old_snapshot.text();
4291            for edit in edits {
4292                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
4293                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
4294            }
4295            assert_eq!(text.to_string(), snapshot.text());
4296        }
4297    }
4298
4299    #[gpui::test]
4300    fn test_history(cx: &mut MutableAppContext) {
4301        cx.set_global(Settings::test(cx));
4302        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
4303        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
4304        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4305        let group_interval = multibuffer.read(cx).history.group_interval;
4306        multibuffer.update(cx, |multibuffer, cx| {
4307            multibuffer.push_excerpts(
4308                buffer_1.clone(),
4309                [ExcerptRange {
4310                    context: 0..buffer_1.read(cx).len(),
4311                    primary: None,
4312                }],
4313                cx,
4314            );
4315            multibuffer.push_excerpts(
4316                buffer_2.clone(),
4317                [ExcerptRange {
4318                    context: 0..buffer_2.read(cx).len(),
4319                    primary: None,
4320                }],
4321                cx,
4322            );
4323        });
4324
4325        let mut now = Instant::now();
4326
4327        multibuffer.update(cx, |multibuffer, cx| {
4328            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
4329            multibuffer.edit(
4330                [
4331                    (Point::new(0, 0)..Point::new(0, 0), "A"),
4332                    (Point::new(1, 0)..Point::new(1, 0), "A"),
4333                ],
4334                None,
4335                cx,
4336            );
4337            multibuffer.edit(
4338                [
4339                    (Point::new(0, 1)..Point::new(0, 1), "B"),
4340                    (Point::new(1, 1)..Point::new(1, 1), "B"),
4341                ],
4342                None,
4343                cx,
4344            );
4345            multibuffer.end_transaction_at(now, cx);
4346            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4347
4348            // Edit buffer 1 through the multibuffer
4349            now += 2 * group_interval;
4350            multibuffer.start_transaction_at(now, cx);
4351            multibuffer.edit([(2..2, "C")], None, cx);
4352            multibuffer.end_transaction_at(now, cx);
4353            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
4354
4355            // Edit buffer 1 independently
4356            buffer_1.update(cx, |buffer_1, cx| {
4357                buffer_1.start_transaction_at(now);
4358                buffer_1.edit([(3..3, "D")], None, cx);
4359                buffer_1.end_transaction_at(now, cx);
4360
4361                now += 2 * group_interval;
4362                buffer_1.start_transaction_at(now);
4363                buffer_1.edit([(4..4, "E")], None, cx);
4364                buffer_1.end_transaction_at(now, cx);
4365            });
4366            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4367
4368            // An undo in the multibuffer undoes the multibuffer transaction
4369            // and also any individual buffer edits that have occured since
4370            // that transaction.
4371            multibuffer.undo(cx);
4372            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4373
4374            multibuffer.undo(cx);
4375            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4376
4377            multibuffer.redo(cx);
4378            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4379
4380            multibuffer.redo(cx);
4381            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4382
4383            // Undo buffer 2 independently.
4384            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
4385            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
4386
4387            // An undo in the multibuffer undoes the components of the
4388            // the last multibuffer transaction that are not already undone.
4389            multibuffer.undo(cx);
4390            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
4391
4392            multibuffer.undo(cx);
4393            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4394
4395            multibuffer.redo(cx);
4396            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4397
4398            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
4399            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4400
4401            // Redo stack gets cleared after an edit.
4402            now += 2 * group_interval;
4403            multibuffer.start_transaction_at(now, cx);
4404            multibuffer.edit([(0..0, "X")], None, cx);
4405            multibuffer.end_transaction_at(now, cx);
4406            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4407            multibuffer.redo(cx);
4408            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4409            multibuffer.undo(cx);
4410            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4411            multibuffer.undo(cx);
4412            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4413
4414            // Transactions can be grouped manually.
4415            multibuffer.redo(cx);
4416            multibuffer.redo(cx);
4417            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4418            multibuffer.group_until_transaction(transaction_1, cx);
4419            multibuffer.undo(cx);
4420            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4421            multibuffer.redo(cx);
4422            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4423        });
4424    }
4425}