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