multi_buffer.rs

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