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