multi_buffer.rs

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