multi_buffer.rs

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