multi_buffer.rs

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