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_multi<const COUNT: usize>(
1569        excerpts: [(&str, Vec<Range<Point>>); COUNT],
1570        cx: &mut gpui::AppContext,
1571    ) -> ModelHandle<Self> {
1572        let multi = cx.add_model(|_| Self::new(0));
1573        for (text, ranges) in excerpts {
1574            let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
1575            let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
1576                context: range,
1577                primary: None,
1578            });
1579            multi.update(cx, |multi, cx| {
1580                multi.push_excerpts(buffer, excerpt_ranges, cx)
1581            });
1582        }
1583
1584        multi
1585    }
1586
1587    pub fn build_from_buffer(
1588        buffer: ModelHandle<Buffer>,
1589        cx: &mut gpui::AppContext,
1590    ) -> ModelHandle<Self> {
1591        cx.add_model(|cx| Self::singleton(buffer, cx))
1592    }
1593
1594    pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> ModelHandle<Self> {
1595        cx.add_model(|cx| {
1596            let mut multibuffer = MultiBuffer::new(0);
1597            let mutation_count = rng.gen_range(1..=5);
1598            multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
1599            multibuffer
1600        })
1601    }
1602
1603    pub fn randomly_edit(
1604        &mut self,
1605        rng: &mut impl rand::Rng,
1606        edit_count: usize,
1607        cx: &mut ModelContext<Self>,
1608    ) {
1609        use util::RandomCharIter;
1610
1611        let snapshot = self.read(cx);
1612        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1613        let mut last_end = None;
1614        for _ in 0..edit_count {
1615            if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
1616                break;
1617            }
1618
1619            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1620            let end = snapshot.clip_offset(rng.gen_range(new_start..=snapshot.len()), Bias::Right);
1621            let start = snapshot.clip_offset(rng.gen_range(new_start..=end), Bias::Right);
1622            last_end = Some(end);
1623
1624            let mut range = start..end;
1625            if rng.gen_bool(0.2) {
1626                mem::swap(&mut range.start, &mut range.end);
1627            }
1628
1629            let new_text_len = rng.gen_range(0..10);
1630            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1631
1632            edits.push((range, new_text.into()));
1633        }
1634        log::info!("mutating multi-buffer with {:?}", edits);
1635        drop(snapshot);
1636
1637        self.edit(edits, None, cx);
1638    }
1639
1640    pub fn randomly_edit_excerpts(
1641        &mut self,
1642        rng: &mut impl rand::Rng,
1643        mutation_count: usize,
1644        cx: &mut ModelContext<Self>,
1645    ) {
1646        use rand::prelude::*;
1647        use std::env;
1648        use util::RandomCharIter;
1649
1650        let max_excerpts = env::var("MAX_EXCERPTS")
1651            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
1652            .unwrap_or(5);
1653
1654        let mut buffers = Vec::new();
1655        for _ in 0..mutation_count {
1656            if rng.gen_bool(0.05) {
1657                log::info!("Clearing multi-buffer");
1658                self.clear(cx);
1659                continue;
1660            }
1661
1662            let excerpt_ids = self.excerpt_ids();
1663            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
1664                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
1665                    let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
1666                    buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
1667                    let buffer = buffers.last().unwrap().read(cx);
1668                    log::info!(
1669                        "Creating new buffer {} with text: {:?}",
1670                        buffer.remote_id(),
1671                        buffer.text()
1672                    );
1673                    buffers.last().unwrap().clone()
1674                } else {
1675                    self.buffers
1676                        .borrow()
1677                        .values()
1678                        .choose(rng)
1679                        .unwrap()
1680                        .buffer
1681                        .clone()
1682                };
1683
1684                let buffer = buffer_handle.read(cx);
1685                let buffer_text = buffer.text();
1686                let ranges = (0..rng.gen_range(0..5))
1687                    .map(|_| {
1688                        let end_ix =
1689                            buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1690                        let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1691                        ExcerptRange {
1692                            context: start_ix..end_ix,
1693                            primary: None,
1694                        }
1695                    })
1696                    .collect::<Vec<_>>();
1697                log::info!(
1698                    "Inserting excerpts from buffer {} and ranges {:?}: {:?}",
1699                    buffer_handle.read(cx).remote_id(),
1700                    ranges.iter().map(|r| &r.context).collect::<Vec<_>>(),
1701                    ranges
1702                        .iter()
1703                        .map(|r| &buffer_text[r.context.clone()])
1704                        .collect::<Vec<_>>()
1705                );
1706
1707                let excerpt_id = self.push_excerpts(buffer_handle.clone(), ranges, cx);
1708                log::info!("Inserted with ids: {:?}", excerpt_id);
1709            } else {
1710                let remove_count = rng.gen_range(1..=excerpt_ids.len());
1711                let mut excerpts_to_remove = excerpt_ids
1712                    .choose_multiple(rng, remove_count)
1713                    .cloned()
1714                    .collect::<Vec<_>>();
1715                let snapshot = self.snapshot.borrow();
1716                excerpts_to_remove.sort_unstable_by(|a, b| a.cmp(b, &*snapshot));
1717                drop(snapshot);
1718                log::info!("Removing excerpts {:?}", excerpts_to_remove);
1719                self.remove_excerpts(excerpts_to_remove, cx);
1720            }
1721        }
1722    }
1723
1724    pub fn randomly_mutate(
1725        &mut self,
1726        rng: &mut impl rand::Rng,
1727        mutation_count: usize,
1728        cx: &mut ModelContext<Self>,
1729    ) {
1730        use rand::prelude::*;
1731
1732        if rng.gen_bool(0.7) || self.singleton {
1733            let buffer = self
1734                .buffers
1735                .borrow()
1736                .values()
1737                .choose(rng)
1738                .map(|state| state.buffer.clone());
1739
1740            if let Some(buffer) = buffer {
1741                buffer.update(cx, |buffer, cx| {
1742                    if rng.gen() {
1743                        buffer.randomly_edit(rng, mutation_count, cx);
1744                    } else {
1745                        buffer.randomly_undo_redo(rng, cx);
1746                    }
1747                });
1748            } else {
1749                self.randomly_edit(rng, mutation_count, cx);
1750            }
1751        } else {
1752            self.randomly_edit_excerpts(rng, mutation_count, cx);
1753        }
1754
1755        self.check_invariants(cx);
1756    }
1757
1758    fn check_invariants(&self, cx: &mut ModelContext<Self>) {
1759        let snapshot = self.read(cx);
1760        let excerpts = snapshot.excerpts.items(&());
1761        let excerpt_ids = snapshot.excerpt_ids.items(&());
1762
1763        for (ix, excerpt) in excerpts.iter().enumerate() {
1764            if ix == 0 {
1765                if excerpt.locator <= Locator::min() {
1766                    panic!("invalid first excerpt locator {:?}", excerpt.locator);
1767                }
1768            } else {
1769                if excerpt.locator <= excerpts[ix - 1].locator {
1770                    panic!("excerpts are out-of-order: {:?}", excerpts);
1771                }
1772            }
1773        }
1774
1775        for (ix, entry) in excerpt_ids.iter().enumerate() {
1776            if ix == 0 {
1777                if entry.id.cmp(&ExcerptId::min(), &*snapshot).is_le() {
1778                    panic!("invalid first excerpt id {:?}", entry.id);
1779                }
1780            } else {
1781                if entry.id <= excerpt_ids[ix - 1].id {
1782                    panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
1783                }
1784            }
1785        }
1786    }
1787}
1788
1789impl Entity for MultiBuffer {
1790    type Event = Event;
1791}
1792
1793impl MultiBufferSnapshot {
1794    pub fn text(&self) -> String {
1795        self.chunks(0..self.len(), false)
1796            .map(|chunk| chunk.text)
1797            .collect()
1798    }
1799
1800    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1801        let mut offset = position.to_offset(self);
1802        let mut cursor = self.excerpts.cursor::<usize>();
1803        cursor.seek(&offset, Bias::Left, &());
1804        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1805            let end_before_footer = cursor.start() + excerpt.text_summary.len;
1806            let start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1807            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1808            excerpt.buffer.reversed_chunks_in_range(start..end)
1809        });
1810        iter::from_fn(move || {
1811            if offset == *cursor.start() {
1812                cursor.prev(&());
1813                let excerpt = cursor.item()?;
1814                excerpt_chunks = Some(
1815                    excerpt
1816                        .buffer
1817                        .reversed_chunks_in_range(excerpt.range.context.clone()),
1818                );
1819            }
1820
1821            let excerpt = cursor.item().unwrap();
1822            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1823                offset -= 1;
1824                Some("\n")
1825            } else {
1826                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1827                offset -= chunk.len();
1828                Some(chunk)
1829            }
1830        })
1831        .flat_map(|c| c.chars().rev())
1832    }
1833
1834    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1835        let offset = position.to_offset(self);
1836        self.text_for_range(offset..self.len())
1837            .flat_map(|chunk| chunk.chars())
1838    }
1839
1840    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = &str> + '_ {
1841        self.chunks(range, false).map(|chunk| chunk.text)
1842    }
1843
1844    pub fn is_line_blank(&self, row: u32) -> bool {
1845        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1846            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1847    }
1848
1849    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1850    where
1851        T: ToOffset,
1852    {
1853        let position = position.to_offset(self);
1854        position == self.clip_offset(position, Bias::Left)
1855            && self
1856                .bytes_in_range(position..self.len())
1857                .flatten()
1858                .copied()
1859                .take(needle.len())
1860                .eq(needle.bytes())
1861    }
1862
1863    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1864        let mut start = start.to_offset(self);
1865        let mut end = start;
1866        let mut next_chars = self.chars_at(start).peekable();
1867        let mut prev_chars = self.reversed_chars_at(start).peekable();
1868        let word_kind = cmp::max(
1869            prev_chars.peek().copied().map(char_kind),
1870            next_chars.peek().copied().map(char_kind),
1871        );
1872
1873        for ch in prev_chars {
1874            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1875                start -= ch.len_utf8();
1876            } else {
1877                break;
1878            }
1879        }
1880
1881        for ch in next_chars {
1882            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1883                end += ch.len_utf8();
1884            } else {
1885                break;
1886            }
1887        }
1888
1889        (start..end, word_kind)
1890    }
1891
1892    pub fn as_singleton(&self) -> Option<(&ExcerptId, u64, &BufferSnapshot)> {
1893        if self.singleton {
1894            self.excerpts
1895                .iter()
1896                .next()
1897                .map(|e| (&e.id, e.buffer_id, &e.buffer))
1898        } else {
1899            None
1900        }
1901    }
1902
1903    pub fn len(&self) -> usize {
1904        self.excerpts.summary().text.len
1905    }
1906
1907    pub fn is_empty(&self) -> bool {
1908        self.excerpts.summary().text.len == 0
1909    }
1910
1911    pub fn max_buffer_row(&self) -> u32 {
1912        self.excerpts.summary().max_buffer_row
1913    }
1914
1915    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1916        if let Some((_, _, buffer)) = self.as_singleton() {
1917            return buffer.clip_offset(offset, bias);
1918        }
1919
1920        let mut cursor = self.excerpts.cursor::<usize>();
1921        cursor.seek(&offset, Bias::Right, &());
1922        let overshoot = if let Some(excerpt) = cursor.item() {
1923            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
1924            let buffer_offset = excerpt
1925                .buffer
1926                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1927            buffer_offset.saturating_sub(excerpt_start)
1928        } else {
1929            0
1930        };
1931        cursor.start() + overshoot
1932    }
1933
1934    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1935        if let Some((_, _, buffer)) = self.as_singleton() {
1936            return buffer.clip_point(point, bias);
1937        }
1938
1939        let mut cursor = self.excerpts.cursor::<Point>();
1940        cursor.seek(&point, Bias::Right, &());
1941        let overshoot = if let Some(excerpt) = cursor.item() {
1942            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1943            let buffer_point = excerpt
1944                .buffer
1945                .clip_point(excerpt_start + (point - cursor.start()), bias);
1946            buffer_point.saturating_sub(excerpt_start)
1947        } else {
1948            Point::zero()
1949        };
1950        *cursor.start() + overshoot
1951    }
1952
1953    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
1954        if let Some((_, _, buffer)) = self.as_singleton() {
1955            return buffer.clip_offset_utf16(offset, bias);
1956        }
1957
1958        let mut cursor = self.excerpts.cursor::<OffsetUtf16>();
1959        cursor.seek(&offset, Bias::Right, &());
1960        let overshoot = if let Some(excerpt) = cursor.item() {
1961            let excerpt_start = excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
1962            let buffer_offset = excerpt
1963                .buffer
1964                .clip_offset_utf16(excerpt_start + (offset - cursor.start()), bias);
1965            OffsetUtf16(buffer_offset.0.saturating_sub(excerpt_start.0))
1966        } else {
1967            OffsetUtf16(0)
1968        };
1969        *cursor.start() + overshoot
1970    }
1971
1972    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
1973        if let Some((_, _, buffer)) = self.as_singleton() {
1974            return buffer.clip_point_utf16(point, bias);
1975        }
1976
1977        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1978        cursor.seek(&point.0, Bias::Right, &());
1979        let overshoot = if let Some(excerpt) = cursor.item() {
1980            let excerpt_start = excerpt
1981                .buffer
1982                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
1983            let buffer_point = excerpt
1984                .buffer
1985                .clip_point_utf16(Unclipped(excerpt_start + (point.0 - cursor.start())), bias);
1986            buffer_point.saturating_sub(excerpt_start)
1987        } else {
1988            PointUtf16::zero()
1989        };
1990        *cursor.start() + overshoot
1991    }
1992
1993    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> MultiBufferBytes {
1994        let range = range.start.to_offset(self)..range.end.to_offset(self);
1995        let mut excerpts = self.excerpts.cursor::<usize>();
1996        excerpts.seek(&range.start, Bias::Right, &());
1997
1998        let mut chunk = &[][..];
1999        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2000            let mut excerpt_bytes = excerpt
2001                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
2002            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2003            Some(excerpt_bytes)
2004        } else {
2005            None
2006        };
2007        MultiBufferBytes {
2008            range,
2009            excerpts,
2010            excerpt_bytes,
2011            chunk,
2012        }
2013    }
2014
2015    pub fn reversed_bytes_in_range<T: ToOffset>(
2016        &self,
2017        range: Range<T>,
2018    ) -> ReversedMultiBufferBytes {
2019        let range = range.start.to_offset(self)..range.end.to_offset(self);
2020        let mut excerpts = self.excerpts.cursor::<usize>();
2021        excerpts.seek(&range.end, Bias::Left, &());
2022
2023        let mut chunk = &[][..];
2024        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
2025            let mut excerpt_bytes = excerpt.reversed_bytes_in_range(
2026                range.start - excerpts.start()..range.end - excerpts.start(),
2027            );
2028            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
2029            Some(excerpt_bytes)
2030        } else {
2031            None
2032        };
2033
2034        ReversedMultiBufferBytes {
2035            range,
2036            excerpts,
2037            excerpt_bytes,
2038            chunk,
2039        }
2040    }
2041
2042    pub fn buffer_rows(&self, start_row: u32) -> MultiBufferRows {
2043        let mut result = MultiBufferRows {
2044            buffer_row_range: 0..0,
2045            excerpts: self.excerpts.cursor(),
2046        };
2047        result.seek(start_row);
2048        result
2049    }
2050
2051    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> MultiBufferChunks {
2052        let range = range.start.to_offset(self)..range.end.to_offset(self);
2053        let mut chunks = MultiBufferChunks {
2054            range: range.clone(),
2055            excerpts: self.excerpts.cursor(),
2056            excerpt_chunks: None,
2057            language_aware,
2058        };
2059        chunks.seek(range.start);
2060        chunks
2061    }
2062
2063    pub fn offset_to_point(&self, offset: usize) -> Point {
2064        if let Some((_, _, buffer)) = self.as_singleton() {
2065            return buffer.offset_to_point(offset);
2066        }
2067
2068        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2069        cursor.seek(&offset, Bias::Right, &());
2070        if let Some(excerpt) = cursor.item() {
2071            let (start_offset, start_point) = cursor.start();
2072            let overshoot = offset - start_offset;
2073            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2074            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2075            let buffer_point = excerpt
2076                .buffer
2077                .offset_to_point(excerpt_start_offset + overshoot);
2078            *start_point + (buffer_point - excerpt_start_point)
2079        } else {
2080            self.excerpts.summary().text.lines
2081        }
2082    }
2083
2084    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
2085        if let Some((_, _, buffer)) = self.as_singleton() {
2086            return buffer.offset_to_point_utf16(offset);
2087        }
2088
2089        let mut cursor = self.excerpts.cursor::<(usize, PointUtf16)>();
2090        cursor.seek(&offset, Bias::Right, &());
2091        if let Some(excerpt) = cursor.item() {
2092            let (start_offset, start_point) = cursor.start();
2093            let overshoot = offset - start_offset;
2094            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2095            let excerpt_start_point = excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2096            let buffer_point = excerpt
2097                .buffer
2098                .offset_to_point_utf16(excerpt_start_offset + overshoot);
2099            *start_point + (buffer_point - excerpt_start_point)
2100        } else {
2101            self.excerpts.summary().text.lines_utf16()
2102        }
2103    }
2104
2105    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
2106        if let Some((_, _, buffer)) = self.as_singleton() {
2107            return buffer.point_to_point_utf16(point);
2108        }
2109
2110        let mut cursor = self.excerpts.cursor::<(Point, PointUtf16)>();
2111        cursor.seek(&point, Bias::Right, &());
2112        if let Some(excerpt) = cursor.item() {
2113            let (start_offset, start_point) = cursor.start();
2114            let overshoot = point - start_offset;
2115            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2116            let excerpt_start_point_utf16 =
2117                excerpt.range.context.start.to_point_utf16(&excerpt.buffer);
2118            let buffer_point = excerpt
2119                .buffer
2120                .point_to_point_utf16(excerpt_start_point + overshoot);
2121            *start_point + (buffer_point - excerpt_start_point_utf16)
2122        } else {
2123            self.excerpts.summary().text.lines_utf16()
2124        }
2125    }
2126
2127    pub fn point_to_offset(&self, point: Point) -> usize {
2128        if let Some((_, _, buffer)) = self.as_singleton() {
2129            return buffer.point_to_offset(point);
2130        }
2131
2132        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
2133        cursor.seek(&point, Bias::Right, &());
2134        if let Some(excerpt) = cursor.item() {
2135            let (start_point, start_offset) = cursor.start();
2136            let overshoot = point - start_point;
2137            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2138            let excerpt_start_point = excerpt.range.context.start.to_point(&excerpt.buffer);
2139            let buffer_offset = excerpt
2140                .buffer
2141                .point_to_offset(excerpt_start_point + overshoot);
2142            *start_offset + buffer_offset - excerpt_start_offset
2143        } else {
2144            self.excerpts.summary().text.len
2145        }
2146    }
2147
2148    pub fn offset_utf16_to_offset(&self, offset_utf16: OffsetUtf16) -> usize {
2149        if let Some((_, _, buffer)) = self.as_singleton() {
2150            return buffer.offset_utf16_to_offset(offset_utf16);
2151        }
2152
2153        let mut cursor = self.excerpts.cursor::<(OffsetUtf16, usize)>();
2154        cursor.seek(&offset_utf16, Bias::Right, &());
2155        if let Some(excerpt) = cursor.item() {
2156            let (start_offset_utf16, start_offset) = cursor.start();
2157            let overshoot = offset_utf16 - start_offset_utf16;
2158            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2159            let excerpt_start_offset_utf16 =
2160                excerpt.buffer.offset_to_offset_utf16(excerpt_start_offset);
2161            let buffer_offset = excerpt
2162                .buffer
2163                .offset_utf16_to_offset(excerpt_start_offset_utf16 + overshoot);
2164            *start_offset + (buffer_offset - excerpt_start_offset)
2165        } else {
2166            self.excerpts.summary().text.len
2167        }
2168    }
2169
2170    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
2171        if let Some((_, _, buffer)) = self.as_singleton() {
2172            return buffer.offset_to_offset_utf16(offset);
2173        }
2174
2175        let mut cursor = self.excerpts.cursor::<(usize, OffsetUtf16)>();
2176        cursor.seek(&offset, Bias::Right, &());
2177        if let Some(excerpt) = cursor.item() {
2178            let (start_offset, start_offset_utf16) = cursor.start();
2179            let overshoot = offset - start_offset;
2180            let excerpt_start_offset_utf16 =
2181                excerpt.range.context.start.to_offset_utf16(&excerpt.buffer);
2182            let excerpt_start_offset = excerpt
2183                .buffer
2184                .offset_utf16_to_offset(excerpt_start_offset_utf16);
2185            let buffer_offset_utf16 = excerpt
2186                .buffer
2187                .offset_to_offset_utf16(excerpt_start_offset + overshoot);
2188            *start_offset_utf16 + (buffer_offset_utf16 - excerpt_start_offset_utf16)
2189        } else {
2190            self.excerpts.summary().text.len_utf16
2191        }
2192    }
2193
2194    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
2195        if let Some((_, _, buffer)) = self.as_singleton() {
2196            return buffer.point_utf16_to_offset(point);
2197        }
2198
2199        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
2200        cursor.seek(&point, Bias::Right, &());
2201        if let Some(excerpt) = cursor.item() {
2202            let (start_point, start_offset) = cursor.start();
2203            let overshoot = point - start_point;
2204            let excerpt_start_offset = excerpt.range.context.start.to_offset(&excerpt.buffer);
2205            let excerpt_start_point = excerpt
2206                .buffer
2207                .offset_to_point_utf16(excerpt.range.context.start.to_offset(&excerpt.buffer));
2208            let buffer_offset = excerpt
2209                .buffer
2210                .point_utf16_to_offset(excerpt_start_point + overshoot);
2211            *start_offset + (buffer_offset - excerpt_start_offset)
2212        } else {
2213            self.excerpts.summary().text.len
2214        }
2215    }
2216
2217    pub fn point_to_buffer_offset<T: ToOffset>(
2218        &self,
2219        point: T,
2220    ) -> Option<(&BufferSnapshot, usize)> {
2221        let offset = point.to_offset(&self);
2222        let mut cursor = self.excerpts.cursor::<usize>();
2223        cursor.seek(&offset, Bias::Right, &());
2224        if cursor.item().is_none() {
2225            cursor.prev(&());
2226        }
2227
2228        cursor.item().map(|excerpt| {
2229            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2230            let buffer_point = excerpt_start + offset - *cursor.start();
2231            (&excerpt.buffer, buffer_point)
2232        })
2233    }
2234
2235    pub fn suggested_indents(
2236        &self,
2237        rows: impl IntoIterator<Item = u32>,
2238        cx: &AppContext,
2239    ) -> BTreeMap<u32, IndentSize> {
2240        let mut result = BTreeMap::new();
2241
2242        let mut rows_for_excerpt = Vec::new();
2243        let mut cursor = self.excerpts.cursor::<Point>();
2244        let mut rows = rows.into_iter().peekable();
2245        let mut prev_row = u32::MAX;
2246        let mut prev_language_indent_size = IndentSize::default();
2247
2248        while let Some(row) = rows.next() {
2249            cursor.seek(&Point::new(row, 0), Bias::Right, &());
2250            let excerpt = match cursor.item() {
2251                Some(excerpt) => excerpt,
2252                _ => continue,
2253            };
2254
2255            // Retrieve the language and indent size once for each disjoint region being indented.
2256            let single_indent_size = if row.saturating_sub(1) == prev_row {
2257                prev_language_indent_size
2258            } else {
2259                excerpt
2260                    .buffer
2261                    .language_indent_size_at(Point::new(row, 0), cx)
2262            };
2263            prev_language_indent_size = single_indent_size;
2264            prev_row = row;
2265
2266            let start_buffer_row = excerpt.range.context.start.to_point(&excerpt.buffer).row;
2267            let start_multibuffer_row = cursor.start().row;
2268
2269            rows_for_excerpt.push(row);
2270            while let Some(next_row) = rows.peek().copied() {
2271                if cursor.end(&()).row > next_row {
2272                    rows_for_excerpt.push(next_row);
2273                    rows.next();
2274                } else {
2275                    break;
2276                }
2277            }
2278
2279            let buffer_rows = rows_for_excerpt
2280                .drain(..)
2281                .map(|row| start_buffer_row + row - start_multibuffer_row);
2282            let buffer_indents = excerpt
2283                .buffer
2284                .suggested_indents(buffer_rows, single_indent_size);
2285            let multibuffer_indents = buffer_indents
2286                .into_iter()
2287                .map(|(row, indent)| (start_multibuffer_row + row - start_buffer_row, indent));
2288            result.extend(multibuffer_indents);
2289        }
2290
2291        result
2292    }
2293
2294    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
2295        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
2296            let mut size = buffer.indent_size_for_line(range.start.row);
2297            size.len = size
2298                .len
2299                .min(range.end.column)
2300                .saturating_sub(range.start.column);
2301            size
2302        } else {
2303            IndentSize::spaces(0)
2304        }
2305    }
2306
2307    pub fn line_len(&self, row: u32) -> u32 {
2308        if let Some((_, range)) = self.buffer_line_for_row(row) {
2309            range.end.column - range.start.column
2310        } else {
2311            0
2312        }
2313    }
2314
2315    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
2316        let mut cursor = self.excerpts.cursor::<Point>();
2317        let point = Point::new(row, 0);
2318        cursor.seek(&point, Bias::Right, &());
2319        if cursor.item().is_none() && *cursor.start() == point {
2320            cursor.prev(&());
2321        }
2322        if let Some(excerpt) = cursor.item() {
2323            let overshoot = row - cursor.start().row;
2324            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
2325            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
2326            let buffer_row = excerpt_start.row + overshoot;
2327            let line_start = Point::new(buffer_row, 0);
2328            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
2329            return Some((
2330                &excerpt.buffer,
2331                line_start.max(excerpt_start)..line_end.min(excerpt_end),
2332            ));
2333        }
2334        None
2335    }
2336
2337    pub fn max_point(&self) -> Point {
2338        self.text_summary().lines
2339    }
2340
2341    pub fn text_summary(&self) -> TextSummary {
2342        self.excerpts.summary().text.clone()
2343    }
2344
2345    pub fn text_summary_for_range<D, O>(&self, range: Range<O>) -> D
2346    where
2347        D: TextDimension,
2348        O: ToOffset,
2349    {
2350        let mut summary = D::default();
2351        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
2352        let mut cursor = self.excerpts.cursor::<usize>();
2353        cursor.seek(&range.start, Bias::Right, &());
2354        if let Some(excerpt) = cursor.item() {
2355            let mut end_before_newline = cursor.end(&());
2356            if excerpt.has_trailing_newline {
2357                end_before_newline -= 1;
2358            }
2359
2360            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2361            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2362            let end_in_excerpt =
2363                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2364            summary.add_assign(
2365                &excerpt
2366                    .buffer
2367                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2368            );
2369
2370            if range.end > end_before_newline {
2371                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2372            }
2373
2374            cursor.next(&());
2375        }
2376
2377        if range.end > *cursor.start() {
2378            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2379                &range.end,
2380                Bias::Right,
2381                &(),
2382            )));
2383            if let Some(excerpt) = cursor.item() {
2384                range.end = cmp::max(*cursor.start(), range.end);
2385
2386                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2387                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2388                summary.add_assign(
2389                    &excerpt
2390                        .buffer
2391                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2392                );
2393            }
2394        }
2395
2396        summary
2397    }
2398
2399    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2400    where
2401        D: TextDimension + Ord + Sub<D, Output = D>,
2402    {
2403        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2404        let locator = self.excerpt_locator_for_id(anchor.excerpt_id);
2405
2406        cursor.seek(locator, Bias::Left, &());
2407        if cursor.item().is_none() {
2408            cursor.next(&());
2409        }
2410
2411        let mut position = D::from_text_summary(&cursor.start().text);
2412        if let Some(excerpt) = cursor.item() {
2413            if excerpt.id == anchor.excerpt_id {
2414                let excerpt_buffer_start =
2415                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2416                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2417                let buffer_position = cmp::min(
2418                    excerpt_buffer_end,
2419                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2420                );
2421                if buffer_position > excerpt_buffer_start {
2422                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2423                }
2424            }
2425        }
2426        position
2427    }
2428
2429    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2430    where
2431        D: TextDimension + Ord + Sub<D, Output = D>,
2432        I: 'a + IntoIterator<Item = &'a Anchor>,
2433    {
2434        if let Some((_, _, buffer)) = self.as_singleton() {
2435            return buffer
2436                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2437                .collect();
2438        }
2439
2440        let mut anchors = anchors.into_iter().peekable();
2441        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2442        let mut summaries = Vec::new();
2443        while let Some(anchor) = anchors.peek() {
2444            let excerpt_id = anchor.excerpt_id;
2445            let excerpt_anchors = iter::from_fn(|| {
2446                let anchor = anchors.peek()?;
2447                if anchor.excerpt_id == excerpt_id {
2448                    Some(&anchors.next().unwrap().text_anchor)
2449                } else {
2450                    None
2451                }
2452            });
2453
2454            let locator = self.excerpt_locator_for_id(excerpt_id);
2455            cursor.seek_forward(locator, Bias::Left, &());
2456            if cursor.item().is_none() {
2457                cursor.next(&());
2458            }
2459
2460            let position = D::from_text_summary(&cursor.start().text);
2461            if let Some(excerpt) = cursor.item() {
2462                if excerpt.id == excerpt_id {
2463                    let excerpt_buffer_start =
2464                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2465                    let excerpt_buffer_end =
2466                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2467                    summaries.extend(
2468                        excerpt
2469                            .buffer
2470                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2471                            .map(move |summary| {
2472                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2473                                let mut position = position.clone();
2474                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2475                                if summary > excerpt_buffer_start {
2476                                    position.add_assign(&(summary - excerpt_buffer_start));
2477                                }
2478                                position
2479                            }),
2480                    );
2481                    continue;
2482                }
2483            }
2484
2485            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2486        }
2487
2488        summaries
2489    }
2490
2491    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2492    where
2493        I: 'a + IntoIterator<Item = &'a Anchor>,
2494    {
2495        let mut anchors = anchors.into_iter().enumerate().peekable();
2496        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2497        cursor.next(&());
2498
2499        let mut result = Vec::new();
2500
2501        while let Some((_, anchor)) = anchors.peek() {
2502            let old_excerpt_id = anchor.excerpt_id;
2503
2504            // Find the location where this anchor's excerpt should be.
2505            let old_locator = self.excerpt_locator_for_id(old_excerpt_id);
2506            cursor.seek_forward(&Some(old_locator), Bias::Left, &());
2507
2508            if cursor.item().is_none() {
2509                cursor.next(&());
2510            }
2511
2512            let next_excerpt = cursor.item();
2513            let prev_excerpt = cursor.prev_item();
2514
2515            // Process all of the anchors for this excerpt.
2516            while let Some((_, anchor)) = anchors.peek() {
2517                if anchor.excerpt_id != old_excerpt_id {
2518                    break;
2519                }
2520                let (anchor_ix, anchor) = anchors.next().unwrap();
2521                let mut anchor = *anchor;
2522
2523                // Leave min and max anchors unchanged if invalid or
2524                // if the old excerpt still exists at this location
2525                let mut kept_position = next_excerpt
2526                    .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
2527                    || old_excerpt_id == ExcerptId::max()
2528                    || old_excerpt_id == ExcerptId::min();
2529
2530                // If the old excerpt no longer exists at this location, then attempt to
2531                // find an equivalent position for this anchor in an adjacent excerpt.
2532                if !kept_position {
2533                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2534                        if excerpt.contains(&anchor) {
2535                            anchor.excerpt_id = excerpt.id.clone();
2536                            kept_position = true;
2537                            break;
2538                        }
2539                    }
2540                }
2541
2542                // If there's no adjacent excerpt that contains the anchor's position,
2543                // then report that the anchor has lost its position.
2544                if !kept_position {
2545                    anchor = if let Some(excerpt) = next_excerpt {
2546                        let mut text_anchor = excerpt
2547                            .range
2548                            .context
2549                            .start
2550                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2551                        if text_anchor
2552                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2553                            .is_gt()
2554                        {
2555                            text_anchor = excerpt.range.context.end;
2556                        }
2557                        Anchor {
2558                            buffer_id: Some(excerpt.buffer_id),
2559                            excerpt_id: excerpt.id.clone(),
2560                            text_anchor,
2561                        }
2562                    } else if let Some(excerpt) = prev_excerpt {
2563                        let mut text_anchor = excerpt
2564                            .range
2565                            .context
2566                            .end
2567                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2568                        if text_anchor
2569                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2570                            .is_lt()
2571                        {
2572                            text_anchor = excerpt.range.context.start;
2573                        }
2574                        Anchor {
2575                            buffer_id: Some(excerpt.buffer_id),
2576                            excerpt_id: excerpt.id.clone(),
2577                            text_anchor,
2578                        }
2579                    } else if anchor.text_anchor.bias == Bias::Left {
2580                        Anchor::min()
2581                    } else {
2582                        Anchor::max()
2583                    };
2584                }
2585
2586                result.push((anchor_ix, anchor, kept_position));
2587            }
2588        }
2589        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2590        result
2591    }
2592
2593    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2594        self.anchor_at(position, Bias::Left)
2595    }
2596
2597    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2598        self.anchor_at(position, Bias::Right)
2599    }
2600
2601    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2602        let offset = position.to_offset(self);
2603        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2604            return Anchor {
2605                buffer_id: Some(buffer_id),
2606                excerpt_id: excerpt_id.clone(),
2607                text_anchor: buffer.anchor_at(offset, bias),
2608            };
2609        }
2610
2611        let mut cursor = self.excerpts.cursor::<(usize, Option<ExcerptId>)>();
2612        cursor.seek(&offset, Bias::Right, &());
2613        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2614            cursor.prev(&());
2615        }
2616        if let Some(excerpt) = cursor.item() {
2617            let mut overshoot = offset.saturating_sub(cursor.start().0);
2618            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2619                overshoot -= 1;
2620                bias = Bias::Right;
2621            }
2622
2623            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2624            let text_anchor =
2625                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2626            Anchor {
2627                buffer_id: Some(excerpt.buffer_id),
2628                excerpt_id: excerpt.id.clone(),
2629                text_anchor,
2630            }
2631        } else if offset == 0 && bias == Bias::Left {
2632            Anchor::min()
2633        } else {
2634            Anchor::max()
2635        }
2636    }
2637
2638    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2639        let locator = self.excerpt_locator_for_id(excerpt_id);
2640        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
2641        cursor.seek(locator, Bias::Left, &());
2642        if let Some(excerpt) = cursor.item() {
2643            if excerpt.id == excerpt_id {
2644                let text_anchor = excerpt.clip_anchor(text_anchor);
2645                drop(cursor);
2646                return Anchor {
2647                    buffer_id: Some(excerpt.buffer_id),
2648                    excerpt_id,
2649                    text_anchor,
2650                };
2651            }
2652        }
2653        panic!("excerpt not found");
2654    }
2655
2656    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2657        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2658            true
2659        } else if let Some(excerpt) = self.excerpt(anchor.excerpt_id) {
2660            excerpt.buffer.can_resolve(&anchor.text_anchor)
2661        } else {
2662            false
2663        }
2664    }
2665
2666    pub fn excerpts(
2667        &self,
2668    ) -> impl Iterator<Item = (ExcerptId, &BufferSnapshot, ExcerptRange<text::Anchor>)> {
2669        self.excerpts
2670            .iter()
2671            .map(|excerpt| (excerpt.id, &excerpt.buffer, excerpt.range.clone()))
2672    }
2673
2674    pub fn excerpt_boundaries_in_range<R, T>(
2675        &self,
2676        range: R,
2677    ) -> impl Iterator<Item = ExcerptBoundary> + '_
2678    where
2679        R: RangeBounds<T>,
2680        T: ToOffset,
2681    {
2682        let start_offset;
2683        let start = match range.start_bound() {
2684            Bound::Included(start) => {
2685                start_offset = start.to_offset(self);
2686                Bound::Included(start_offset)
2687            }
2688            Bound::Excluded(start) => {
2689                start_offset = start.to_offset(self);
2690                Bound::Excluded(start_offset)
2691            }
2692            Bound::Unbounded => {
2693                start_offset = 0;
2694                Bound::Unbounded
2695            }
2696        };
2697        let end = match range.end_bound() {
2698            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2699            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2700            Bound::Unbounded => Bound::Unbounded,
2701        };
2702        let bounds = (start, end);
2703
2704        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2705        cursor.seek(&start_offset, Bias::Right, &());
2706        if cursor.item().is_none() {
2707            cursor.prev(&());
2708        }
2709        if !bounds.contains(&cursor.start().0) {
2710            cursor.next(&());
2711        }
2712
2713        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2714        std::iter::from_fn(move || {
2715            if self.singleton {
2716                None
2717            } else if bounds.contains(&cursor.start().0) {
2718                let excerpt = cursor.item()?;
2719                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2720                let boundary = ExcerptBoundary {
2721                    id: excerpt.id.clone(),
2722                    row: cursor.start().1.row,
2723                    buffer: excerpt.buffer.clone(),
2724                    range: excerpt.range.clone(),
2725                    starts_new_buffer,
2726                };
2727
2728                prev_buffer_id = Some(excerpt.buffer_id);
2729                cursor.next(&());
2730                Some(boundary)
2731            } else {
2732                None
2733            }
2734        })
2735    }
2736
2737    pub fn edit_count(&self) -> usize {
2738        self.edit_count
2739    }
2740
2741    pub fn parse_count(&self) -> usize {
2742        self.parse_count
2743    }
2744
2745    /// Returns the smallest enclosing bracket ranges containing the given range or
2746    /// None if no brackets contain range or the range is not contained in a single
2747    /// excerpt
2748    pub fn innermost_enclosing_bracket_ranges<T: ToOffset>(
2749        &self,
2750        range: Range<T>,
2751    ) -> Option<(Range<usize>, Range<usize>)> {
2752        let range = range.start.to_offset(self)..range.end.to_offset(self);
2753
2754        // Get the ranges of the innermost pair of brackets.
2755        let mut result: Option<(Range<usize>, Range<usize>)> = None;
2756
2757        let Some(enclosing_bracket_ranges) = self.enclosing_bracket_ranges(range.clone()) else { return None; };
2758
2759        for (open, close) in enclosing_bracket_ranges {
2760            let len = close.end - open.start;
2761
2762            if let Some((existing_open, existing_close)) = &result {
2763                let existing_len = existing_close.end - existing_open.start;
2764                if len > existing_len {
2765                    continue;
2766                }
2767            }
2768
2769            result = Some((open, close));
2770        }
2771
2772        result
2773    }
2774
2775    /// Returns enclosing bracket ranges containing the given range or returns None if the range is
2776    /// not contained in a single excerpt
2777    pub fn enclosing_bracket_ranges<'a, T: ToOffset>(
2778        &'a self,
2779        range: Range<T>,
2780    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2781        let range = range.start.to_offset(self)..range.end.to_offset(self);
2782
2783        self.bracket_ranges(range.clone()).map(|range_pairs| {
2784            range_pairs
2785                .filter(move |(open, close)| open.start <= range.start && close.end >= range.end)
2786        })
2787    }
2788
2789    /// Returns bracket range pairs overlapping the given `range` or returns None if the `range` is
2790    /// not contained in a single excerpt
2791    pub fn bracket_ranges<'a, T: ToOffset>(
2792        &'a self,
2793        range: Range<T>,
2794    ) -> Option<impl Iterator<Item = (Range<usize>, Range<usize>)> + 'a> {
2795        let range = range.start.to_offset(self)..range.end.to_offset(self);
2796        let excerpt = self.excerpt_containing(range.clone());
2797        excerpt.map(|(excerpt, excerpt_offset)| {
2798            let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2799            let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
2800
2801            let start_in_buffer = excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
2802            let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
2803
2804            excerpt
2805                .buffer
2806                .bracket_ranges(start_in_buffer..end_in_buffer)
2807                .filter_map(move |(start_bracket_range, end_bracket_range)| {
2808                    if start_bracket_range.start < excerpt_buffer_start
2809                        || end_bracket_range.end > excerpt_buffer_end
2810                    {
2811                        return None;
2812                    }
2813
2814                    let mut start_bracket_range = start_bracket_range.clone();
2815                    start_bracket_range.start =
2816                        excerpt_offset + (start_bracket_range.start - excerpt_buffer_start);
2817                    start_bracket_range.end =
2818                        excerpt_offset + (start_bracket_range.end - excerpt_buffer_start);
2819
2820                    let mut end_bracket_range = end_bracket_range.clone();
2821                    end_bracket_range.start =
2822                        excerpt_offset + (end_bracket_range.start - excerpt_buffer_start);
2823                    end_bracket_range.end =
2824                        excerpt_offset + (end_bracket_range.end - excerpt_buffer_start);
2825                    Some((start_bracket_range, end_bracket_range))
2826                })
2827        })
2828    }
2829
2830    pub fn diagnostics_update_count(&self) -> usize {
2831        self.diagnostics_update_count
2832    }
2833
2834    pub fn git_diff_update_count(&self) -> usize {
2835        self.git_diff_update_count
2836    }
2837
2838    pub fn trailing_excerpt_update_count(&self) -> usize {
2839        self.trailing_excerpt_update_count
2840    }
2841
2842    pub fn file_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<dyn File>> {
2843        self.point_to_buffer_offset(point)
2844            .and_then(|(buffer, _)| buffer.file())
2845    }
2846
2847    pub fn language_at<'a, T: ToOffset>(&'a self, point: T) -> Option<&'a Arc<Language>> {
2848        self.point_to_buffer_offset(point)
2849            .and_then(|(buffer, offset)| buffer.language_at(offset))
2850    }
2851
2852    pub fn settings_at<'a, T: ToOffset>(
2853        &'a self,
2854        point: T,
2855        cx: &'a AppContext,
2856    ) -> &'a LanguageSettings {
2857        let mut language = None;
2858        let mut file = None;
2859        if let Some((buffer, offset)) = self.point_to_buffer_offset(point) {
2860            language = buffer.language_at(offset);
2861            file = buffer.file();
2862        }
2863        language_settings(language, file, cx)
2864    }
2865
2866    pub fn language_scope_at<'a, T: ToOffset>(&'a self, point: T) -> Option<LanguageScope> {
2867        self.point_to_buffer_offset(point)
2868            .and_then(|(buffer, offset)| buffer.language_scope_at(offset))
2869    }
2870
2871    pub fn language_indent_size_at<T: ToOffset>(
2872        &self,
2873        position: T,
2874        cx: &AppContext,
2875    ) -> Option<IndentSize> {
2876        let (buffer_snapshot, offset) = self.point_to_buffer_offset(position)?;
2877        Some(buffer_snapshot.language_indent_size_at(offset, cx))
2878    }
2879
2880    pub fn is_dirty(&self) -> bool {
2881        self.is_dirty
2882    }
2883
2884    pub fn has_conflict(&self) -> bool {
2885        self.has_conflict
2886    }
2887
2888    pub fn diagnostic_group<'a, O>(
2889        &'a self,
2890        group_id: usize,
2891    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2892    where
2893        O: text::FromAnchor + 'a,
2894    {
2895        self.as_singleton()
2896            .into_iter()
2897            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2898    }
2899
2900    pub fn diagnostics_in_range<'a, T, O>(
2901        &'a self,
2902        range: Range<T>,
2903        reversed: bool,
2904    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2905    where
2906        T: 'a + ToOffset,
2907        O: 'a + text::FromAnchor + Ord,
2908    {
2909        self.as_singleton()
2910            .into_iter()
2911            .flat_map(move |(_, _, buffer)| {
2912                buffer.diagnostics_in_range(
2913                    range.start.to_offset(self)..range.end.to_offset(self),
2914                    reversed,
2915                )
2916            })
2917    }
2918
2919    pub fn has_git_diffs(&self) -> bool {
2920        for excerpt in self.excerpts.iter() {
2921            if !excerpt.buffer.git_diff.is_empty() {
2922                return true;
2923            }
2924        }
2925        false
2926    }
2927
2928    pub fn git_diff_hunks_in_range_rev<'a>(
2929        &'a self,
2930        row_range: Range<u32>,
2931    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2932        let mut cursor = self.excerpts.cursor::<Point>();
2933
2934        cursor.seek(&Point::new(row_range.end, 0), Bias::Left, &());
2935        if cursor.item().is_none() {
2936            cursor.prev(&());
2937        }
2938
2939        std::iter::from_fn(move || {
2940            let excerpt = cursor.item()?;
2941            let multibuffer_start = *cursor.start();
2942            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
2943            if multibuffer_start.row >= row_range.end {
2944                return None;
2945            }
2946
2947            let mut buffer_start = excerpt.range.context.start;
2948            let mut buffer_end = excerpt.range.context.end;
2949            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
2950            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
2951
2952            if row_range.start > multibuffer_start.row {
2953                let buffer_start_point =
2954                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
2955                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
2956            }
2957
2958            if row_range.end < multibuffer_end.row {
2959                let buffer_end_point =
2960                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
2961                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
2962            }
2963
2964            let buffer_hunks = excerpt
2965                .buffer
2966                .git_diff_hunks_intersecting_range_rev(buffer_start..buffer_end)
2967                .filter_map(move |hunk| {
2968                    let start = multibuffer_start.row
2969                        + hunk
2970                            .buffer_range
2971                            .start
2972                            .saturating_sub(excerpt_start_point.row);
2973                    let end = multibuffer_start.row
2974                        + hunk
2975                            .buffer_range
2976                            .end
2977                            .min(excerpt_end_point.row + 1)
2978                            .saturating_sub(excerpt_start_point.row);
2979
2980                    Some(DiffHunk {
2981                        buffer_range: start..end,
2982                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
2983                    })
2984                });
2985
2986            cursor.prev(&());
2987
2988            Some(buffer_hunks)
2989        })
2990        .flatten()
2991    }
2992
2993    pub fn git_diff_hunks_in_range<'a>(
2994        &'a self,
2995        row_range: Range<u32>,
2996    ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
2997        let mut cursor = self.excerpts.cursor::<Point>();
2998
2999        cursor.seek(&Point::new(row_range.start, 0), Bias::Right, &());
3000
3001        std::iter::from_fn(move || {
3002            let excerpt = cursor.item()?;
3003            let multibuffer_start = *cursor.start();
3004            let multibuffer_end = multibuffer_start + excerpt.text_summary.lines;
3005            if multibuffer_start.row >= row_range.end {
3006                return None;
3007            }
3008
3009            let mut buffer_start = excerpt.range.context.start;
3010            let mut buffer_end = excerpt.range.context.end;
3011            let excerpt_start_point = buffer_start.to_point(&excerpt.buffer);
3012            let excerpt_end_point = excerpt_start_point + excerpt.text_summary.lines;
3013
3014            if row_range.start > multibuffer_start.row {
3015                let buffer_start_point =
3016                    excerpt_start_point + Point::new(row_range.start - multibuffer_start.row, 0);
3017                buffer_start = excerpt.buffer.anchor_before(buffer_start_point);
3018            }
3019
3020            if row_range.end < multibuffer_end.row {
3021                let buffer_end_point =
3022                    excerpt_start_point + Point::new(row_range.end - multibuffer_start.row, 0);
3023                buffer_end = excerpt.buffer.anchor_before(buffer_end_point);
3024            }
3025
3026            let buffer_hunks = excerpt
3027                .buffer
3028                .git_diff_hunks_intersecting_range(buffer_start..buffer_end)
3029                .filter_map(move |hunk| {
3030                    let start = multibuffer_start.row
3031                        + hunk
3032                            .buffer_range
3033                            .start
3034                            .saturating_sub(excerpt_start_point.row);
3035                    let end = multibuffer_start.row
3036                        + hunk
3037                            .buffer_range
3038                            .end
3039                            .min(excerpt_end_point.row + 1)
3040                            .saturating_sub(excerpt_start_point.row);
3041
3042                    Some(DiffHunk {
3043                        buffer_range: start..end,
3044                        diff_base_byte_range: hunk.diff_base_byte_range.clone(),
3045                    })
3046                });
3047
3048            cursor.next(&());
3049
3050            Some(buffer_hunks)
3051        })
3052        .flatten()
3053    }
3054
3055    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
3056        let range = range.start.to_offset(self)..range.end.to_offset(self);
3057
3058        self.excerpt_containing(range.clone())
3059            .and_then(|(excerpt, excerpt_offset)| {
3060                let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
3061                let excerpt_buffer_end = excerpt_buffer_start + excerpt.text_summary.len;
3062
3063                let start_in_buffer =
3064                    excerpt_buffer_start + range.start.saturating_sub(excerpt_offset);
3065                let end_in_buffer = excerpt_buffer_start + range.end.saturating_sub(excerpt_offset);
3066                let mut ancestor_buffer_range = excerpt
3067                    .buffer
3068                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
3069                ancestor_buffer_range.start =
3070                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
3071                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
3072
3073                let start = excerpt_offset + (ancestor_buffer_range.start - excerpt_buffer_start);
3074                let end = excerpt_offset + (ancestor_buffer_range.end - excerpt_buffer_start);
3075                Some(start..end)
3076            })
3077    }
3078
3079    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
3080        let (excerpt_id, _, buffer) = self.as_singleton()?;
3081        let outline = buffer.outline(theme)?;
3082        Some(Outline::new(
3083            outline
3084                .items
3085                .into_iter()
3086                .map(|item| OutlineItem {
3087                    depth: item.depth,
3088                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
3089                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
3090                    text: item.text,
3091                    highlight_ranges: item.highlight_ranges,
3092                    name_ranges: item.name_ranges,
3093                })
3094                .collect(),
3095        ))
3096    }
3097
3098    pub fn symbols_containing<T: ToOffset>(
3099        &self,
3100        offset: T,
3101        theme: Option<&SyntaxTheme>,
3102    ) -> Option<(u64, Vec<OutlineItem<Anchor>>)> {
3103        let anchor = self.anchor_before(offset);
3104        let excerpt_id = anchor.excerpt_id();
3105        let excerpt = self.excerpt(excerpt_id)?;
3106        Some((
3107            excerpt.buffer_id,
3108            excerpt
3109                .buffer
3110                .symbols_containing(anchor.text_anchor, theme)
3111                .into_iter()
3112                .flatten()
3113                .map(|item| OutlineItem {
3114                    depth: item.depth,
3115                    range: self.anchor_in_excerpt(excerpt_id, item.range.start)
3116                        ..self.anchor_in_excerpt(excerpt_id, item.range.end),
3117                    text: item.text,
3118                    highlight_ranges: item.highlight_ranges,
3119                    name_ranges: item.name_ranges,
3120                })
3121                .collect(),
3122        ))
3123    }
3124
3125    fn excerpt_locator_for_id<'a>(&'a self, id: ExcerptId) -> &'a Locator {
3126        if id == ExcerptId::min() {
3127            Locator::min_ref()
3128        } else if id == ExcerptId::max() {
3129            Locator::max_ref()
3130        } else {
3131            let mut cursor = self.excerpt_ids.cursor::<ExcerptId>();
3132            cursor.seek(&id, Bias::Left, &());
3133            if let Some(entry) = cursor.item() {
3134                if entry.id == id {
3135                    return &entry.locator;
3136                }
3137            }
3138            panic!("invalid excerpt id {:?}", id)
3139        }
3140    }
3141
3142    pub fn buffer_id_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<u64> {
3143        Some(self.excerpt(excerpt_id)?.buffer_id)
3144    }
3145
3146    pub fn buffer_for_excerpt(&self, excerpt_id: ExcerptId) -> Option<&BufferSnapshot> {
3147        Some(&self.excerpt(excerpt_id)?.buffer)
3148    }
3149
3150    fn excerpt<'a>(&'a self, excerpt_id: ExcerptId) -> Option<&'a Excerpt> {
3151        let mut cursor = self.excerpts.cursor::<Option<&Locator>>();
3152        let locator = self.excerpt_locator_for_id(excerpt_id);
3153        cursor.seek(&Some(locator), Bias::Left, &());
3154        if let Some(excerpt) = cursor.item() {
3155            if excerpt.id == excerpt_id {
3156                return Some(excerpt);
3157            }
3158        }
3159        None
3160    }
3161
3162    /// Returns the excerpt containing range and its offset start within the multibuffer or none if `range` spans multiple excerpts
3163    fn excerpt_containing<'a, T: ToOffset>(
3164        &'a self,
3165        range: Range<T>,
3166    ) -> Option<(&'a Excerpt, usize)> {
3167        let range = range.start.to_offset(self)..range.end.to_offset(self);
3168
3169        let mut cursor = self.excerpts.cursor::<usize>();
3170        cursor.seek(&range.start, Bias::Right, &());
3171        let start_excerpt = cursor.item();
3172
3173        if range.start == range.end {
3174            return start_excerpt.map(|excerpt| (excerpt, *cursor.start()));
3175        }
3176
3177        cursor.seek(&range.end, Bias::Right, &());
3178        let end_excerpt = cursor.item();
3179
3180        start_excerpt
3181            .zip(end_excerpt)
3182            .and_then(|(start_excerpt, end_excerpt)| {
3183                if start_excerpt.id != end_excerpt.id {
3184                    return None;
3185                }
3186
3187                Some((start_excerpt, *cursor.start()))
3188            })
3189    }
3190
3191    pub fn remote_selections_in_range<'a>(
3192        &'a self,
3193        range: &'a Range<Anchor>,
3194    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, CursorShape, Selection<Anchor>)> {
3195        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
3196        let start_locator = self.excerpt_locator_for_id(range.start.excerpt_id);
3197        let end_locator = self.excerpt_locator_for_id(range.end.excerpt_id);
3198        cursor.seek(start_locator, Bias::Left, &());
3199        cursor
3200            .take_while(move |excerpt| excerpt.locator <= *end_locator)
3201            .flat_map(move |excerpt| {
3202                let mut query_range = excerpt.range.context.start..excerpt.range.context.end;
3203                if excerpt.id == range.start.excerpt_id {
3204                    query_range.start = range.start.text_anchor;
3205                }
3206                if excerpt.id == range.end.excerpt_id {
3207                    query_range.end = range.end.text_anchor;
3208                }
3209
3210                excerpt
3211                    .buffer
3212                    .remote_selections_in_range(query_range)
3213                    .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| {
3214                        selections.map(move |selection| {
3215                            let mut start = Anchor {
3216                                buffer_id: Some(excerpt.buffer_id),
3217                                excerpt_id: excerpt.id.clone(),
3218                                text_anchor: selection.start,
3219                            };
3220                            let mut end = Anchor {
3221                                buffer_id: Some(excerpt.buffer_id),
3222                                excerpt_id: excerpt.id.clone(),
3223                                text_anchor: selection.end,
3224                            };
3225                            if range.start.cmp(&start, self).is_gt() {
3226                                start = range.start.clone();
3227                            }
3228                            if range.end.cmp(&end, self).is_lt() {
3229                                end = range.end.clone();
3230                            }
3231
3232                            (
3233                                replica_id,
3234                                line_mode,
3235                                cursor_shape,
3236                                Selection {
3237                                    id: selection.id,
3238                                    start,
3239                                    end,
3240                                    reversed: selection.reversed,
3241                                    goal: selection.goal,
3242                                },
3243                            )
3244                        })
3245                    })
3246            })
3247    }
3248}
3249
3250#[cfg(any(test, feature = "test-support"))]
3251impl MultiBufferSnapshot {
3252    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
3253        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
3254        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
3255        start..end
3256    }
3257}
3258
3259impl History {
3260    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
3261        self.transaction_depth += 1;
3262        if self.transaction_depth == 1 {
3263            let id = self.next_transaction_id.tick();
3264            self.undo_stack.push(Transaction {
3265                id,
3266                buffer_transactions: Default::default(),
3267                first_edit_at: now,
3268                last_edit_at: now,
3269                suppress_grouping: false,
3270            });
3271            Some(id)
3272        } else {
3273            None
3274        }
3275    }
3276
3277    fn end_transaction(
3278        &mut self,
3279        now: Instant,
3280        buffer_transactions: HashMap<u64, TransactionId>,
3281    ) -> bool {
3282        assert_ne!(self.transaction_depth, 0);
3283        self.transaction_depth -= 1;
3284        if self.transaction_depth == 0 {
3285            if buffer_transactions.is_empty() {
3286                self.undo_stack.pop();
3287                false
3288            } else {
3289                self.redo_stack.clear();
3290                let transaction = self.undo_stack.last_mut().unwrap();
3291                transaction.last_edit_at = now;
3292                for (buffer_id, transaction_id) in buffer_transactions {
3293                    transaction
3294                        .buffer_transactions
3295                        .entry(buffer_id)
3296                        .or_insert(transaction_id);
3297                }
3298                true
3299            }
3300        } else {
3301            false
3302        }
3303    }
3304
3305    fn push_transaction<'a, T>(
3306        &mut self,
3307        buffer_transactions: T,
3308        now: Instant,
3309        cx: &mut ModelContext<MultiBuffer>,
3310    ) where
3311        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
3312    {
3313        assert_eq!(self.transaction_depth, 0);
3314        let transaction = Transaction {
3315            id: self.next_transaction_id.tick(),
3316            buffer_transactions: buffer_transactions
3317                .into_iter()
3318                .map(|(buffer, transaction)| (buffer.read(cx).remote_id(), transaction.id))
3319                .collect(),
3320            first_edit_at: now,
3321            last_edit_at: now,
3322            suppress_grouping: false,
3323        };
3324        if !transaction.buffer_transactions.is_empty() {
3325            self.undo_stack.push(transaction);
3326            self.redo_stack.clear();
3327        }
3328    }
3329
3330    fn finalize_last_transaction(&mut self) {
3331        if let Some(transaction) = self.undo_stack.last_mut() {
3332            transaction.suppress_grouping = true;
3333        }
3334    }
3335
3336    fn pop_undo(&mut self) -> Option<&mut Transaction> {
3337        assert_eq!(self.transaction_depth, 0);
3338        if let Some(transaction) = self.undo_stack.pop() {
3339            self.redo_stack.push(transaction);
3340            self.redo_stack.last_mut()
3341        } else {
3342            None
3343        }
3344    }
3345
3346    fn pop_redo(&mut self) -> Option<&mut Transaction> {
3347        assert_eq!(self.transaction_depth, 0);
3348        if let Some(transaction) = self.redo_stack.pop() {
3349            self.undo_stack.push(transaction);
3350            self.undo_stack.last_mut()
3351        } else {
3352            None
3353        }
3354    }
3355
3356    fn group(&mut self) -> Option<TransactionId> {
3357        let mut count = 0;
3358        let mut transactions = self.undo_stack.iter();
3359        if let Some(mut transaction) = transactions.next_back() {
3360            while let Some(prev_transaction) = transactions.next_back() {
3361                if !prev_transaction.suppress_grouping
3362                    && transaction.first_edit_at - prev_transaction.last_edit_at
3363                        <= self.group_interval
3364                {
3365                    transaction = prev_transaction;
3366                    count += 1;
3367                } else {
3368                    break;
3369                }
3370            }
3371        }
3372        self.group_trailing(count)
3373    }
3374
3375    fn group_until(&mut self, transaction_id: TransactionId) {
3376        let mut count = 0;
3377        for transaction in self.undo_stack.iter().rev() {
3378            if transaction.id == transaction_id {
3379                self.group_trailing(count);
3380                break;
3381            } else if transaction.suppress_grouping {
3382                break;
3383            } else {
3384                count += 1;
3385            }
3386        }
3387    }
3388
3389    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
3390        let new_len = self.undo_stack.len() - n;
3391        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
3392        if let Some(last_transaction) = transactions_to_keep.last_mut() {
3393            if let Some(transaction) = transactions_to_merge.last() {
3394                last_transaction.last_edit_at = transaction.last_edit_at;
3395            }
3396            for to_merge in transactions_to_merge {
3397                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
3398                    last_transaction
3399                        .buffer_transactions
3400                        .entry(*buffer_id)
3401                        .or_insert(*transaction_id);
3402                }
3403            }
3404        }
3405
3406        self.undo_stack.truncate(new_len);
3407        self.undo_stack.last().map(|t| t.id)
3408    }
3409}
3410
3411impl Excerpt {
3412    fn new(
3413        id: ExcerptId,
3414        locator: Locator,
3415        buffer_id: u64,
3416        buffer: BufferSnapshot,
3417        range: ExcerptRange<text::Anchor>,
3418        has_trailing_newline: bool,
3419    ) -> Self {
3420        Excerpt {
3421            id,
3422            locator,
3423            max_buffer_row: range.context.end.to_point(&buffer).row,
3424            text_summary: buffer
3425                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
3426            buffer_id,
3427            buffer,
3428            range,
3429            has_trailing_newline,
3430        }
3431    }
3432
3433    fn chunks_in_range(&self, range: Range<usize>, language_aware: bool) -> ExcerptChunks {
3434        let content_start = self.range.context.start.to_offset(&self.buffer);
3435        let chunks_start = content_start + range.start;
3436        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
3437
3438        let footer_height = if self.has_trailing_newline
3439            && range.start <= self.text_summary.len
3440            && range.end > self.text_summary.len
3441        {
3442            1
3443        } else {
3444            0
3445        };
3446
3447        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
3448
3449        ExcerptChunks {
3450            content_chunks,
3451            footer_height,
3452        }
3453    }
3454
3455    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3456        let content_start = self.range.context.start.to_offset(&self.buffer);
3457        let bytes_start = content_start + range.start;
3458        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3459        let footer_height = if self.has_trailing_newline
3460            && range.start <= self.text_summary.len
3461            && range.end > self.text_summary.len
3462        {
3463            1
3464        } else {
3465            0
3466        };
3467        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
3468
3469        ExcerptBytes {
3470            content_bytes,
3471            footer_height,
3472        }
3473    }
3474
3475    fn reversed_bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
3476        let content_start = self.range.context.start.to_offset(&self.buffer);
3477        let bytes_start = content_start + range.start;
3478        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
3479        let footer_height = if self.has_trailing_newline
3480            && range.start <= self.text_summary.len
3481            && range.end > self.text_summary.len
3482        {
3483            1
3484        } else {
3485            0
3486        };
3487        let content_bytes = self.buffer.reversed_bytes_in_range(bytes_start..bytes_end);
3488
3489        ExcerptBytes {
3490            content_bytes,
3491            footer_height,
3492        }
3493    }
3494
3495    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
3496        if text_anchor
3497            .cmp(&self.range.context.start, &self.buffer)
3498            .is_lt()
3499        {
3500            self.range.context.start
3501        } else if text_anchor
3502            .cmp(&self.range.context.end, &self.buffer)
3503            .is_gt()
3504        {
3505            self.range.context.end
3506        } else {
3507            text_anchor
3508        }
3509    }
3510
3511    fn contains(&self, anchor: &Anchor) -> bool {
3512        Some(self.buffer_id) == anchor.buffer_id
3513            && self
3514                .range
3515                .context
3516                .start
3517                .cmp(&anchor.text_anchor, &self.buffer)
3518                .is_le()
3519            && self
3520                .range
3521                .context
3522                .end
3523                .cmp(&anchor.text_anchor, &self.buffer)
3524                .is_ge()
3525    }
3526}
3527
3528impl ExcerptId {
3529    pub fn min() -> Self {
3530        Self(0)
3531    }
3532
3533    pub fn max() -> Self {
3534        Self(usize::MAX)
3535    }
3536
3537    pub fn to_proto(&self) -> u64 {
3538        self.0 as _
3539    }
3540
3541    pub fn from_proto(proto: u64) -> Self {
3542        Self(proto as _)
3543    }
3544
3545    pub fn cmp(&self, other: &Self, snapshot: &MultiBufferSnapshot) -> cmp::Ordering {
3546        let a = snapshot.excerpt_locator_for_id(*self);
3547        let b = snapshot.excerpt_locator_for_id(*other);
3548        a.cmp(&b).then_with(|| self.0.cmp(&other.0))
3549    }
3550}
3551
3552impl Into<usize> for ExcerptId {
3553    fn into(self) -> usize {
3554        self.0
3555    }
3556}
3557
3558impl fmt::Debug for Excerpt {
3559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3560        f.debug_struct("Excerpt")
3561            .field("id", &self.id)
3562            .field("locator", &self.locator)
3563            .field("buffer_id", &self.buffer_id)
3564            .field("range", &self.range)
3565            .field("text_summary", &self.text_summary)
3566            .field("has_trailing_newline", &self.has_trailing_newline)
3567            .finish()
3568    }
3569}
3570
3571impl sum_tree::Item for Excerpt {
3572    type Summary = ExcerptSummary;
3573
3574    fn summary(&self) -> Self::Summary {
3575        let mut text = self.text_summary.clone();
3576        if self.has_trailing_newline {
3577            text += TextSummary::from("\n");
3578        }
3579        ExcerptSummary {
3580            excerpt_id: self.id,
3581            excerpt_locator: self.locator.clone(),
3582            max_buffer_row: self.max_buffer_row,
3583            text,
3584        }
3585    }
3586}
3587
3588impl sum_tree::Item for ExcerptIdMapping {
3589    type Summary = ExcerptId;
3590
3591    fn summary(&self) -> Self::Summary {
3592        self.id
3593    }
3594}
3595
3596impl sum_tree::KeyedItem for ExcerptIdMapping {
3597    type Key = ExcerptId;
3598
3599    fn key(&self) -> Self::Key {
3600        self.id
3601    }
3602}
3603
3604impl sum_tree::Summary for ExcerptId {
3605    type Context = ();
3606
3607    fn add_summary(&mut self, other: &Self, _: &()) {
3608        *self = *other;
3609    }
3610}
3611
3612impl sum_tree::Summary for ExcerptSummary {
3613    type Context = ();
3614
3615    fn add_summary(&mut self, summary: &Self, _: &()) {
3616        debug_assert!(summary.excerpt_locator > self.excerpt_locator);
3617        self.excerpt_locator = summary.excerpt_locator.clone();
3618        self.text.add_summary(&summary.text, &());
3619        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
3620    }
3621}
3622
3623impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
3624    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3625        *self += &summary.text;
3626    }
3627}
3628
3629impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
3630    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3631        *self += summary.text.len;
3632    }
3633}
3634
3635impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
3636    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3637        Ord::cmp(self, &cursor_location.text.len)
3638    }
3639}
3640
3641impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, Option<&'a Locator>> for Locator {
3642    fn cmp(&self, cursor_location: &Option<&'a Locator>, _: &()) -> cmp::Ordering {
3643        Ord::cmp(&Some(self), cursor_location)
3644    }
3645}
3646
3647impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Locator {
3648    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
3649        Ord::cmp(self, &cursor_location.excerpt_locator)
3650    }
3651}
3652
3653impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
3654    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3655        *self += summary.text.len_utf16;
3656    }
3657}
3658
3659impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
3660    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3661        *self += summary.text.lines;
3662    }
3663}
3664
3665impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
3666    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3667        *self += summary.text.lines_utf16()
3668    }
3669}
3670
3671impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a Locator> {
3672    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3673        *self = Some(&summary.excerpt_locator);
3674    }
3675}
3676
3677impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<ExcerptId> {
3678    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
3679        *self = Some(summary.excerpt_id);
3680    }
3681}
3682
3683impl<'a> MultiBufferRows<'a> {
3684    pub fn seek(&mut self, row: u32) {
3685        self.buffer_row_range = 0..0;
3686
3687        self.excerpts
3688            .seek_forward(&Point::new(row, 0), Bias::Right, &());
3689        if self.excerpts.item().is_none() {
3690            self.excerpts.prev(&());
3691
3692            if self.excerpts.item().is_none() && row == 0 {
3693                self.buffer_row_range = 0..1;
3694                return;
3695            }
3696        }
3697
3698        if let Some(excerpt) = self.excerpts.item() {
3699            let overshoot = row - self.excerpts.start().row;
3700            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3701            self.buffer_row_range.start = excerpt_start + overshoot;
3702            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3703        }
3704    }
3705}
3706
3707impl<'a> Iterator for MultiBufferRows<'a> {
3708    type Item = Option<u32>;
3709
3710    fn next(&mut self) -> Option<Self::Item> {
3711        loop {
3712            if !self.buffer_row_range.is_empty() {
3713                let row = Some(self.buffer_row_range.start);
3714                self.buffer_row_range.start += 1;
3715                return Some(row);
3716            }
3717            self.excerpts.item()?;
3718            self.excerpts.next(&());
3719            let excerpt = self.excerpts.item()?;
3720            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3721            self.buffer_row_range.end =
3722                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3723        }
3724    }
3725}
3726
3727impl<'a> MultiBufferChunks<'a> {
3728    pub fn offset(&self) -> usize {
3729        self.range.start
3730    }
3731
3732    pub fn seek(&mut self, offset: usize) {
3733        self.range.start = offset;
3734        self.excerpts.seek(&offset, Bias::Right, &());
3735        if let Some(excerpt) = self.excerpts.item() {
3736            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3737                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3738                self.language_aware,
3739            ));
3740        } else {
3741            self.excerpt_chunks = None;
3742        }
3743    }
3744}
3745
3746impl<'a> Iterator for MultiBufferChunks<'a> {
3747    type Item = Chunk<'a>;
3748
3749    fn next(&mut self) -> Option<Self::Item> {
3750        if self.range.is_empty() {
3751            None
3752        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3753            self.range.start += chunk.text.len();
3754            Some(chunk)
3755        } else {
3756            self.excerpts.next(&());
3757            let excerpt = self.excerpts.item()?;
3758            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3759                0..self.range.end - self.excerpts.start(),
3760                self.language_aware,
3761            ));
3762            self.next()
3763        }
3764    }
3765}
3766
3767impl<'a> MultiBufferBytes<'a> {
3768    fn consume(&mut self, len: usize) {
3769        self.range.start += len;
3770        self.chunk = &self.chunk[len..];
3771
3772        if !self.range.is_empty() && self.chunk.is_empty() {
3773            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3774                self.chunk = chunk;
3775            } else {
3776                self.excerpts.next(&());
3777                if let Some(excerpt) = self.excerpts.item() {
3778                    let mut excerpt_bytes =
3779                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3780                    self.chunk = excerpt_bytes.next().unwrap();
3781                    self.excerpt_bytes = Some(excerpt_bytes);
3782                }
3783            }
3784        }
3785    }
3786}
3787
3788impl<'a> Iterator for MultiBufferBytes<'a> {
3789    type Item = &'a [u8];
3790
3791    fn next(&mut self) -> Option<Self::Item> {
3792        let chunk = self.chunk;
3793        if chunk.is_empty() {
3794            None
3795        } else {
3796            self.consume(chunk.len());
3797            Some(chunk)
3798        }
3799    }
3800}
3801
3802impl<'a> io::Read for MultiBufferBytes<'a> {
3803    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3804        let len = cmp::min(buf.len(), self.chunk.len());
3805        buf[..len].copy_from_slice(&self.chunk[..len]);
3806        if len > 0 {
3807            self.consume(len);
3808        }
3809        Ok(len)
3810    }
3811}
3812
3813impl<'a> ReversedMultiBufferBytes<'a> {
3814    fn consume(&mut self, len: usize) {
3815        self.range.end -= len;
3816        self.chunk = &self.chunk[..self.chunk.len() - len];
3817
3818        if !self.range.is_empty() && self.chunk.is_empty() {
3819            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3820                self.chunk = chunk;
3821            } else {
3822                self.excerpts.next(&());
3823                if let Some(excerpt) = self.excerpts.item() {
3824                    let mut excerpt_bytes =
3825                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3826                    self.chunk = excerpt_bytes.next().unwrap();
3827                    self.excerpt_bytes = Some(excerpt_bytes);
3828                }
3829            }
3830        }
3831    }
3832}
3833
3834impl<'a> io::Read for ReversedMultiBufferBytes<'a> {
3835    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3836        let len = cmp::min(buf.len(), self.chunk.len());
3837        buf[..len].copy_from_slice(&self.chunk[..len]);
3838        buf[..len].reverse();
3839        if len > 0 {
3840            self.consume(len);
3841        }
3842        Ok(len)
3843    }
3844}
3845impl<'a> Iterator for ExcerptBytes<'a> {
3846    type Item = &'a [u8];
3847
3848    fn next(&mut self) -> Option<Self::Item> {
3849        if let Some(chunk) = self.content_bytes.next() {
3850            if !chunk.is_empty() {
3851                return Some(chunk);
3852            }
3853        }
3854
3855        if self.footer_height > 0 {
3856            let result = &NEWLINES[..self.footer_height];
3857            self.footer_height = 0;
3858            return Some(result);
3859        }
3860
3861        None
3862    }
3863}
3864
3865impl<'a> Iterator for ExcerptChunks<'a> {
3866    type Item = Chunk<'a>;
3867
3868    fn next(&mut self) -> Option<Self::Item> {
3869        if let Some(chunk) = self.content_chunks.next() {
3870            return Some(chunk);
3871        }
3872
3873        if self.footer_height > 0 {
3874            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3875            self.footer_height = 0;
3876            return Some(Chunk {
3877                text,
3878                ..Default::default()
3879            });
3880        }
3881
3882        None
3883    }
3884}
3885
3886impl ToOffset for Point {
3887    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3888        snapshot.point_to_offset(*self)
3889    }
3890}
3891
3892impl ToOffset for usize {
3893    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3894        assert!(*self <= snapshot.len(), "offset is out of range");
3895        *self
3896    }
3897}
3898
3899impl ToOffset for OffsetUtf16 {
3900    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3901        snapshot.offset_utf16_to_offset(*self)
3902    }
3903}
3904
3905impl ToOffset for PointUtf16 {
3906    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3907        snapshot.point_utf16_to_offset(*self)
3908    }
3909}
3910
3911impl ToOffsetUtf16 for OffsetUtf16 {
3912    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3913        *self
3914    }
3915}
3916
3917impl ToOffsetUtf16 for usize {
3918    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3919        snapshot.offset_to_offset_utf16(*self)
3920    }
3921}
3922
3923impl ToPoint for usize {
3924    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3925        snapshot.offset_to_point(*self)
3926    }
3927}
3928
3929impl ToPoint for Point {
3930    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3931        *self
3932    }
3933}
3934
3935impl ToPointUtf16 for usize {
3936    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3937        snapshot.offset_to_point_utf16(*self)
3938    }
3939}
3940
3941impl ToPointUtf16 for Point {
3942    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3943        snapshot.point_to_point_utf16(*self)
3944    }
3945}
3946
3947impl ToPointUtf16 for PointUtf16 {
3948    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3949        *self
3950    }
3951}
3952
3953fn build_excerpt_ranges<T>(
3954    buffer: &BufferSnapshot,
3955    ranges: &[Range<T>],
3956    context_line_count: u32,
3957) -> (Vec<ExcerptRange<Point>>, Vec<usize>)
3958where
3959    T: text::ToPoint,
3960{
3961    let max_point = buffer.max_point();
3962    let mut range_counts = Vec::new();
3963    let mut excerpt_ranges = Vec::new();
3964    let mut range_iter = ranges
3965        .iter()
3966        .map(|range| range.start.to_point(buffer)..range.end.to_point(buffer))
3967        .peekable();
3968    while let Some(range) = range_iter.next() {
3969        let excerpt_start = Point::new(range.start.row.saturating_sub(context_line_count), 0);
3970        let mut excerpt_end = Point::new(range.end.row + 1 + context_line_count, 0).min(max_point);
3971        let mut ranges_in_excerpt = 1;
3972
3973        while let Some(next_range) = range_iter.peek() {
3974            if next_range.start.row <= excerpt_end.row + context_line_count {
3975                excerpt_end =
3976                    Point::new(next_range.end.row + 1 + context_line_count, 0).min(max_point);
3977                ranges_in_excerpt += 1;
3978                range_iter.next();
3979            } else {
3980                break;
3981            }
3982        }
3983
3984        excerpt_ranges.push(ExcerptRange {
3985            context: excerpt_start..excerpt_end,
3986            primary: Some(range),
3987        });
3988        range_counts.push(ranges_in_excerpt);
3989    }
3990
3991    (excerpt_ranges, range_counts)
3992}
3993
3994#[cfg(test)]
3995mod tests {
3996    use crate::editor_tests::init_test;
3997
3998    use super::*;
3999    use futures::StreamExt;
4000    use gpui::{AppContext, TestAppContext};
4001    use language::{Buffer, Rope};
4002    use project::{FakeFs, Project};
4003    use rand::prelude::*;
4004    use settings::SettingsStore;
4005    use std::{env, rc::Rc};
4006    use unindent::Unindent;
4007    use util::test::sample_text;
4008
4009    #[gpui::test]
4010    fn test_singleton(cx: &mut AppContext) {
4011        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4012        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4013
4014        let snapshot = multibuffer.read(cx).snapshot(cx);
4015        assert_eq!(snapshot.text(), buffer.read(cx).text());
4016
4017        assert_eq!(
4018            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4019            (0..buffer.read(cx).row_count())
4020                .map(Some)
4021                .collect::<Vec<_>>()
4022        );
4023
4024        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
4025        let snapshot = multibuffer.read(cx).snapshot(cx);
4026
4027        assert_eq!(snapshot.text(), buffer.read(cx).text());
4028        assert_eq!(
4029            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4030            (0..buffer.read(cx).row_count())
4031                .map(Some)
4032                .collect::<Vec<_>>()
4033        );
4034    }
4035
4036    #[gpui::test]
4037    fn test_remote(cx: &mut AppContext) {
4038        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
4039        let guest_buffer = cx.add_model(|cx| {
4040            let state = host_buffer.read(cx).to_proto();
4041            let ops = cx
4042                .background()
4043                .block(host_buffer.read(cx).serialize_ops(None, cx));
4044            let mut buffer = Buffer::from_proto(1, state, None).unwrap();
4045            buffer
4046                .apply_ops(
4047                    ops.into_iter()
4048                        .map(|op| language::proto::deserialize_operation(op).unwrap()),
4049                    cx,
4050                )
4051                .unwrap();
4052            buffer
4053        });
4054        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
4055        let snapshot = multibuffer.read(cx).snapshot(cx);
4056        assert_eq!(snapshot.text(), "a");
4057
4058        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
4059        let snapshot = multibuffer.read(cx).snapshot(cx);
4060        assert_eq!(snapshot.text(), "ab");
4061
4062        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
4063        let snapshot = multibuffer.read(cx).snapshot(cx);
4064        assert_eq!(snapshot.text(), "abc");
4065    }
4066
4067    #[gpui::test]
4068    fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
4069        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
4070        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
4071        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4072
4073        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
4074        multibuffer.update(cx, |_, cx| {
4075            let events = events.clone();
4076            cx.subscribe(&multibuffer, move |_, _, event, _| {
4077                if let Event::Edited = event {
4078                    events.borrow_mut().push(event.clone())
4079                }
4080            })
4081            .detach();
4082        });
4083
4084        let subscription = multibuffer.update(cx, |multibuffer, cx| {
4085            let subscription = multibuffer.subscribe();
4086            multibuffer.push_excerpts(
4087                buffer_1.clone(),
4088                [ExcerptRange {
4089                    context: Point::new(1, 2)..Point::new(2, 5),
4090                    primary: None,
4091                }],
4092                cx,
4093            );
4094            assert_eq!(
4095                subscription.consume().into_inner(),
4096                [Edit {
4097                    old: 0..0,
4098                    new: 0..10
4099                }]
4100            );
4101
4102            multibuffer.push_excerpts(
4103                buffer_1.clone(),
4104                [ExcerptRange {
4105                    context: Point::new(3, 3)..Point::new(4, 4),
4106                    primary: None,
4107                }],
4108                cx,
4109            );
4110            multibuffer.push_excerpts(
4111                buffer_2.clone(),
4112                [ExcerptRange {
4113                    context: Point::new(3, 1)..Point::new(3, 3),
4114                    primary: None,
4115                }],
4116                cx,
4117            );
4118            assert_eq!(
4119                subscription.consume().into_inner(),
4120                [Edit {
4121                    old: 10..10,
4122                    new: 10..22
4123                }]
4124            );
4125
4126            subscription
4127        });
4128
4129        // Adding excerpts emits an edited event.
4130        assert_eq!(
4131            events.borrow().as_slice(),
4132            &[Event::Edited, Event::Edited, Event::Edited]
4133        );
4134
4135        let snapshot = multibuffer.read(cx).snapshot(cx);
4136        assert_eq!(
4137            snapshot.text(),
4138            concat!(
4139                "bbbb\n",  // Preserve newlines
4140                "ccccc\n", //
4141                "ddd\n",   //
4142                "eeee\n",  //
4143                "jj"       //
4144            )
4145        );
4146        assert_eq!(
4147            snapshot.buffer_rows(0).collect::<Vec<_>>(),
4148            [Some(1), Some(2), Some(3), Some(4), Some(3)]
4149        );
4150        assert_eq!(
4151            snapshot.buffer_rows(2).collect::<Vec<_>>(),
4152            [Some(3), Some(4), Some(3)]
4153        );
4154        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
4155        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
4156
4157        assert_eq!(
4158            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
4159            &[
4160                (0, "bbbb\nccccc".to_string(), true),
4161                (2, "ddd\neeee".to_string(), false),
4162                (4, "jj".to_string(), true),
4163            ]
4164        );
4165        assert_eq!(
4166            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
4167            &[(0, "bbbb\nccccc".to_string(), true)]
4168        );
4169        assert_eq!(
4170            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
4171            &[]
4172        );
4173        assert_eq!(
4174            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
4175            &[]
4176        );
4177        assert_eq!(
4178            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4179            &[(2, "ddd\neeee".to_string(), false)]
4180        );
4181        assert_eq!(
4182            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
4183            &[(2, "ddd\neeee".to_string(), false)]
4184        );
4185        assert_eq!(
4186            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
4187            &[(2, "ddd\neeee".to_string(), false)]
4188        );
4189        assert_eq!(
4190            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
4191            &[(4, "jj".to_string(), true)]
4192        );
4193        assert_eq!(
4194            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
4195            &[]
4196        );
4197
4198        buffer_1.update(cx, |buffer, cx| {
4199            let text = "\n";
4200            buffer.edit(
4201                [
4202                    (Point::new(0, 0)..Point::new(0, 0), text),
4203                    (Point::new(2, 1)..Point::new(2, 3), text),
4204                ],
4205                None,
4206                cx,
4207            );
4208        });
4209
4210        let snapshot = multibuffer.read(cx).snapshot(cx);
4211        assert_eq!(
4212            snapshot.text(),
4213            concat!(
4214                "bbbb\n", // Preserve newlines
4215                "c\n",    //
4216                "cc\n",   //
4217                "ddd\n",  //
4218                "eeee\n", //
4219                "jj"      //
4220            )
4221        );
4222
4223        assert_eq!(
4224            subscription.consume().into_inner(),
4225            [Edit {
4226                old: 6..8,
4227                new: 6..7
4228            }]
4229        );
4230
4231        let snapshot = multibuffer.read(cx).snapshot(cx);
4232        assert_eq!(
4233            snapshot.clip_point(Point::new(0, 5), Bias::Left),
4234            Point::new(0, 4)
4235        );
4236        assert_eq!(
4237            snapshot.clip_point(Point::new(0, 5), Bias::Right),
4238            Point::new(0, 4)
4239        );
4240        assert_eq!(
4241            snapshot.clip_point(Point::new(5, 1), Bias::Right),
4242            Point::new(5, 1)
4243        );
4244        assert_eq!(
4245            snapshot.clip_point(Point::new(5, 2), Bias::Right),
4246            Point::new(5, 2)
4247        );
4248        assert_eq!(
4249            snapshot.clip_point(Point::new(5, 3), Bias::Right),
4250            Point::new(5, 2)
4251        );
4252
4253        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
4254            let (buffer_2_excerpt_id, _) =
4255                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
4256            multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
4257            multibuffer.snapshot(cx)
4258        });
4259
4260        assert_eq!(
4261            snapshot.text(),
4262            concat!(
4263                "bbbb\n", // Preserve newlines
4264                "c\n",    //
4265                "cc\n",   //
4266                "ddd\n",  //
4267                "eeee",   //
4268            )
4269        );
4270
4271        fn boundaries_in_range(
4272            range: Range<Point>,
4273            snapshot: &MultiBufferSnapshot,
4274        ) -> Vec<(u32, String, bool)> {
4275            snapshot
4276                .excerpt_boundaries_in_range(range)
4277                .map(|boundary| {
4278                    (
4279                        boundary.row,
4280                        boundary
4281                            .buffer
4282                            .text_for_range(boundary.range.context)
4283                            .collect::<String>(),
4284                        boundary.starts_new_buffer,
4285                    )
4286                })
4287                .collect::<Vec<_>>()
4288        }
4289    }
4290
4291    #[gpui::test]
4292    fn test_excerpt_events(cx: &mut AppContext) {
4293        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'a'), cx));
4294        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(10, 3, 'm'), cx));
4295
4296        let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4297        let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4298        let follower_edit_event_count = Rc::new(RefCell::new(0));
4299
4300        follower_multibuffer.update(cx, |_, cx| {
4301            let follower_edit_event_count = follower_edit_event_count.clone();
4302            cx.subscribe(
4303                &leader_multibuffer,
4304                move |follower, _, event, cx| match event.clone() {
4305                    Event::ExcerptsAdded {
4306                        buffer,
4307                        predecessor,
4308                        excerpts,
4309                    } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
4310                    Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
4311                    Event::Edited => {
4312                        *follower_edit_event_count.borrow_mut() += 1;
4313                    }
4314                    _ => {}
4315                },
4316            )
4317            .detach();
4318        });
4319
4320        leader_multibuffer.update(cx, |leader, cx| {
4321            leader.push_excerpts(
4322                buffer_1.clone(),
4323                [
4324                    ExcerptRange {
4325                        context: 0..8,
4326                        primary: None,
4327                    },
4328                    ExcerptRange {
4329                        context: 12..16,
4330                        primary: None,
4331                    },
4332                ],
4333                cx,
4334            );
4335            leader.insert_excerpts_after(
4336                leader.excerpt_ids()[0],
4337                buffer_2.clone(),
4338                [
4339                    ExcerptRange {
4340                        context: 0..5,
4341                        primary: None,
4342                    },
4343                    ExcerptRange {
4344                        context: 10..15,
4345                        primary: None,
4346                    },
4347                ],
4348                cx,
4349            )
4350        });
4351        assert_eq!(
4352            leader_multibuffer.read(cx).snapshot(cx).text(),
4353            follower_multibuffer.read(cx).snapshot(cx).text(),
4354        );
4355        assert_eq!(*follower_edit_event_count.borrow(), 2);
4356
4357        leader_multibuffer.update(cx, |leader, cx| {
4358            let excerpt_ids = leader.excerpt_ids();
4359            leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
4360        });
4361        assert_eq!(
4362            leader_multibuffer.read(cx).snapshot(cx).text(),
4363            follower_multibuffer.read(cx).snapshot(cx).text(),
4364        );
4365        assert_eq!(*follower_edit_event_count.borrow(), 3);
4366
4367        // Removing an empty set of excerpts is a noop.
4368        leader_multibuffer.update(cx, |leader, cx| {
4369            leader.remove_excerpts([], 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(), 3);
4376
4377        // Adding an empty set of excerpts is a noop.
4378        leader_multibuffer.update(cx, |leader, cx| {
4379            leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
4380        });
4381        assert_eq!(
4382            leader_multibuffer.read(cx).snapshot(cx).text(),
4383            follower_multibuffer.read(cx).snapshot(cx).text(),
4384        );
4385        assert_eq!(*follower_edit_event_count.borrow(), 3);
4386
4387        leader_multibuffer.update(cx, |leader, cx| {
4388            leader.clear(cx);
4389        });
4390        assert_eq!(
4391            leader_multibuffer.read(cx).snapshot(cx).text(),
4392            follower_multibuffer.read(cx).snapshot(cx).text(),
4393        );
4394        assert_eq!(*follower_edit_event_count.borrow(), 4);
4395    }
4396
4397    #[gpui::test]
4398    fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
4399        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4400        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4401        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
4402            multibuffer.push_excerpts_with_context_lines(
4403                buffer.clone(),
4404                vec![
4405                    Point::new(3, 2)..Point::new(4, 2),
4406                    Point::new(7, 1)..Point::new(7, 3),
4407                    Point::new(15, 0)..Point::new(15, 0),
4408                ],
4409                2,
4410                cx,
4411            )
4412        });
4413
4414        let snapshot = multibuffer.read(cx).snapshot(cx);
4415        assert_eq!(
4416            snapshot.text(),
4417            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4418        );
4419
4420        assert_eq!(
4421            anchor_ranges
4422                .iter()
4423                .map(|range| range.to_point(&snapshot))
4424                .collect::<Vec<_>>(),
4425            vec![
4426                Point::new(2, 2)..Point::new(3, 2),
4427                Point::new(6, 1)..Point::new(6, 3),
4428                Point::new(12, 0)..Point::new(12, 0)
4429            ]
4430        );
4431    }
4432
4433    #[gpui::test]
4434    async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
4435        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
4436        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4437        let (task, anchor_ranges) = multibuffer.update(cx, |multibuffer, cx| {
4438            let snapshot = buffer.read(cx);
4439            let ranges = vec![
4440                snapshot.anchor_before(Point::new(3, 2))..snapshot.anchor_before(Point::new(4, 2)),
4441                snapshot.anchor_before(Point::new(7, 1))..snapshot.anchor_before(Point::new(7, 3)),
4442                snapshot.anchor_before(Point::new(15, 0))
4443                    ..snapshot.anchor_before(Point::new(15, 0)),
4444            ];
4445            multibuffer.stream_excerpts_with_context_lines(vec![(buffer.clone(), ranges)], 2, cx)
4446        });
4447
4448        let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
4449        // Ensure task is finished when stream completes.
4450        task.await;
4451
4452        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4453        assert_eq!(
4454            snapshot.text(),
4455            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
4456        );
4457
4458        assert_eq!(
4459            anchor_ranges
4460                .iter()
4461                .map(|range| range.to_point(&snapshot))
4462                .collect::<Vec<_>>(),
4463            vec![
4464                Point::new(2, 2)..Point::new(3, 2),
4465                Point::new(6, 1)..Point::new(6, 3),
4466                Point::new(12, 0)..Point::new(12, 0)
4467            ]
4468        );
4469    }
4470
4471    #[gpui::test]
4472    fn test_empty_multibuffer(cx: &mut AppContext) {
4473        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4474
4475        let snapshot = multibuffer.read(cx).snapshot(cx);
4476        assert_eq!(snapshot.text(), "");
4477        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
4478        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
4479    }
4480
4481    #[gpui::test]
4482    fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
4483        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4484        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4485        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4486        buffer.update(cx, |buffer, cx| {
4487            buffer.edit([(0..0, "X")], None, cx);
4488            buffer.edit([(5..5, "Y")], None, cx);
4489        });
4490        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4491
4492        assert_eq!(old_snapshot.text(), "abcd");
4493        assert_eq!(new_snapshot.text(), "XabcdY");
4494
4495        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4496        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4497        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
4498        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
4499    }
4500
4501    #[gpui::test]
4502    fn test_multibuffer_anchors(cx: &mut AppContext) {
4503        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4504        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
4505        let multibuffer = cx.add_model(|cx| {
4506            let mut multibuffer = MultiBuffer::new(0);
4507            multibuffer.push_excerpts(
4508                buffer_1.clone(),
4509                [ExcerptRange {
4510                    context: 0..4,
4511                    primary: None,
4512                }],
4513                cx,
4514            );
4515            multibuffer.push_excerpts(
4516                buffer_2.clone(),
4517                [ExcerptRange {
4518                    context: 0..5,
4519                    primary: None,
4520                }],
4521                cx,
4522            );
4523            multibuffer
4524        });
4525        let old_snapshot = multibuffer.read(cx).snapshot(cx);
4526
4527        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
4528        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
4529        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4530        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
4531        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4532        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
4533
4534        buffer_1.update(cx, |buffer, cx| {
4535            buffer.edit([(0..0, "W")], None, cx);
4536            buffer.edit([(5..5, "X")], None, cx);
4537        });
4538        buffer_2.update(cx, |buffer, cx| {
4539            buffer.edit([(0..0, "Y")], None, cx);
4540            buffer.edit([(6..6, "Z")], None, cx);
4541        });
4542        let new_snapshot = multibuffer.read(cx).snapshot(cx);
4543
4544        assert_eq!(old_snapshot.text(), "abcd\nefghi");
4545        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
4546
4547        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
4548        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
4549        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
4550        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
4551        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
4552        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
4553        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
4554        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
4555        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
4556        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
4557    }
4558
4559    #[gpui::test]
4560    fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
4561        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
4562        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
4563        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4564
4565        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
4566        // Add an excerpt from buffer 1 that spans this new insertion.
4567        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
4568        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
4569            multibuffer
4570                .push_excerpts(
4571                    buffer_1.clone(),
4572                    [ExcerptRange {
4573                        context: 0..7,
4574                        primary: None,
4575                    }],
4576                    cx,
4577                )
4578                .pop()
4579                .unwrap()
4580        });
4581
4582        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
4583        assert_eq!(snapshot_1.text(), "abcd123");
4584
4585        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
4586        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
4587            multibuffer.remove_excerpts([excerpt_id_1], cx);
4588            let mut ids = multibuffer
4589                .push_excerpts(
4590                    buffer_2.clone(),
4591                    [
4592                        ExcerptRange {
4593                            context: 0..4,
4594                            primary: None,
4595                        },
4596                        ExcerptRange {
4597                            context: 6..10,
4598                            primary: None,
4599                        },
4600                        ExcerptRange {
4601                            context: 12..16,
4602                            primary: None,
4603                        },
4604                    ],
4605                    cx,
4606                )
4607                .into_iter();
4608            (ids.next().unwrap(), ids.next().unwrap())
4609        });
4610        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
4611        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
4612
4613        // The old excerpt id doesn't get reused.
4614        assert_ne!(excerpt_id_2, excerpt_id_1);
4615
4616        // Resolve some anchors from the previous snapshot in the new snapshot.
4617        // The current excerpts are from a different buffer, so we don't attempt to
4618        // resolve the old text anchor in the new buffer.
4619        assert_eq!(
4620            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
4621            0
4622        );
4623        assert_eq!(
4624            snapshot_2.summaries_for_anchors::<usize, _>(&[
4625                snapshot_1.anchor_before(2),
4626                snapshot_1.anchor_after(3)
4627            ]),
4628            vec![0, 0]
4629        );
4630
4631        // Refresh anchors from the old snapshot. The return value indicates that both
4632        // anchors lost their original excerpt.
4633        let refresh =
4634            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
4635        assert_eq!(
4636            refresh,
4637            &[
4638                (0, snapshot_2.anchor_before(0), false),
4639                (1, snapshot_2.anchor_after(0), false),
4640            ]
4641        );
4642
4643        // Replace the middle excerpt with a smaller excerpt in buffer 2,
4644        // that intersects the old excerpt.
4645        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
4646            multibuffer.remove_excerpts([excerpt_id_3], cx);
4647            multibuffer
4648                .insert_excerpts_after(
4649                    excerpt_id_2,
4650                    buffer_2.clone(),
4651                    [ExcerptRange {
4652                        context: 5..8,
4653                        primary: None,
4654                    }],
4655                    cx,
4656                )
4657                .pop()
4658                .unwrap()
4659        });
4660
4661        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
4662        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
4663        assert_ne!(excerpt_id_5, excerpt_id_3);
4664
4665        // Resolve some anchors from the previous snapshot in the new snapshot.
4666        // The third anchor can't be resolved, since its excerpt has been removed,
4667        // so it resolves to the same position as its predecessor.
4668        let anchors = [
4669            snapshot_2.anchor_before(0),
4670            snapshot_2.anchor_after(2),
4671            snapshot_2.anchor_after(6),
4672            snapshot_2.anchor_after(14),
4673        ];
4674        assert_eq!(
4675            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
4676            &[0, 2, 9, 13]
4677        );
4678
4679        let new_anchors = snapshot_3.refresh_anchors(&anchors);
4680        assert_eq!(
4681            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
4682            &[(0, true), (1, true), (2, true), (3, true)]
4683        );
4684        assert_eq!(
4685            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
4686            &[0, 2, 7, 13]
4687        );
4688    }
4689
4690    #[gpui::test]
4691    async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
4692        use git::diff::DiffHunkStatus;
4693        init_test(cx, |_| {});
4694
4695        let fs = FakeFs::new(cx.background());
4696        let project = Project::test(fs, [], cx).await;
4697
4698        // buffer has two modified hunks with two rows each
4699        let buffer_1 = project
4700            .update(cx, |project, cx| {
4701                project.create_buffer(
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                    .as_str(),
4713                    None,
4714                    cx,
4715                )
4716            })
4717            .unwrap();
4718        buffer_1.update(cx, |buffer, cx| {
4719            buffer.set_diff_base(
4720                Some(
4721                    "
4722                        1.zero
4723                        1.one
4724                        1.two
4725                        1.three
4726                        1.four
4727                        1.five
4728                        1.six
4729                    "
4730                    .unindent(),
4731                ),
4732                cx,
4733            );
4734        });
4735
4736        // buffer has a deletion hunk and an insertion hunk
4737        let buffer_2 = project
4738            .update(cx, |project, cx| {
4739                project.create_buffer(
4740                    "
4741                        2.zero
4742                        2.one
4743                        2.two
4744                        2.three
4745                        2.four
4746                        2.five
4747                        2.six
4748                    "
4749                    .unindent()
4750                    .as_str(),
4751                    None,
4752                    cx,
4753                )
4754            })
4755            .unwrap();
4756        buffer_2.update(cx, |buffer, cx| {
4757            buffer.set_diff_base(
4758                Some(
4759                    "
4760                        2.zero
4761                        2.one
4762                        2.one-and-a-half
4763                        2.two
4764                        2.three
4765                        2.four
4766                        2.six
4767                    "
4768                    .unindent(),
4769                ),
4770                cx,
4771            );
4772        });
4773
4774        cx.foreground().run_until_parked();
4775
4776        let multibuffer = cx.add_model(|cx| {
4777            let mut multibuffer = MultiBuffer::new(0);
4778            multibuffer.push_excerpts(
4779                buffer_1.clone(),
4780                [
4781                    // excerpt ends in the middle of a modified hunk
4782                    ExcerptRange {
4783                        context: Point::new(0, 0)..Point::new(1, 5),
4784                        primary: Default::default(),
4785                    },
4786                    // excerpt begins in the middle of a modified hunk
4787                    ExcerptRange {
4788                        context: Point::new(5, 0)..Point::new(6, 5),
4789                        primary: Default::default(),
4790                    },
4791                ],
4792                cx,
4793            );
4794            multibuffer.push_excerpts(
4795                buffer_2.clone(),
4796                [
4797                    // excerpt ends at a deletion
4798                    ExcerptRange {
4799                        context: Point::new(0, 0)..Point::new(1, 5),
4800                        primary: Default::default(),
4801                    },
4802                    // excerpt starts at a deletion
4803                    ExcerptRange {
4804                        context: Point::new(2, 0)..Point::new(2, 5),
4805                        primary: Default::default(),
4806                    },
4807                    // excerpt fully contains a deletion hunk
4808                    ExcerptRange {
4809                        context: Point::new(1, 0)..Point::new(2, 5),
4810                        primary: Default::default(),
4811                    },
4812                    // excerpt fully contains an insertion hunk
4813                    ExcerptRange {
4814                        context: Point::new(4, 0)..Point::new(6, 5),
4815                        primary: Default::default(),
4816                    },
4817                ],
4818                cx,
4819            );
4820            multibuffer
4821        });
4822
4823        let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
4824
4825        assert_eq!(
4826            snapshot.text(),
4827            "
4828                1.zero
4829                1.ONE
4830                1.FIVE
4831                1.six
4832                2.zero
4833                2.one
4834                2.two
4835                2.one
4836                2.two
4837                2.four
4838                2.five
4839                2.six"
4840                .unindent()
4841        );
4842
4843        let expected = [
4844            (DiffHunkStatus::Modified, 1..2),
4845            (DiffHunkStatus::Modified, 2..3),
4846            //TODO: Define better when and where removed hunks show up at range extremities
4847            (DiffHunkStatus::Removed, 6..6),
4848            (DiffHunkStatus::Removed, 8..8),
4849            (DiffHunkStatus::Added, 10..11),
4850        ];
4851
4852        assert_eq!(
4853            snapshot
4854                .git_diff_hunks_in_range(0..12)
4855                .map(|hunk| (hunk.status(), hunk.buffer_range))
4856                .collect::<Vec<_>>(),
4857            &expected,
4858        );
4859
4860        assert_eq!(
4861            snapshot
4862                .git_diff_hunks_in_range_rev(0..12)
4863                .map(|hunk| (hunk.status(), hunk.buffer_range))
4864                .collect::<Vec<_>>(),
4865            expected
4866                .iter()
4867                .rev()
4868                .cloned()
4869                .collect::<Vec<_>>()
4870                .as_slice(),
4871        );
4872    }
4873
4874    #[gpui::test(iterations = 100)]
4875    fn test_random_multibuffer(cx: &mut AppContext, mut rng: StdRng) {
4876        let operations = env::var("OPERATIONS")
4877            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4878            .unwrap_or(10);
4879
4880        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
4881        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4882        let mut excerpt_ids = Vec::<ExcerptId>::new();
4883        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
4884        let mut anchors = Vec::new();
4885        let mut old_versions = Vec::new();
4886
4887        for _ in 0..operations {
4888            match rng.gen_range(0..100) {
4889                0..=19 if !buffers.is_empty() => {
4890                    let buffer = buffers.choose(&mut rng).unwrap();
4891                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
4892                }
4893                20..=29 if !expected_excerpts.is_empty() => {
4894                    let mut ids_to_remove = vec![];
4895                    for _ in 0..rng.gen_range(1..=3) {
4896                        if expected_excerpts.is_empty() {
4897                            break;
4898                        }
4899
4900                        let ix = rng.gen_range(0..expected_excerpts.len());
4901                        ids_to_remove.push(excerpt_ids.remove(ix));
4902                        let (buffer, range) = expected_excerpts.remove(ix);
4903                        let buffer = buffer.read(cx);
4904                        log::info!(
4905                            "Removing excerpt {}: {:?}",
4906                            ix,
4907                            buffer
4908                                .text_for_range(range.to_offset(buffer))
4909                                .collect::<String>(),
4910                        );
4911                    }
4912                    let snapshot = multibuffer.read(cx).read(cx);
4913                    ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
4914                    drop(snapshot);
4915                    multibuffer.update(cx, |multibuffer, cx| {
4916                        multibuffer.remove_excerpts(ids_to_remove, cx)
4917                    });
4918                }
4919                30..=39 if !expected_excerpts.is_empty() => {
4920                    let multibuffer = multibuffer.read(cx).read(cx);
4921                    let offset =
4922                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
4923                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
4924                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
4925                    anchors.push(multibuffer.anchor_at(offset, bias));
4926                    anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
4927                }
4928                40..=44 if !anchors.is_empty() => {
4929                    let multibuffer = multibuffer.read(cx).read(cx);
4930                    let prev_len = anchors.len();
4931                    anchors = multibuffer
4932                        .refresh_anchors(&anchors)
4933                        .into_iter()
4934                        .map(|a| a.1)
4935                        .collect();
4936
4937                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
4938                    // overshoot its boundaries.
4939                    assert_eq!(anchors.len(), prev_len);
4940                    for anchor in &anchors {
4941                        if anchor.excerpt_id == ExcerptId::min()
4942                            || anchor.excerpt_id == ExcerptId::max()
4943                        {
4944                            continue;
4945                        }
4946
4947                        let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
4948                        assert_eq!(excerpt.id, anchor.excerpt_id);
4949                        assert!(excerpt.contains(anchor));
4950                    }
4951                }
4952                _ => {
4953                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
4954                        let base_text = util::RandomCharIter::new(&mut rng)
4955                            .take(10)
4956                            .collect::<String>();
4957                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
4958                        buffers.last().unwrap()
4959                    } else {
4960                        buffers.choose(&mut rng).unwrap()
4961                    };
4962
4963                    let buffer = buffer_handle.read(cx);
4964                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
4965                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4966                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
4967                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
4968                    let prev_excerpt_id = excerpt_ids
4969                        .get(prev_excerpt_ix)
4970                        .cloned()
4971                        .unwrap_or_else(ExcerptId::max);
4972                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
4973
4974                    log::info!(
4975                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
4976                        excerpt_ix,
4977                        expected_excerpts.len(),
4978                        buffer_handle.read(cx).remote_id(),
4979                        buffer.text(),
4980                        start_ix..end_ix,
4981                        &buffer.text()[start_ix..end_ix]
4982                    );
4983
4984                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
4985                        multibuffer
4986                            .insert_excerpts_after(
4987                                prev_excerpt_id,
4988                                buffer_handle.clone(),
4989                                [ExcerptRange {
4990                                    context: start_ix..end_ix,
4991                                    primary: None,
4992                                }],
4993                                cx,
4994                            )
4995                            .pop()
4996                            .unwrap()
4997                    });
4998
4999                    excerpt_ids.insert(excerpt_ix, excerpt_id);
5000                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
5001                }
5002            }
5003
5004            if rng.gen_bool(0.3) {
5005                multibuffer.update(cx, |multibuffer, cx| {
5006                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
5007                })
5008            }
5009
5010            let snapshot = multibuffer.read(cx).snapshot(cx);
5011
5012            let mut excerpt_starts = Vec::new();
5013            let mut expected_text = String::new();
5014            let mut expected_buffer_rows = Vec::new();
5015            for (buffer, range) in &expected_excerpts {
5016                let buffer = buffer.read(cx);
5017                let buffer_range = range.to_offset(buffer);
5018
5019                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
5020                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
5021                expected_text.push('\n');
5022
5023                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
5024                    ..=buffer.offset_to_point(buffer_range.end).row;
5025                for row in buffer_row_range {
5026                    expected_buffer_rows.push(Some(row));
5027                }
5028            }
5029            // Remove final trailing newline.
5030            if !expected_excerpts.is_empty() {
5031                expected_text.pop();
5032            }
5033
5034            // Always report one buffer row
5035            if expected_buffer_rows.is_empty() {
5036                expected_buffer_rows.push(Some(0));
5037            }
5038
5039            assert_eq!(snapshot.text(), expected_text);
5040            log::info!("MultiBuffer text: {:?}", expected_text);
5041
5042            assert_eq!(
5043                snapshot.buffer_rows(0).collect::<Vec<_>>(),
5044                expected_buffer_rows,
5045            );
5046
5047            for _ in 0..5 {
5048                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
5049                assert_eq!(
5050                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
5051                    &expected_buffer_rows[start_row..],
5052                    "buffer_rows({})",
5053                    start_row
5054                );
5055            }
5056
5057            assert_eq!(
5058                snapshot.max_buffer_row(),
5059                expected_buffer_rows.into_iter().flatten().max().unwrap()
5060            );
5061
5062            let mut excerpt_starts = excerpt_starts.into_iter();
5063            for (buffer, range) in &expected_excerpts {
5064                let buffer = buffer.read(cx);
5065                let buffer_id = buffer.remote_id();
5066                let buffer_range = range.to_offset(buffer);
5067                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
5068                let buffer_start_point_utf16 =
5069                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
5070
5071                let excerpt_start = excerpt_starts.next().unwrap();
5072                let mut offset = excerpt_start.len;
5073                let mut buffer_offset = buffer_range.start;
5074                let mut point = excerpt_start.lines;
5075                let mut buffer_point = buffer_start_point;
5076                let mut point_utf16 = excerpt_start.lines_utf16();
5077                let mut buffer_point_utf16 = buffer_start_point_utf16;
5078                for ch in buffer
5079                    .snapshot()
5080                    .chunks(buffer_range.clone(), false)
5081                    .flat_map(|c| c.text.chars())
5082                {
5083                    for _ in 0..ch.len_utf8() {
5084                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
5085                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
5086                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
5087                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
5088                        assert_eq!(
5089                            left_offset,
5090                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
5091                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
5092                            offset,
5093                            buffer_id,
5094                            buffer_offset,
5095                        );
5096                        assert_eq!(
5097                            right_offset,
5098                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
5099                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
5100                            offset,
5101                            buffer_id,
5102                            buffer_offset,
5103                        );
5104
5105                        let left_point = snapshot.clip_point(point, Bias::Left);
5106                        let right_point = snapshot.clip_point(point, Bias::Right);
5107                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
5108                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
5109                        assert_eq!(
5110                            left_point,
5111                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
5112                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
5113                            point,
5114                            buffer_id,
5115                            buffer_point,
5116                        );
5117                        assert_eq!(
5118                            right_point,
5119                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
5120                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
5121                            point,
5122                            buffer_id,
5123                            buffer_point,
5124                        );
5125
5126                        assert_eq!(
5127                            snapshot.point_to_offset(left_point),
5128                            left_offset,
5129                            "point_to_offset({:?})",
5130                            left_point,
5131                        );
5132                        assert_eq!(
5133                            snapshot.offset_to_point(left_offset),
5134                            left_point,
5135                            "offset_to_point({:?})",
5136                            left_offset,
5137                        );
5138
5139                        offset += 1;
5140                        buffer_offset += 1;
5141                        if ch == '\n' {
5142                            point += Point::new(1, 0);
5143                            buffer_point += Point::new(1, 0);
5144                        } else {
5145                            point += Point::new(0, 1);
5146                            buffer_point += Point::new(0, 1);
5147                        }
5148                    }
5149
5150                    for _ in 0..ch.len_utf16() {
5151                        let left_point_utf16 =
5152                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Left);
5153                        let right_point_utf16 =
5154                            snapshot.clip_point_utf16(Unclipped(point_utf16), Bias::Right);
5155                        let buffer_left_point_utf16 =
5156                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Left);
5157                        let buffer_right_point_utf16 =
5158                            buffer.clip_point_utf16(Unclipped(buffer_point_utf16), Bias::Right);
5159                        assert_eq!(
5160                            left_point_utf16,
5161                            excerpt_start.lines_utf16()
5162                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
5163                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
5164                            point_utf16,
5165                            buffer_id,
5166                            buffer_point_utf16,
5167                        );
5168                        assert_eq!(
5169                            right_point_utf16,
5170                            excerpt_start.lines_utf16()
5171                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
5172                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
5173                            point_utf16,
5174                            buffer_id,
5175                            buffer_point_utf16,
5176                        );
5177
5178                        if ch == '\n' {
5179                            point_utf16 += PointUtf16::new(1, 0);
5180                            buffer_point_utf16 += PointUtf16::new(1, 0);
5181                        } else {
5182                            point_utf16 += PointUtf16::new(0, 1);
5183                            buffer_point_utf16 += PointUtf16::new(0, 1);
5184                        }
5185                    }
5186                }
5187            }
5188
5189            for (row, line) in expected_text.split('\n').enumerate() {
5190                assert_eq!(
5191                    snapshot.line_len(row as u32),
5192                    line.len() as u32,
5193                    "line_len({}).",
5194                    row
5195                );
5196            }
5197
5198            let text_rope = Rope::from(expected_text.as_str());
5199            for _ in 0..10 {
5200                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5201                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
5202
5203                let text_for_range = snapshot
5204                    .text_for_range(start_ix..end_ix)
5205                    .collect::<String>();
5206                assert_eq!(
5207                    text_for_range,
5208                    &expected_text[start_ix..end_ix],
5209                    "incorrect text for range {:?}",
5210                    start_ix..end_ix
5211                );
5212
5213                let excerpted_buffer_ranges = multibuffer
5214                    .read(cx)
5215                    .range_to_buffer_ranges(start_ix..end_ix, cx);
5216                let excerpted_buffers_text = excerpted_buffer_ranges
5217                    .iter()
5218                    .map(|(buffer, buffer_range, _)| {
5219                        buffer
5220                            .read(cx)
5221                            .text_for_range(buffer_range.clone())
5222                            .collect::<String>()
5223                    })
5224                    .collect::<Vec<_>>()
5225                    .join("\n");
5226                assert_eq!(excerpted_buffers_text, text_for_range);
5227                if !expected_excerpts.is_empty() {
5228                    assert!(!excerpted_buffer_ranges.is_empty());
5229                }
5230
5231                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
5232                assert_eq!(
5233                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
5234                    expected_summary,
5235                    "incorrect summary for range {:?}",
5236                    start_ix..end_ix
5237                );
5238            }
5239
5240            // Anchor resolution
5241            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
5242            assert_eq!(anchors.len(), summaries.len());
5243            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
5244                assert!(resolved_offset <= snapshot.len());
5245                assert_eq!(
5246                    snapshot.summary_for_anchor::<usize>(anchor),
5247                    resolved_offset
5248                );
5249            }
5250
5251            for _ in 0..10 {
5252                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
5253                assert_eq!(
5254                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
5255                    expected_text[..end_ix].chars().rev().collect::<String>(),
5256                );
5257            }
5258
5259            for _ in 0..10 {
5260                let end_ix = rng.gen_range(0..=text_rope.len());
5261                let start_ix = rng.gen_range(0..=end_ix);
5262                assert_eq!(
5263                    snapshot
5264                        .bytes_in_range(start_ix..end_ix)
5265                        .flatten()
5266                        .copied()
5267                        .collect::<Vec<_>>(),
5268                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
5269                    "bytes_in_range({:?})",
5270                    start_ix..end_ix,
5271                );
5272            }
5273        }
5274
5275        let snapshot = multibuffer.read(cx).snapshot(cx);
5276        for (old_snapshot, subscription) in old_versions {
5277            let edits = subscription.consume().into_inner();
5278
5279            log::info!(
5280                "applying subscription edits to old text: {:?}: {:?}",
5281                old_snapshot.text(),
5282                edits,
5283            );
5284
5285            let mut text = old_snapshot.text();
5286            for edit in edits {
5287                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
5288                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
5289            }
5290            assert_eq!(text.to_string(), snapshot.text());
5291        }
5292    }
5293
5294    #[gpui::test]
5295    fn test_history(cx: &mut AppContext) {
5296        cx.set_global(SettingsStore::test(cx));
5297
5298        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
5299        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
5300        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
5301        let group_interval = multibuffer.read(cx).history.group_interval;
5302        multibuffer.update(cx, |multibuffer, cx| {
5303            multibuffer.push_excerpts(
5304                buffer_1.clone(),
5305                [ExcerptRange {
5306                    context: 0..buffer_1.read(cx).len(),
5307                    primary: None,
5308                }],
5309                cx,
5310            );
5311            multibuffer.push_excerpts(
5312                buffer_2.clone(),
5313                [ExcerptRange {
5314                    context: 0..buffer_2.read(cx).len(),
5315                    primary: None,
5316                }],
5317                cx,
5318            );
5319        });
5320
5321        let mut now = Instant::now();
5322
5323        multibuffer.update(cx, |multibuffer, cx| {
5324            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
5325            multibuffer.edit(
5326                [
5327                    (Point::new(0, 0)..Point::new(0, 0), "A"),
5328                    (Point::new(1, 0)..Point::new(1, 0), "A"),
5329                ],
5330                None,
5331                cx,
5332            );
5333            multibuffer.edit(
5334                [
5335                    (Point::new(0, 1)..Point::new(0, 1), "B"),
5336                    (Point::new(1, 1)..Point::new(1, 1), "B"),
5337                ],
5338                None,
5339                cx,
5340            );
5341            multibuffer.end_transaction_at(now, cx);
5342            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5343
5344            // Edit buffer 1 through the multibuffer
5345            now += 2 * group_interval;
5346            multibuffer.start_transaction_at(now, cx);
5347            multibuffer.edit([(2..2, "C")], None, cx);
5348            multibuffer.end_transaction_at(now, cx);
5349            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
5350
5351            // Edit buffer 1 independently
5352            buffer_1.update(cx, |buffer_1, cx| {
5353                buffer_1.start_transaction_at(now);
5354                buffer_1.edit([(3..3, "D")], None, cx);
5355                buffer_1.end_transaction_at(now, cx);
5356
5357                now += 2 * group_interval;
5358                buffer_1.start_transaction_at(now);
5359                buffer_1.edit([(4..4, "E")], None, cx);
5360                buffer_1.end_transaction_at(now, cx);
5361            });
5362            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5363
5364            // An undo in the multibuffer undoes the multibuffer transaction
5365            // and also any individual buffer edits that have occurred since
5366            // that transaction.
5367            multibuffer.undo(cx);
5368            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5369
5370            multibuffer.undo(cx);
5371            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5372
5373            multibuffer.redo(cx);
5374            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5375
5376            multibuffer.redo(cx);
5377            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
5378
5379            // Undo buffer 2 independently.
5380            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
5381            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
5382
5383            // An undo in the multibuffer undoes the components of the
5384            // the last multibuffer transaction that are not already undone.
5385            multibuffer.undo(cx);
5386            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
5387
5388            multibuffer.undo(cx);
5389            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5390
5391            multibuffer.redo(cx);
5392            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
5393
5394            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
5395            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5396
5397            // Redo stack gets cleared after an edit.
5398            now += 2 * group_interval;
5399            multibuffer.start_transaction_at(now, cx);
5400            multibuffer.edit([(0..0, "X")], None, cx);
5401            multibuffer.end_transaction_at(now, cx);
5402            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5403            multibuffer.redo(cx);
5404            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5405            multibuffer.undo(cx);
5406            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
5407            multibuffer.undo(cx);
5408            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5409
5410            // Transactions can be grouped manually.
5411            multibuffer.redo(cx);
5412            multibuffer.redo(cx);
5413            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5414            multibuffer.group_until_transaction(transaction_1, cx);
5415            multibuffer.undo(cx);
5416            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
5417            multibuffer.redo(cx);
5418            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
5419        });
5420    }
5421}