multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt};
   4use anyhow::Result;
   5use clock::ReplicaId;
   6use collections::{HashMap, HashSet};
   7use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
   8use language::{
   9    Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Outline,
  10    OutlineItem, Selection, ToOffset as _, ToPoint as _, TransactionId,
  11};
  12use std::{
  13    cell::{Ref, RefCell},
  14    cmp, fmt, io,
  15    iter::{self, FromIterator},
  16    ops::{Range, Sub},
  17    str,
  18    sync::Arc,
  19    time::{Duration, Instant},
  20};
  21use sum_tree::{Bias, Cursor, SumTree};
  22use text::{
  23    locator::Locator,
  24    rope::TextDimension,
  25    subscription::{Subscription, Topic},
  26    AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary,
  27};
  28use theme::SyntaxTheme;
  29use util::post_inc;
  30
  31const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
  32
  33pub type ExcerptId = Locator;
  34
  35pub struct MultiBuffer {
  36    snapshot: RefCell<MultiBufferSnapshot>,
  37    buffers: RefCell<HashMap<usize, BufferState>>,
  38    subscriptions: Topic,
  39    singleton: bool,
  40    replica_id: ReplicaId,
  41    history: History,
  42}
  43
  44struct History {
  45    next_transaction_id: usize,
  46    undo_stack: Vec<Transaction>,
  47    redo_stack: Vec<Transaction>,
  48    transaction_depth: usize,
  49    group_interval: Duration,
  50}
  51
  52struct Transaction {
  53    id: usize,
  54    buffer_transactions: HashSet<(usize, text::TransactionId)>,
  55    first_edit_at: Instant,
  56    last_edit_at: Instant,
  57}
  58
  59pub trait ToOffset: 'static + fmt::Debug {
  60    fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
  61}
  62
  63pub trait ToPoint: 'static + fmt::Debug {
  64    fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
  65}
  66
  67struct BufferState {
  68    buffer: ModelHandle<Buffer>,
  69    last_version: clock::Global,
  70    last_parse_count: usize,
  71    last_selections_update_count: usize,
  72    last_diagnostics_update_count: usize,
  73    excerpts: Vec<ExcerptId>,
  74    _subscriptions: [gpui::Subscription; 2],
  75}
  76
  77#[derive(Clone, Default)]
  78pub struct MultiBufferSnapshot {
  79    excerpts: SumTree<Excerpt>,
  80    parse_count: usize,
  81    diagnostics_update_count: usize,
  82    is_dirty: bool,
  83    has_conflict: bool,
  84}
  85
  86pub struct ExcerptProperties<'a, T> {
  87    pub buffer: &'a ModelHandle<Buffer>,
  88    pub range: Range<T>,
  89}
  90
  91#[derive(Clone)]
  92struct Excerpt {
  93    id: ExcerptId,
  94    buffer_id: usize,
  95    buffer: BufferSnapshot,
  96    range: Range<text::Anchor>,
  97    max_buffer_row: u32,
  98    text_summary: TextSummary,
  99    has_trailing_newline: bool,
 100}
 101
 102#[derive(Clone, Debug, Default)]
 103struct ExcerptSummary {
 104    excerpt_id: ExcerptId,
 105    max_buffer_row: u32,
 106    text: TextSummary,
 107}
 108
 109pub struct MultiBufferRows<'a> {
 110    buffer_row_range: Range<u32>,
 111    excerpts: Cursor<'a, Excerpt, Point>,
 112}
 113
 114pub struct MultiBufferChunks<'a> {
 115    range: Range<usize>,
 116    excerpts: Cursor<'a, Excerpt, usize>,
 117    excerpt_chunks: Option<ExcerptChunks<'a>>,
 118    theme: Option<&'a SyntaxTheme>,
 119}
 120
 121pub struct MultiBufferBytes<'a> {
 122    range: Range<usize>,
 123    excerpts: Cursor<'a, Excerpt, usize>,
 124    excerpt_bytes: Option<ExcerptBytes<'a>>,
 125    chunk: &'a [u8],
 126}
 127
 128struct ExcerptChunks<'a> {
 129    content_chunks: BufferChunks<'a>,
 130    footer_height: usize,
 131}
 132
 133struct ExcerptBytes<'a> {
 134    content_bytes: language::rope::Bytes<'a>,
 135    footer_height: usize,
 136}
 137
 138impl MultiBuffer {
 139    pub fn new(replica_id: ReplicaId) -> Self {
 140        Self {
 141            snapshot: Default::default(),
 142            buffers: Default::default(),
 143            subscriptions: Default::default(),
 144            singleton: false,
 145            replica_id,
 146            history: History {
 147                next_transaction_id: Default::default(),
 148                undo_stack: Default::default(),
 149                redo_stack: Default::default(),
 150                transaction_depth: 0,
 151                group_interval: Duration::from_millis(300),
 152            },
 153        }
 154    }
 155
 156    pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
 157        let mut this = Self::new(buffer.read(cx).replica_id());
 158        this.singleton = true;
 159        this.push_excerpt(
 160            ExcerptProperties {
 161                buffer: &buffer,
 162                range: text::Anchor::min()..text::Anchor::max(),
 163            },
 164            cx,
 165        );
 166        this
 167    }
 168
 169    #[cfg(any(test, feature = "test-support"))]
 170    pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
 171        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 172        cx.add_model(|cx| Self::singleton(buffer, cx))
 173    }
 174
 175    #[cfg(any(test, feature = "test-support"))]
 176    pub fn build_random(
 177        mut rng: &mut impl rand::Rng,
 178        cx: &mut gpui::MutableAppContext,
 179    ) -> ModelHandle<Self> {
 180        use rand::prelude::*;
 181        use std::env;
 182        use text::RandomCharIter;
 183
 184        let max_excerpts = env::var("MAX_EXCERPTS")
 185            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
 186            .unwrap_or(5);
 187        let excerpts = rng.gen_range(1..=max_excerpts);
 188
 189        cx.add_model(|cx| {
 190            let mut multibuffer = MultiBuffer::new(0);
 191            let mut buffers = Vec::new();
 192            for _ in 0..excerpts {
 193                let buffer_handle = if rng.gen() || buffers.is_empty() {
 194                    let text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
 195                    buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
 196                    let buffer = buffers.last().unwrap();
 197                    log::info!(
 198                        "Creating new buffer {} with text: {:?}",
 199                        buffer.id(),
 200                        buffer.read(cx).text()
 201                    );
 202                    buffers.last().unwrap()
 203                } else {
 204                    buffers.choose(rng).unwrap()
 205                };
 206
 207                let buffer = buffer_handle.read(cx);
 208                let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
 209                let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
 210                let header_height = rng.gen_range(0..=5);
 211                log::info!(
 212                    "Inserting excerpt from buffer {} with header height {} and range {:?}: {:?}",
 213                    buffer_handle.id(),
 214                    header_height,
 215                    start_ix..end_ix,
 216                    &buffer.text()[start_ix..end_ix]
 217                );
 218
 219                multibuffer.push_excerpt(
 220                    ExcerptProperties {
 221                        buffer: buffer_handle,
 222                        range: start_ix..end_ix,
 223                    },
 224                    cx,
 225                );
 226            }
 227            multibuffer
 228        })
 229    }
 230
 231    pub fn replica_id(&self) -> ReplicaId {
 232        self.replica_id
 233    }
 234
 235    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
 236        self.sync(cx);
 237        self.snapshot.borrow().clone()
 238    }
 239
 240    pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
 241        self.sync(cx);
 242        self.snapshot.borrow()
 243    }
 244
 245    pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
 246        if self.singleton {
 247            return Some(
 248                self.buffers
 249                    .borrow()
 250                    .values()
 251                    .next()
 252                    .unwrap()
 253                    .buffer
 254                    .clone(),
 255            );
 256        } else {
 257            None
 258        }
 259    }
 260
 261    pub fn subscribe(&mut self) -> Subscription {
 262        self.subscriptions.subscribe()
 263    }
 264
 265    pub fn edit<I, S, T>(&mut self, ranges: I, new_text: T, cx: &mut ModelContext<Self>)
 266    where
 267        I: IntoIterator<Item = Range<S>>,
 268        S: ToOffset,
 269        T: Into<String>,
 270    {
 271        self.edit_internal(ranges, new_text, false, cx)
 272    }
 273
 274    pub fn edit_with_autoindent<I, S, T>(
 275        &mut self,
 276        ranges: I,
 277        new_text: T,
 278        cx: &mut ModelContext<Self>,
 279    ) where
 280        I: IntoIterator<Item = Range<S>>,
 281        S: ToOffset,
 282        T: Into<String>,
 283    {
 284        self.edit_internal(ranges, new_text, true, cx)
 285    }
 286
 287    pub fn edit_internal<I, S, T>(
 288        &mut self,
 289        ranges_iter: I,
 290        new_text: T,
 291        autoindent: bool,
 292        cx: &mut ModelContext<Self>,
 293    ) where
 294        I: IntoIterator<Item = Range<S>>,
 295        S: ToOffset,
 296        T: Into<String>,
 297    {
 298        if let Some(buffer) = self.as_singleton() {
 299            let snapshot = self.read(cx);
 300            let ranges = ranges_iter
 301                .into_iter()
 302                .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot));
 303            return buffer.update(cx, |buffer, cx| {
 304                if autoindent {
 305                    buffer.edit_with_autoindent(ranges, new_text, cx)
 306                } else {
 307                    buffer.edit(ranges, new_text, cx)
 308                }
 309            });
 310        }
 311
 312        let snapshot = self.read(cx);
 313        let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, bool)>> = Default::default();
 314        let mut cursor = snapshot.excerpts.cursor::<usize>();
 315        for range in ranges_iter {
 316            let start = range.start.to_offset(&snapshot);
 317            let end = range.end.to_offset(&snapshot);
 318            cursor.seek(&start, Bias::Right, &());
 319            if cursor.item().is_none() && start == *cursor.start() {
 320                cursor.prev(&());
 321            }
 322            let start_excerpt = cursor.item().expect("start offset out of bounds");
 323            let start_overshoot = start - cursor.start();
 324            let buffer_start =
 325                start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot;
 326
 327            cursor.seek(&end, Bias::Right, &());
 328            if cursor.item().is_none() && end == *cursor.start() {
 329                cursor.prev(&());
 330            }
 331            let end_excerpt = cursor.item().expect("end offset out of bounds");
 332            let end_overshoot = end - cursor.start();
 333            let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot;
 334
 335            if start_excerpt.id == end_excerpt.id {
 336                buffer_edits
 337                    .entry(start_excerpt.buffer_id)
 338                    .or_insert(Vec::new())
 339                    .push((buffer_start..buffer_end, true));
 340            } else {
 341                let start_excerpt_range =
 342                    buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
 343                let end_excerpt_range =
 344                    end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end;
 345                buffer_edits
 346                    .entry(start_excerpt.buffer_id)
 347                    .or_insert(Vec::new())
 348                    .push((start_excerpt_range, true));
 349                buffer_edits
 350                    .entry(end_excerpt.buffer_id)
 351                    .or_insert(Vec::new())
 352                    .push((end_excerpt_range, false));
 353
 354                cursor.seek(&start, Bias::Right, &());
 355                cursor.next(&());
 356                while let Some(excerpt) = cursor.item() {
 357                    if excerpt.id == end_excerpt.id {
 358                        break;
 359                    }
 360                    buffer_edits
 361                        .entry(excerpt.buffer_id)
 362                        .or_insert(Vec::new())
 363                        .push((excerpt.range.to_offset(&excerpt.buffer), false));
 364                    cursor.next(&());
 365                }
 366            }
 367        }
 368
 369        let new_text = new_text.into();
 370        for (buffer_id, mut edits) in buffer_edits {
 371            edits.sort_unstable_by_key(|(range, _)| range.start);
 372            self.buffers.borrow()[&buffer_id]
 373                .buffer
 374                .update(cx, |buffer, cx| {
 375                    let mut edits = edits.into_iter().peekable();
 376                    let mut insertions = Vec::new();
 377                    let mut deletions = Vec::new();
 378                    while let Some((mut range, mut is_insertion)) = edits.next() {
 379                        while let Some((next_range, next_is_insertion)) = edits.peek() {
 380                            if range.end >= next_range.start {
 381                                range.end = cmp::max(next_range.end, range.end);
 382                                is_insertion |= *next_is_insertion;
 383                                edits.next();
 384                            } else {
 385                                break;
 386                            }
 387                        }
 388
 389                        if is_insertion {
 390                            insertions.push(
 391                                buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 392                            );
 393                        } else if !range.is_empty() {
 394                            deletions.push(
 395                                buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 396                            );
 397                        }
 398                    }
 399
 400                    if autoindent {
 401                        buffer.edit_with_autoindent(deletions, "", cx);
 402                        buffer.edit_with_autoindent(insertions, new_text.clone(), cx);
 403                    } else {
 404                        buffer.edit(deletions, "", cx);
 405                        buffer.edit(insertions, new_text.clone(), cx);
 406                    }
 407                })
 408        }
 409    }
 410
 411    pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 412        self.start_transaction_at(Instant::now(), cx)
 413    }
 414
 415    pub(crate) fn start_transaction_at(
 416        &mut self,
 417        now: Instant,
 418        cx: &mut ModelContext<Self>,
 419    ) -> Option<TransactionId> {
 420        if let Some(buffer) = self.as_singleton() {
 421            return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 422        }
 423
 424        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 425            buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 426        }
 427        self.history.start_transaction(now)
 428    }
 429
 430    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 431        self.end_transaction_at(Instant::now(), cx)
 432    }
 433
 434    pub(crate) fn end_transaction_at(
 435        &mut self,
 436        now: Instant,
 437        cx: &mut ModelContext<Self>,
 438    ) -> Option<TransactionId> {
 439        if let Some(buffer) = self.as_singleton() {
 440            return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
 441        }
 442
 443        let mut buffer_transactions = HashSet::default();
 444        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 445            if let Some(transaction_id) =
 446                buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 447            {
 448                buffer_transactions.insert((buffer.id(), transaction_id));
 449            }
 450        }
 451
 452        if self.history.end_transaction(now, buffer_transactions) {
 453            let transaction_id = self.history.group().unwrap();
 454            Some(transaction_id)
 455        } else {
 456            None
 457        }
 458    }
 459
 460    pub fn avoid_grouping_next_transaction(&mut self, cx: &mut ModelContext<Self>) {
 461        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 462            buffer.update(cx, |buffer, _| buffer.avoid_grouping_next_transaction());
 463        }
 464    }
 465
 466    pub fn set_active_selections(
 467        &mut self,
 468        selections: &[Selection<Anchor>],
 469        cx: &mut ModelContext<Self>,
 470    ) {
 471        let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
 472            Default::default();
 473        let snapshot = self.read(cx);
 474        let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
 475        for selection in selections {
 476            cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &());
 477            while let Some(excerpt) = cursor.item() {
 478                if excerpt.id > selection.end.excerpt_id {
 479                    break;
 480                }
 481
 482                let mut start = excerpt.range.start.clone();
 483                let mut end = excerpt.range.end.clone();
 484                if excerpt.id == selection.start.excerpt_id {
 485                    start = selection.start.text_anchor.clone();
 486                }
 487                if excerpt.id == selection.end.excerpt_id {
 488                    end = selection.end.text_anchor.clone();
 489                }
 490                selections_by_buffer
 491                    .entry(excerpt.buffer_id)
 492                    .or_default()
 493                    .push(Selection {
 494                        id: selection.id,
 495                        start,
 496                        end,
 497                        reversed: selection.reversed,
 498                        goal: selection.goal,
 499                    });
 500
 501                cursor.next(&());
 502            }
 503        }
 504
 505        for (buffer_id, buffer_state) in self.buffers.borrow().iter() {
 506            if !selections_by_buffer.contains_key(buffer_id) {
 507                buffer_state
 508                    .buffer
 509                    .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 510            }
 511        }
 512
 513        for (buffer_id, mut selections) in selections_by_buffer {
 514            self.buffers.borrow()[&buffer_id]
 515                .buffer
 516                .update(cx, |buffer, cx| {
 517                    selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap());
 518                    let mut selections = selections.into_iter().peekable();
 519                    let merged_selections = Arc::from_iter(iter::from_fn(|| {
 520                        let mut selection = selections.next()?;
 521                        while let Some(next_selection) = selections.peek() {
 522                            if selection
 523                                .end
 524                                .cmp(&next_selection.start, buffer)
 525                                .unwrap()
 526                                .is_ge()
 527                            {
 528                                let next_selection = selections.next().unwrap();
 529                                if next_selection
 530                                    .end
 531                                    .cmp(&selection.end, buffer)
 532                                    .unwrap()
 533                                    .is_ge()
 534                                {
 535                                    selection.end = next_selection.end;
 536                                }
 537                            } else {
 538                                break;
 539                            }
 540                        }
 541                        Some(selection)
 542                    }));
 543                    buffer.set_active_selections(merged_selections, cx);
 544                });
 545        }
 546    }
 547
 548    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 549        for buffer in self.buffers.borrow().values() {
 550            buffer
 551                .buffer
 552                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 553        }
 554    }
 555
 556    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 557        if let Some(buffer) = self.as_singleton() {
 558            return buffer.update(cx, |buffer, cx| buffer.undo(cx));
 559        }
 560
 561        while let Some(transaction) = self.history.pop_undo() {
 562            let mut undone = false;
 563            for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
 564                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
 565                    undone |= buffer.update(cx, |buf, cx| {
 566                        buf.undo_transaction(*buffer_transaction_id, cx)
 567                    });
 568                }
 569            }
 570
 571            if undone {
 572                return Some(transaction.id);
 573            }
 574        }
 575
 576        None
 577    }
 578
 579    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 580        if let Some(buffer) = self.as_singleton() {
 581            return buffer.update(cx, |buffer, cx| buffer.redo(cx));
 582        }
 583
 584        while let Some(transaction) = self.history.pop_redo() {
 585            let mut redone = false;
 586            for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
 587                if let Some(BufferState { buffer, .. }) = self.buffers.borrow().get(&buffer_id) {
 588                    redone |= buffer.update(cx, |buf, cx| {
 589                        buf.redo_transaction(*buffer_transaction_id, cx)
 590                    });
 591                }
 592            }
 593
 594            if redone {
 595                return Some(transaction.id);
 596            }
 597        }
 598
 599        None
 600    }
 601
 602    pub fn push_excerpt<O>(
 603        &mut self,
 604        props: ExcerptProperties<O>,
 605        cx: &mut ModelContext<Self>,
 606    ) -> ExcerptId
 607    where
 608        O: text::ToOffset,
 609    {
 610        self.insert_excerpt_after(&ExcerptId::max(), props, cx)
 611    }
 612
 613    pub fn insert_excerpt_after<O>(
 614        &mut self,
 615        prev_excerpt_id: &ExcerptId,
 616        props: ExcerptProperties<O>,
 617        cx: &mut ModelContext<Self>,
 618    ) -> ExcerptId
 619    where
 620        O: text::ToOffset,
 621    {
 622        assert_eq!(self.history.transaction_depth, 0);
 623        self.sync(cx);
 624
 625        let buffer_snapshot = props.buffer.read(cx).snapshot();
 626        let range = buffer_snapshot.anchor_before(&props.range.start)
 627            ..buffer_snapshot.anchor_after(&props.range.end);
 628        let mut snapshot = self.snapshot.borrow_mut();
 629        let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
 630        let mut new_excerpts = cursor.slice(&Some(prev_excerpt_id), Bias::Right, &());
 631
 632        let mut prev_id = ExcerptId::min();
 633        let edit_start = new_excerpts.summary().text.bytes;
 634        new_excerpts.update_last(
 635            |excerpt| {
 636                excerpt.has_trailing_newline = true;
 637                prev_id = excerpt.id.clone();
 638            },
 639            &(),
 640        );
 641
 642        let mut next_id = ExcerptId::max();
 643        if let Some(next_excerpt) = cursor.item() {
 644            next_id = next_excerpt.id.clone();
 645        }
 646
 647        let id = ExcerptId::between(&prev_id, &next_id);
 648
 649        let mut buffers = self.buffers.borrow_mut();
 650        let buffer_state = buffers
 651            .entry(props.buffer.id())
 652            .or_insert_with(|| BufferState {
 653                last_version: buffer_snapshot.version().clone(),
 654                last_parse_count: buffer_snapshot.parse_count(),
 655                last_selections_update_count: buffer_snapshot.selections_update_count(),
 656                last_diagnostics_update_count: buffer_snapshot.diagnostics_update_count(),
 657                excerpts: Default::default(),
 658                _subscriptions: [
 659                    cx.observe(&props.buffer, |_, _, cx| cx.notify()),
 660                    cx.subscribe(&props.buffer, Self::on_buffer_event),
 661                ],
 662                buffer: props.buffer.clone(),
 663            });
 664        if let Err(ix) = buffer_state.excerpts.binary_search(&id) {
 665            buffer_state.excerpts.insert(ix, id.clone());
 666        }
 667
 668        let excerpt = Excerpt::new(
 669            id.clone(),
 670            props.buffer.id(),
 671            buffer_snapshot,
 672            range,
 673            cursor.item().is_some(),
 674        );
 675        new_excerpts.push(excerpt, &());
 676        let edit_end = new_excerpts.summary().text.bytes;
 677
 678        new_excerpts.push_tree(cursor.suffix(&()), &());
 679        drop(cursor);
 680        snapshot.excerpts = new_excerpts;
 681
 682        self.subscriptions.publish_mut([Edit {
 683            old: edit_start..edit_start,
 684            new: edit_start..edit_end,
 685        }]);
 686
 687        cx.notify();
 688        id
 689    }
 690
 691    pub fn excerpt_ids_for_buffer(&self, buffer: &ModelHandle<Buffer>) -> Vec<ExcerptId> {
 692        self.buffers
 693            .borrow()
 694            .get(&buffer.id())
 695            .map_or(Vec::new(), |state| state.excerpts.clone())
 696    }
 697
 698    pub fn excerpted_buffers<'a, T: ToOffset>(
 699        &'a self,
 700        range: Range<T>,
 701        cx: &AppContext,
 702    ) -> Vec<(ModelHandle<Buffer>, Range<usize>)> {
 703        let snapshot = self.snapshot(cx);
 704        let start = range.start.to_offset(&snapshot);
 705        let end = range.end.to_offset(&snapshot);
 706
 707        let mut result = Vec::new();
 708        let mut cursor = snapshot.excerpts.cursor::<usize>();
 709        cursor.seek(&start, Bias::Right, &());
 710        while let Some(excerpt) = cursor.item() {
 711            if *cursor.start() > end {
 712                break;
 713            }
 714
 715            let mut end_before_newline = cursor.end(&());
 716            if excerpt.has_trailing_newline {
 717                end_before_newline -= 1;
 718            }
 719            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 720            let start = excerpt_start + (cmp::max(start, *cursor.start()) - *cursor.start());
 721            let end = excerpt_start + (cmp::min(end, end_before_newline) - *cursor.start());
 722            let buffer = self.buffers.borrow()[&excerpt.buffer_id].buffer.clone();
 723            result.push((buffer, start..end));
 724            cursor.next(&());
 725        }
 726
 727        result
 728    }
 729
 730    pub fn remove_excerpts<'a>(
 731        &mut self,
 732        excerpt_ids: impl IntoIterator<Item = &'a ExcerptId>,
 733        cx: &mut ModelContext<Self>,
 734    ) {
 735        let mut buffers = self.buffers.borrow_mut();
 736        let mut snapshot = self.snapshot.borrow_mut();
 737        let mut new_excerpts = SumTree::new();
 738        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 739        let mut edits = Vec::new();
 740        let mut excerpt_ids = excerpt_ids.into_iter().peekable();
 741
 742        while let Some(mut excerpt_id) = excerpt_ids.next() {
 743            // Seek to the next excerpt to remove, preserving any preceding excerpts.
 744            new_excerpts.push_tree(cursor.slice(&Some(excerpt_id), Bias::Left, &()), &());
 745            if let Some(mut excerpt) = cursor.item() {
 746                if excerpt.id != *excerpt_id {
 747                    continue;
 748                }
 749                let mut old_start = cursor.start().1;
 750
 751                // Skip over the removed excerpt.
 752                loop {
 753                    if let Some(buffer_state) = buffers.get_mut(&excerpt.buffer_id) {
 754                        buffer_state.excerpts.retain(|id| id != excerpt_id);
 755                        if buffer_state.excerpts.is_empty() {
 756                            buffers.remove(&excerpt.buffer_id);
 757                        }
 758                    }
 759                    cursor.next(&());
 760
 761                    // Skip over any subsequent excerpts that are also removed.
 762                    if let Some(&next_excerpt_id) = excerpt_ids.peek() {
 763                        if let Some(next_excerpt) = cursor.item() {
 764                            if next_excerpt.id == *next_excerpt_id {
 765                                excerpt = next_excerpt;
 766                                excerpt_id = excerpt_ids.next().unwrap();
 767                                continue;
 768                            }
 769                        }
 770                    }
 771
 772                    break;
 773                }
 774
 775                // When removing the last excerpt, remove the trailing newline from
 776                // the previous excerpt.
 777                if cursor.item().is_none() && old_start > 0 {
 778                    old_start -= 1;
 779                    new_excerpts.update_last(|e| e.has_trailing_newline = false, &());
 780                }
 781
 782                // Push an edit for the removal of this run of excerpts.
 783                let old_end = cursor.start().1;
 784                let new_start = new_excerpts.summary().text.bytes;
 785                edits.push(Edit {
 786                    old: old_start..old_end,
 787                    new: new_start..new_start,
 788                });
 789            }
 790        }
 791        new_excerpts.push_tree(cursor.suffix(&()), &());
 792        drop(cursor);
 793        snapshot.excerpts = new_excerpts;
 794        self.subscriptions.publish_mut(edits);
 795        cx.notify();
 796    }
 797
 798    pub fn text_anchor_for_position<'a, T: ToOffset>(
 799        &'a self,
 800        position: T,
 801        cx: &AppContext,
 802    ) -> (ModelHandle<Buffer>, language::Anchor) {
 803        let snapshot = self.read(cx);
 804        let anchor = snapshot.anchor_before(position);
 805        (
 806            self.buffers.borrow()[&anchor.buffer_id].buffer.clone(),
 807            anchor.text_anchor,
 808        )
 809    }
 810
 811    fn on_buffer_event(
 812        &mut self,
 813        _: ModelHandle<Buffer>,
 814        event: &Event,
 815        cx: &mut ModelContext<Self>,
 816    ) {
 817        cx.emit(event.clone());
 818    }
 819
 820    pub fn format(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 821        let mut format_tasks = Vec::new();
 822        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 823            format_tasks.push(buffer.update(cx, |buffer, cx| buffer.format(cx)));
 824        }
 825
 826        cx.spawn(|_, _| async move {
 827            for format in format_tasks {
 828                format.await?;
 829            }
 830            Ok(())
 831        })
 832    }
 833
 834    pub fn save(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 835        let mut save_tasks = Vec::new();
 836        for BufferState { buffer, .. } in self.buffers.borrow().values() {
 837            save_tasks.push(buffer.update(cx, |buffer, cx| buffer.save(cx)));
 838        }
 839
 840        cx.spawn(|_, _| async move {
 841            for save in save_tasks {
 842                save.await?;
 843            }
 844            Ok(())
 845        })
 846    }
 847
 848    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 849        self.buffers
 850            .borrow()
 851            .values()
 852            .next()
 853            .and_then(|state| state.buffer.read(cx).language())
 854    }
 855
 856    pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
 857        self.as_singleton()?.read(cx).file()
 858    }
 859
 860    #[cfg(test)]
 861    pub fn is_parsing(&self, cx: &AppContext) -> bool {
 862        self.as_singleton().unwrap().read(cx).is_parsing()
 863    }
 864
 865    fn sync(&self, cx: &AppContext) {
 866        let mut snapshot = self.snapshot.borrow_mut();
 867        let mut excerpts_to_edit = Vec::new();
 868        let mut reparsed = false;
 869        let mut diagnostics_updated = false;
 870        let mut is_dirty = false;
 871        let mut has_conflict = false;
 872        let mut buffers = self.buffers.borrow_mut();
 873        for buffer_state in buffers.values_mut() {
 874            let buffer = buffer_state.buffer.read(cx);
 875            let version = buffer.version();
 876            let parse_count = buffer.parse_count();
 877            let selections_update_count = buffer.selections_update_count();
 878            let diagnostics_update_count = buffer.diagnostics_update_count();
 879
 880            let buffer_edited = version.changed_since(&buffer_state.last_version);
 881            let buffer_reparsed = parse_count > buffer_state.last_parse_count;
 882            let buffer_selections_updated =
 883                selections_update_count > buffer_state.last_selections_update_count;
 884            let buffer_diagnostics_updated =
 885                diagnostics_update_count > buffer_state.last_diagnostics_update_count;
 886            if buffer_edited
 887                || buffer_reparsed
 888                || buffer_selections_updated
 889                || buffer_diagnostics_updated
 890            {
 891                buffer_state.last_version = version;
 892                buffer_state.last_parse_count = parse_count;
 893                buffer_state.last_selections_update_count = selections_update_count;
 894                buffer_state.last_diagnostics_update_count = diagnostics_update_count;
 895                excerpts_to_edit.extend(
 896                    buffer_state
 897                        .excerpts
 898                        .iter()
 899                        .map(|excerpt_id| (excerpt_id, buffer_state.buffer.clone(), buffer_edited)),
 900                );
 901            }
 902
 903            reparsed |= buffer_reparsed;
 904            diagnostics_updated |= buffer_diagnostics_updated;
 905            is_dirty |= buffer.is_dirty();
 906            has_conflict |= buffer.has_conflict();
 907        }
 908        if reparsed {
 909            snapshot.parse_count += 1;
 910        }
 911        if diagnostics_updated {
 912            snapshot.diagnostics_update_count += 1;
 913        }
 914        snapshot.is_dirty = is_dirty;
 915        snapshot.has_conflict = has_conflict;
 916
 917        excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
 918
 919        let mut edits = Vec::new();
 920        let mut new_excerpts = SumTree::new();
 921        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 922
 923        for (id, buffer, buffer_edited) in excerpts_to_edit {
 924            new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
 925            let old_excerpt = cursor.item().unwrap();
 926            let buffer_id = buffer.id();
 927            let buffer = buffer.read(cx);
 928
 929            let mut new_excerpt;
 930            if buffer_edited {
 931                edits.extend(
 932                    buffer
 933                        .edits_since_in_range::<usize>(
 934                            old_excerpt.buffer.version(),
 935                            old_excerpt.range.clone(),
 936                        )
 937                        .map(|mut edit| {
 938                            let excerpt_old_start = cursor.start().1;
 939                            let excerpt_new_start = new_excerpts.summary().text.bytes;
 940                            edit.old.start += excerpt_old_start;
 941                            edit.old.end += excerpt_old_start;
 942                            edit.new.start += excerpt_new_start;
 943                            edit.new.end += excerpt_new_start;
 944                            edit
 945                        }),
 946                );
 947
 948                new_excerpt = Excerpt::new(
 949                    id.clone(),
 950                    buffer_id,
 951                    buffer.snapshot(),
 952                    old_excerpt.range.clone(),
 953                    old_excerpt.has_trailing_newline,
 954                );
 955            } else {
 956                new_excerpt = old_excerpt.clone();
 957                new_excerpt.buffer = buffer.snapshot();
 958            }
 959
 960            new_excerpts.push(new_excerpt, &());
 961            cursor.next(&());
 962        }
 963        new_excerpts.push_tree(cursor.suffix(&()), &());
 964
 965        drop(cursor);
 966        snapshot.excerpts = new_excerpts;
 967
 968        self.subscriptions.publish(edits);
 969    }
 970}
 971
 972#[cfg(any(test, feature = "test-support"))]
 973impl MultiBuffer {
 974    pub fn randomly_edit(
 975        &mut self,
 976        rng: &mut impl rand::Rng,
 977        count: usize,
 978        cx: &mut ModelContext<Self>,
 979    ) {
 980        use text::RandomCharIter;
 981
 982        let snapshot = self.read(cx);
 983        let mut old_ranges: Vec<Range<usize>> = Vec::new();
 984        for _ in 0..count {
 985            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
 986            if last_end > snapshot.len() {
 987                break;
 988            }
 989            let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
 990            let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
 991            old_ranges.push(start_ix..end_ix);
 992        }
 993        let new_text_len = rng.gen_range(0..10);
 994        let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
 995        log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
 996        drop(snapshot);
 997
 998        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
 999    }
1000}
1001
1002impl Entity for MultiBuffer {
1003    type Event = language::Event;
1004}
1005
1006impl MultiBufferSnapshot {
1007    pub fn text(&self) -> String {
1008        self.chunks(0..self.len(), None)
1009            .map(|chunk| chunk.text)
1010            .collect()
1011    }
1012
1013    pub fn reversed_chars_at<'a, T: ToOffset>(
1014        &'a self,
1015        position: T,
1016    ) -> impl Iterator<Item = char> + 'a {
1017        let mut offset = position.to_offset(self);
1018        let mut cursor = self.excerpts.cursor::<usize>();
1019        cursor.seek(&offset, Bias::Left, &());
1020        let mut excerpt_chunks = cursor.item().map(|excerpt| {
1021            let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
1022            let start = excerpt.range.start.to_offset(&excerpt.buffer);
1023            let end = start + (cmp::min(offset, end_before_footer) - cursor.start());
1024            excerpt.buffer.reversed_chunks_in_range(start..end)
1025        });
1026        iter::from_fn(move || {
1027            if offset == *cursor.start() {
1028                cursor.prev(&());
1029                let excerpt = cursor.item()?;
1030                excerpt_chunks = Some(
1031                    excerpt
1032                        .buffer
1033                        .reversed_chunks_in_range(excerpt.range.clone()),
1034                );
1035            }
1036
1037            let excerpt = cursor.item().unwrap();
1038            if offset == cursor.end(&()) && excerpt.has_trailing_newline {
1039                offset -= 1;
1040                Some("\n")
1041            } else {
1042                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
1043                offset -= chunk.len();
1044                Some(chunk)
1045            }
1046        })
1047        .flat_map(|c| c.chars().rev())
1048    }
1049
1050    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1051        let offset = position.to_offset(self);
1052        self.text_for_range(offset..self.len())
1053            .flat_map(|chunk| chunk.chars())
1054    }
1055
1056    pub fn text_for_range<'a, T: ToOffset>(
1057        &'a self,
1058        range: Range<T>,
1059    ) -> impl Iterator<Item = &'a str> {
1060        self.chunks(range, None).map(|chunk| chunk.text)
1061    }
1062
1063    pub fn is_line_blank(&self, row: u32) -> bool {
1064        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1065            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1066    }
1067
1068    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1069    where
1070        T: ToOffset,
1071    {
1072        let position = position.to_offset(self);
1073        position == self.clip_offset(position, Bias::Left)
1074            && self
1075                .bytes_in_range(position..self.len())
1076                .flatten()
1077                .copied()
1078                .take(needle.len())
1079                .eq(needle.bytes())
1080    }
1081
1082    fn as_singleton(&self) -> Option<&BufferSnapshot> {
1083        let mut excerpts = self.excerpts.iter();
1084        let buffer = excerpts.next().map(|excerpt| &excerpt.buffer);
1085        if excerpts.next().is_none() {
1086            buffer
1087        } else {
1088            None
1089        }
1090    }
1091
1092    pub fn len(&self) -> usize {
1093        self.excerpts.summary().text.bytes
1094    }
1095
1096    pub fn max_buffer_row(&self) -> u32 {
1097        self.excerpts.summary().max_buffer_row
1098    }
1099
1100    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1101        let mut cursor = self.excerpts.cursor::<usize>();
1102        cursor.seek(&offset, Bias::Right, &());
1103        let overshoot = if let Some(excerpt) = cursor.item() {
1104            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1105            let buffer_offset = excerpt
1106                .buffer
1107                .clip_offset(excerpt_start + (offset - cursor.start()), bias);
1108            buffer_offset.saturating_sub(excerpt_start)
1109        } else {
1110            0
1111        };
1112        cursor.start() + overshoot
1113    }
1114
1115    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1116        let mut cursor = self.excerpts.cursor::<Point>();
1117        cursor.seek(&point, Bias::Right, &());
1118        let overshoot = if let Some(excerpt) = cursor.item() {
1119            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1120            let buffer_point = excerpt
1121                .buffer
1122                .clip_point(excerpt_start + (point - cursor.start()), bias);
1123            buffer_point.saturating_sub(excerpt_start)
1124        } else {
1125            Point::zero()
1126        };
1127        *cursor.start() + overshoot
1128    }
1129
1130    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1131        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1132        cursor.seek(&point, Bias::Right, &());
1133        let overshoot = if let Some(excerpt) = cursor.item() {
1134            let excerpt_start = excerpt
1135                .buffer
1136                .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1137            let buffer_point = excerpt
1138                .buffer
1139                .clip_point_utf16(excerpt_start + (point - cursor.start()), bias);
1140            buffer_point.saturating_sub(excerpt_start)
1141        } else {
1142            PointUtf16::zero()
1143        };
1144        *cursor.start() + overshoot
1145    }
1146
1147    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1148        let range = range.start.to_offset(self)..range.end.to_offset(self);
1149        let mut excerpts = self.excerpts.cursor::<usize>();
1150        excerpts.seek(&range.start, Bias::Right, &());
1151
1152        let mut chunk = &[][..];
1153        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1154            let mut excerpt_bytes = excerpt
1155                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1156            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1157            Some(excerpt_bytes)
1158        } else {
1159            None
1160        };
1161
1162        MultiBufferBytes {
1163            range,
1164            excerpts,
1165            excerpt_bytes,
1166            chunk,
1167        }
1168    }
1169
1170    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1171        let mut result = MultiBufferRows {
1172            buffer_row_range: 0..0,
1173            excerpts: self.excerpts.cursor(),
1174        };
1175        result.seek(start_row);
1176        result
1177    }
1178
1179    pub fn chunks<'a, T: ToOffset>(
1180        &'a self,
1181        range: Range<T>,
1182        theme: Option<&'a SyntaxTheme>,
1183    ) -> MultiBufferChunks<'a> {
1184        let range = range.start.to_offset(self)..range.end.to_offset(self);
1185        let mut chunks = MultiBufferChunks {
1186            range: range.clone(),
1187            excerpts: self.excerpts.cursor(),
1188            excerpt_chunks: None,
1189            theme,
1190        };
1191        chunks.seek(range.start);
1192        chunks
1193    }
1194
1195    pub fn offset_to_point(&self, offset: usize) -> Point {
1196        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1197        cursor.seek(&offset, Bias::Right, &());
1198        if let Some(excerpt) = cursor.item() {
1199            let (start_offset, start_point) = cursor.start();
1200            let overshoot = offset - start_offset;
1201            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1202            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1203            let buffer_point = excerpt
1204                .buffer
1205                .offset_to_point(excerpt_start_offset + overshoot);
1206            *start_point + (buffer_point - excerpt_start_point)
1207        } else {
1208            self.excerpts.summary().text.lines
1209        }
1210    }
1211
1212    pub fn point_to_offset(&self, point: Point) -> usize {
1213        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1214        cursor.seek(&point, Bias::Right, &());
1215        if let Some(excerpt) = cursor.item() {
1216            let (start_point, start_offset) = cursor.start();
1217            let overshoot = point - start_point;
1218            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1219            let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1220            let buffer_offset = excerpt
1221                .buffer
1222                .point_to_offset(excerpt_start_point + overshoot);
1223            *start_offset + buffer_offset - excerpt_start_offset
1224        } else {
1225            self.excerpts.summary().text.bytes
1226        }
1227    }
1228
1229    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1230        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1231        cursor.seek(&point, Bias::Right, &());
1232        if let Some(excerpt) = cursor.item() {
1233            let (start_point, start_offset) = cursor.start();
1234            let overshoot = point - start_point;
1235            let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1236            let excerpt_start_point = excerpt
1237                .buffer
1238                .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1239            let buffer_offset = excerpt
1240                .buffer
1241                .point_utf16_to_offset(excerpt_start_point + overshoot);
1242            *start_offset + (buffer_offset - excerpt_start_offset)
1243        } else {
1244            self.excerpts.summary().text.bytes
1245        }
1246    }
1247
1248    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1249        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1250            buffer
1251                .indent_column_for_line(range.start.row)
1252                .min(range.end.column)
1253                .saturating_sub(range.start.column)
1254        } else {
1255            0
1256        }
1257    }
1258
1259    pub fn line_len(&self, row: u32) -> u32 {
1260        if let Some((_, range)) = self.buffer_line_for_row(row) {
1261            range.end.column - range.start.column
1262        } else {
1263            0
1264        }
1265    }
1266
1267    fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1268        let mut cursor = self.excerpts.cursor::<Point>();
1269        cursor.seek(&Point::new(row, 0), Bias::Right, &());
1270        if let Some(excerpt) = cursor.item() {
1271            let overshoot = row - cursor.start().row;
1272            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1273            let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1274            let buffer_row = excerpt_start.row + overshoot;
1275            let line_start = Point::new(buffer_row, 0);
1276            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1277            return Some((
1278                &excerpt.buffer,
1279                line_start.max(excerpt_start)..line_end.min(excerpt_end),
1280            ));
1281        }
1282        None
1283    }
1284
1285    pub fn max_point(&self) -> Point {
1286        self.text_summary().lines
1287    }
1288
1289    pub fn text_summary(&self) -> TextSummary {
1290        self.excerpts.summary().text
1291    }
1292
1293    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1294    where
1295        D: TextDimension,
1296        O: ToOffset,
1297    {
1298        let mut summary = D::default();
1299        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1300        let mut cursor = self.excerpts.cursor::<usize>();
1301        cursor.seek(&range.start, Bias::Right, &());
1302        if let Some(excerpt) = cursor.item() {
1303            let mut end_before_newline = cursor.end(&());
1304            if excerpt.has_trailing_newline {
1305                end_before_newline -= 1;
1306            }
1307
1308            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1309            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
1310            let end_in_excerpt =
1311                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
1312            summary.add_assign(
1313                &excerpt
1314                    .buffer
1315                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1316            );
1317
1318            if range.end > end_before_newline {
1319                summary.add_assign(&D::from_text_summary(&TextSummary {
1320                    bytes: 1,
1321                    lines: Point::new(1 as u32, 0),
1322                    lines_utf16: PointUtf16::new(1 as u32, 0),
1323                    first_line_chars: 0,
1324                    last_line_chars: 0,
1325                    longest_row: 0,
1326                    longest_row_chars: 0,
1327                }));
1328            }
1329
1330            cursor.next(&());
1331        }
1332
1333        if range.end > *cursor.start() {
1334            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1335                &range.end,
1336                Bias::Right,
1337                &(),
1338            )));
1339            if let Some(excerpt) = cursor.item() {
1340                range.end = cmp::max(*cursor.start(), range.end);
1341
1342                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1343                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
1344                summary.add_assign(
1345                    &excerpt
1346                        .buffer
1347                        .text_summary_for_range(excerpt_start..end_in_excerpt),
1348                );
1349            }
1350        }
1351
1352        summary
1353    }
1354
1355    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1356    where
1357        D: TextDimension + Ord + Sub<D, Output = D>,
1358    {
1359        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1360        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1361        if cursor.item().is_none() {
1362            cursor.next(&());
1363        }
1364
1365        let mut position = D::from_text_summary(&cursor.start().text);
1366        if let Some(excerpt) = cursor.item() {
1367            if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id {
1368                let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1369                let buffer_position = anchor.text_anchor.summary::<D>(&excerpt.buffer);
1370                if buffer_position > excerpt_buffer_start {
1371                    position.add_assign(&(buffer_position - excerpt_buffer_start));
1372                }
1373            }
1374        }
1375        position
1376    }
1377
1378    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1379    where
1380        D: TextDimension + Ord + Sub<D, Output = D>,
1381        I: 'a + IntoIterator<Item = &'a Anchor>,
1382    {
1383        let mut anchors = anchors.into_iter().peekable();
1384        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1385        let mut summaries = Vec::new();
1386        while let Some(anchor) = anchors.peek() {
1387            let excerpt_id = &anchor.excerpt_id;
1388            let buffer_id = anchor.buffer_id;
1389            let excerpt_anchors = iter::from_fn(|| {
1390                let anchor = anchors.peek()?;
1391                if anchor.excerpt_id == *excerpt_id && anchor.buffer_id == buffer_id {
1392                    Some(&anchors.next().unwrap().text_anchor)
1393                } else {
1394                    None
1395                }
1396            });
1397
1398            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1399            if cursor.item().is_none() {
1400                cursor.next(&());
1401            }
1402
1403            let position = D::from_text_summary(&cursor.start().text);
1404            if let Some(excerpt) = cursor.item() {
1405                if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id {
1406                    let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1407                    summaries.extend(
1408                        excerpt
1409                            .buffer
1410                            .summaries_for_anchors::<D, _>(excerpt_anchors)
1411                            .map(move |summary| {
1412                                let mut position = position.clone();
1413                                let excerpt_buffer_start = excerpt_buffer_start.clone();
1414                                if summary > excerpt_buffer_start {
1415                                    position.add_assign(&(summary - excerpt_buffer_start));
1416                                }
1417                                position
1418                            }),
1419                    );
1420                    continue;
1421                }
1422            }
1423
1424            summaries.extend(excerpt_anchors.map(|_| position.clone()));
1425        }
1426
1427        summaries
1428    }
1429
1430    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
1431    where
1432        I: 'a + IntoIterator<Item = &'a Anchor>,
1433    {
1434        let mut anchors = anchors.into_iter().enumerate().peekable();
1435        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1436        let mut result = Vec::new();
1437        while let Some((_, anchor)) = anchors.peek() {
1438            let old_excerpt_id = &anchor.excerpt_id;
1439
1440            // Find the location where this anchor's excerpt should be.
1441            cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
1442            if cursor.item().is_none() {
1443                cursor.next(&());
1444            }
1445
1446            let next_excerpt = cursor.item();
1447            let prev_excerpt = cursor.prev_item();
1448
1449            // Process all of the anchors for this excerpt.
1450            while let Some((_, anchor)) = anchors.peek() {
1451                if anchor.excerpt_id != *old_excerpt_id {
1452                    break;
1453                }
1454                let mut kept_position = false;
1455                let (anchor_ix, anchor) = anchors.next().unwrap();
1456                let mut anchor = anchor.clone();
1457
1458                // Leave min and max anchors unchanged.
1459                if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
1460                    kept_position = true;
1461                }
1462                // If the old excerpt still exists at this location, then leave
1463                // the anchor unchanged.
1464                else if next_excerpt.map_or(false, |excerpt| {
1465                    excerpt.id == *old_excerpt_id && excerpt.buffer_id == anchor.buffer_id
1466                }) {
1467                    kept_position = true;
1468                }
1469                // If the old excerpt no longer exists at this location, then attempt to
1470                // find an equivalent position for this anchor in an adjacent excerpt.
1471                else {
1472                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
1473                        if excerpt.contains(&anchor) {
1474                            anchor.excerpt_id = excerpt.id.clone();
1475                            kept_position = true;
1476                            break;
1477                        }
1478                    }
1479                }
1480                // If there's no adjacent excerpt that contains the anchor's position,
1481                // then report that the anchor has lost its position.
1482                if !kept_position {
1483                    anchor = if let Some(excerpt) = next_excerpt {
1484                        Anchor {
1485                            buffer_id: excerpt.buffer_id,
1486                            excerpt_id: excerpt.id.clone(),
1487                            text_anchor: excerpt
1488                                .buffer
1489                                .anchor_at(&excerpt.range.start, anchor.text_anchor.bias),
1490                        }
1491                    } else if let Some(excerpt) = prev_excerpt {
1492                        Anchor {
1493                            buffer_id: excerpt.buffer_id,
1494                            excerpt_id: excerpt.id.clone(),
1495                            text_anchor: excerpt
1496                                .buffer
1497                                .anchor_at(&excerpt.range.end, anchor.text_anchor.bias),
1498                        }
1499                    } else if anchor.text_anchor.bias == Bias::Left {
1500                        Anchor::min()
1501                    } else {
1502                        Anchor::max()
1503                    };
1504                }
1505
1506                result.push((anchor_ix, anchor, kept_position));
1507            }
1508        }
1509        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self).unwrap());
1510        result
1511    }
1512
1513    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1514        self.anchor_at(position, Bias::Left)
1515    }
1516
1517    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1518        self.anchor_at(position, Bias::Right)
1519    }
1520
1521    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1522        let offset = position.to_offset(self);
1523        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1524        cursor.seek(&offset, Bias::Right, &());
1525        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1526            cursor.prev(&());
1527        }
1528        if let Some(excerpt) = cursor.item() {
1529            let mut overshoot = offset.saturating_sub(cursor.start().0);
1530            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1531                overshoot -= 1;
1532                bias = Bias::Right;
1533            }
1534
1535            let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1536            let text_anchor =
1537                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1538            Anchor {
1539                buffer_id: excerpt.buffer_id,
1540                excerpt_id: excerpt.id.clone(),
1541                text_anchor,
1542            }
1543        } else if offset == 0 && bias == Bias::Left {
1544            Anchor::min()
1545        } else {
1546            Anchor::max()
1547        }
1548    }
1549
1550    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1551        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1552        cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1553        if let Some(excerpt) = cursor.item() {
1554            if excerpt.id == excerpt_id {
1555                let text_anchor = excerpt.clip_anchor(text_anchor);
1556                drop(cursor);
1557                return Anchor {
1558                    buffer_id: excerpt.buffer_id,
1559                    excerpt_id,
1560                    text_anchor,
1561                };
1562            }
1563        }
1564        panic!("excerpt not found");
1565    }
1566
1567    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1568        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
1569            true
1570        } else if let Some((buffer_id, buffer_snapshot)) =
1571            self.buffer_snapshot_for_excerpt(&anchor.excerpt_id)
1572        {
1573            anchor.buffer_id == buffer_id && buffer_snapshot.can_resolve(&anchor.text_anchor)
1574        } else {
1575            false
1576        }
1577    }
1578
1579    pub fn range_contains_excerpt_boundary<T: ToOffset>(&self, range: Range<T>) -> bool {
1580        let start = range.start.to_offset(self);
1581        let end = range.end.to_offset(self);
1582        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1583        cursor.seek(&start, Bias::Right, &());
1584        let start_id = cursor
1585            .item()
1586            .or_else(|| cursor.prev_item())
1587            .map(|excerpt| &excerpt.id);
1588        cursor.seek_forward(&end, Bias::Right, &());
1589        let end_id = cursor
1590            .item()
1591            .or_else(|| cursor.prev_item())
1592            .map(|excerpt| &excerpt.id);
1593        start_id != end_id
1594    }
1595
1596    pub fn parse_count(&self) -> usize {
1597        self.parse_count
1598    }
1599
1600    pub fn enclosing_bracket_ranges<T: ToOffset>(
1601        &self,
1602        range: Range<T>,
1603    ) -> Option<(Range<usize>, Range<usize>)> {
1604        let range = range.start.to_offset(self)..range.end.to_offset(self);
1605
1606        let mut cursor = self.excerpts.cursor::<usize>();
1607        cursor.seek(&range.start, Bias::Right, &());
1608        let start_excerpt = cursor.item();
1609
1610        cursor.seek(&range.end, Bias::Right, &());
1611        let end_excerpt = cursor.item();
1612
1613        start_excerpt
1614            .zip(end_excerpt)
1615            .and_then(|(start_excerpt, end_excerpt)| {
1616                if start_excerpt.id != end_excerpt.id {
1617                    return None;
1618                }
1619
1620                let excerpt_buffer_start =
1621                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1622                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1623
1624                let start_in_buffer =
1625                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1626                let end_in_buffer =
1627                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1628                let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1629                    .buffer
1630                    .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1631
1632                if start_bracket_range.start >= excerpt_buffer_start
1633                    && end_bracket_range.end < excerpt_buffer_end
1634                {
1635                    start_bracket_range.start =
1636                        cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
1637                    start_bracket_range.end =
1638                        cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
1639                    end_bracket_range.start =
1640                        cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
1641                    end_bracket_range.end =
1642                        cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
1643                    Some((start_bracket_range, end_bracket_range))
1644                } else {
1645                    None
1646                }
1647            })
1648    }
1649
1650    pub fn diagnostics_update_count(&self) -> usize {
1651        self.diagnostics_update_count
1652    }
1653
1654    pub fn language(&self) -> Option<&Arc<Language>> {
1655        self.excerpts
1656            .iter()
1657            .next()
1658            .and_then(|excerpt| excerpt.buffer.language())
1659    }
1660
1661    pub fn is_dirty(&self) -> bool {
1662        self.is_dirty
1663    }
1664
1665    pub fn has_conflict(&self) -> bool {
1666        self.has_conflict
1667    }
1668
1669    pub fn diagnostic_group<'a, O>(
1670        &'a self,
1671        group_id: usize,
1672    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1673    where
1674        O: text::FromAnchor + 'a,
1675    {
1676        self.as_singleton()
1677            .into_iter()
1678            .flat_map(move |buffer| buffer.diagnostic_group(group_id))
1679    }
1680
1681    pub fn diagnostics_in_range<'a, T, O>(
1682        &'a self,
1683        range: Range<T>,
1684    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1685    where
1686        T: 'a + ToOffset,
1687        O: 'a + text::FromAnchor,
1688    {
1689        self.as_singleton().into_iter().flat_map(move |buffer| {
1690            buffer.diagnostics_in_range(range.start.to_offset(self)..range.end.to_offset(self))
1691        })
1692    }
1693
1694    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1695        let range = range.start.to_offset(self)..range.end.to_offset(self);
1696
1697        let mut cursor = self.excerpts.cursor::<usize>();
1698        cursor.seek(&range.start, Bias::Right, &());
1699        let start_excerpt = cursor.item();
1700
1701        cursor.seek(&range.end, Bias::Right, &());
1702        let end_excerpt = cursor.item();
1703
1704        start_excerpt
1705            .zip(end_excerpt)
1706            .and_then(|(start_excerpt, end_excerpt)| {
1707                if start_excerpt.id != end_excerpt.id {
1708                    return None;
1709                }
1710
1711                let excerpt_buffer_start =
1712                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1713                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes;
1714
1715                let start_in_buffer =
1716                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
1717                let end_in_buffer =
1718                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
1719                let mut ancestor_buffer_range = start_excerpt
1720                    .buffer
1721                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1722                ancestor_buffer_range.start =
1723                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1724                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1725
1726                let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
1727                let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
1728                Some(start..end)
1729            })
1730    }
1731
1732    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1733        let buffer = self.as_singleton()?;
1734        let outline = buffer.outline(theme)?;
1735        let excerpt_id = &self.excerpts.iter().next().unwrap().id;
1736        Some(Outline::new(
1737            outline
1738                .items
1739                .into_iter()
1740                .map(|item| OutlineItem {
1741                    depth: item.depth,
1742                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
1743                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
1744                    text: item.text,
1745                    highlight_ranges: item.highlight_ranges,
1746                    name_ranges: item.name_ranges,
1747                })
1748                .collect(),
1749        ))
1750    }
1751
1752    fn buffer_snapshot_for_excerpt<'a>(
1753        &'a self,
1754        excerpt_id: &'a ExcerptId,
1755    ) -> Option<(usize, &'a BufferSnapshot)> {
1756        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1757        cursor.seek(&Some(excerpt_id), Bias::Left, &());
1758        if let Some(excerpt) = cursor.item() {
1759            if excerpt.id == *excerpt_id {
1760                return Some((excerpt.buffer_id, &excerpt.buffer));
1761            }
1762        }
1763        None
1764    }
1765
1766    pub fn remote_selections_in_range<'a>(
1767        &'a self,
1768        range: &'a Range<Anchor>,
1769    ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1770        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1771        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1772        cursor
1773            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1774            .flat_map(move |excerpt| {
1775                let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1776                if excerpt.id == range.start.excerpt_id {
1777                    query_range.start = range.start.text_anchor.clone();
1778                }
1779                if excerpt.id == range.end.excerpt_id {
1780                    query_range.end = range.end.text_anchor.clone();
1781                }
1782
1783                excerpt
1784                    .buffer
1785                    .remote_selections_in_range(query_range)
1786                    .flat_map(move |(replica_id, selections)| {
1787                        selections.map(move |selection| {
1788                            let mut start = Anchor {
1789                                buffer_id: excerpt.buffer_id,
1790                                excerpt_id: excerpt.id.clone(),
1791                                text_anchor: selection.start.clone(),
1792                            };
1793                            let mut end = Anchor {
1794                                buffer_id: excerpt.buffer_id,
1795                                excerpt_id: excerpt.id.clone(),
1796                                text_anchor: selection.end.clone(),
1797                            };
1798                            if range.start.cmp(&start, self).unwrap().is_gt() {
1799                                start = range.start.clone();
1800                            }
1801                            if range.end.cmp(&end, self).unwrap().is_lt() {
1802                                end = range.end.clone();
1803                            }
1804
1805                            (
1806                                replica_id,
1807                                Selection {
1808                                    id: selection.id,
1809                                    start,
1810                                    end,
1811                                    reversed: selection.reversed,
1812                                    goal: selection.goal,
1813                                },
1814                            )
1815                        })
1816                    })
1817            })
1818    }
1819}
1820
1821impl History {
1822    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
1823        self.transaction_depth += 1;
1824        if self.transaction_depth == 1 {
1825            let id = post_inc(&mut self.next_transaction_id);
1826            self.undo_stack.push(Transaction {
1827                id,
1828                buffer_transactions: Default::default(),
1829                first_edit_at: now,
1830                last_edit_at: now,
1831            });
1832            Some(id)
1833        } else {
1834            None
1835        }
1836    }
1837
1838    fn end_transaction(
1839        &mut self,
1840        now: Instant,
1841        buffer_transactions: HashSet<(usize, TransactionId)>,
1842    ) -> bool {
1843        assert_ne!(self.transaction_depth, 0);
1844        self.transaction_depth -= 1;
1845        if self.transaction_depth == 0 {
1846            if buffer_transactions.is_empty() {
1847                self.undo_stack.pop();
1848                false
1849            } else {
1850                let transaction = self.undo_stack.last_mut().unwrap();
1851                transaction.last_edit_at = now;
1852                transaction.buffer_transactions.extend(buffer_transactions);
1853                true
1854            }
1855        } else {
1856            false
1857        }
1858    }
1859
1860    fn pop_undo(&mut self) -> Option<&Transaction> {
1861        assert_eq!(self.transaction_depth, 0);
1862        if let Some(transaction) = self.undo_stack.pop() {
1863            self.redo_stack.push(transaction);
1864            self.redo_stack.last()
1865        } else {
1866            None
1867        }
1868    }
1869
1870    fn pop_redo(&mut self) -> Option<&Transaction> {
1871        assert_eq!(self.transaction_depth, 0);
1872        if let Some(transaction) = self.redo_stack.pop() {
1873            self.undo_stack.push(transaction);
1874            self.undo_stack.last()
1875        } else {
1876            None
1877        }
1878    }
1879
1880    fn group(&mut self) -> Option<TransactionId> {
1881        let mut new_len = self.undo_stack.len();
1882        let mut transactions = self.undo_stack.iter_mut();
1883
1884        if let Some(mut transaction) = transactions.next_back() {
1885            while let Some(prev_transaction) = transactions.next_back() {
1886                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
1887                {
1888                    transaction = prev_transaction;
1889                    new_len -= 1;
1890                } else {
1891                    break;
1892                }
1893            }
1894        }
1895
1896        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
1897        if let Some(last_transaction) = transactions_to_keep.last_mut() {
1898            if let Some(transaction) = transactions_to_merge.last() {
1899                last_transaction.last_edit_at = transaction.last_edit_at;
1900            }
1901        }
1902
1903        self.undo_stack.truncate(new_len);
1904        self.undo_stack.last().map(|t| t.id)
1905    }
1906}
1907
1908impl Excerpt {
1909    fn new(
1910        id: ExcerptId,
1911        buffer_id: usize,
1912        buffer: BufferSnapshot,
1913        range: Range<text::Anchor>,
1914        has_trailing_newline: bool,
1915    ) -> Self {
1916        Excerpt {
1917            id,
1918            max_buffer_row: range.end.to_point(&buffer).row,
1919            text_summary: buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer)),
1920            buffer_id,
1921            buffer,
1922            range,
1923            has_trailing_newline,
1924        }
1925    }
1926
1927    fn chunks_in_range<'a>(
1928        &'a self,
1929        range: Range<usize>,
1930        theme: Option<&'a SyntaxTheme>,
1931    ) -> ExcerptChunks<'a> {
1932        let content_start = self.range.start.to_offset(&self.buffer);
1933        let chunks_start = content_start + range.start;
1934        let chunks_end = content_start + cmp::min(range.end, self.text_summary.bytes);
1935
1936        let footer_height = if self.has_trailing_newline
1937            && range.start <= self.text_summary.bytes
1938            && range.end > self.text_summary.bytes
1939        {
1940            1
1941        } else {
1942            0
1943        };
1944
1945        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, theme);
1946
1947        ExcerptChunks {
1948            content_chunks,
1949            footer_height,
1950        }
1951    }
1952
1953    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
1954        let content_start = self.range.start.to_offset(&self.buffer);
1955        let bytes_start = content_start + range.start;
1956        let bytes_end = content_start + cmp::min(range.end, self.text_summary.bytes);
1957        let footer_height = if self.has_trailing_newline
1958            && range.start <= self.text_summary.bytes
1959            && range.end > self.text_summary.bytes
1960        {
1961            1
1962        } else {
1963            0
1964        };
1965        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
1966
1967        ExcerptBytes {
1968            content_bytes,
1969            footer_height,
1970        }
1971    }
1972
1973    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
1974        if text_anchor
1975            .cmp(&self.range.start, &self.buffer)
1976            .unwrap()
1977            .is_lt()
1978        {
1979            self.range.start.clone()
1980        } else if text_anchor
1981            .cmp(&self.range.end, &self.buffer)
1982            .unwrap()
1983            .is_gt()
1984        {
1985            self.range.end.clone()
1986        } else {
1987            text_anchor
1988        }
1989    }
1990
1991    fn contains(&self, anchor: &Anchor) -> bool {
1992        self.buffer_id == anchor.buffer_id
1993            && self
1994                .range
1995                .start
1996                .cmp(&anchor.text_anchor, &self.buffer)
1997                .unwrap()
1998                .is_le()
1999            && self
2000                .range
2001                .end
2002                .cmp(&anchor.text_anchor, &self.buffer)
2003                .unwrap()
2004                .is_ge()
2005    }
2006}
2007
2008impl fmt::Debug for Excerpt {
2009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2010        f.debug_struct("Excerpt")
2011            .field("id", &self.id)
2012            .field("buffer_id", &self.buffer_id)
2013            .field("range", &self.range)
2014            .field("text_summary", &self.text_summary)
2015            .field("has_trailing_newline", &self.has_trailing_newline)
2016            .finish()
2017    }
2018}
2019
2020impl sum_tree::Item for Excerpt {
2021    type Summary = ExcerptSummary;
2022
2023    fn summary(&self) -> Self::Summary {
2024        let mut text = self.text_summary.clone();
2025        if self.has_trailing_newline {
2026            text += TextSummary::from("\n");
2027        }
2028        ExcerptSummary {
2029            excerpt_id: self.id.clone(),
2030            max_buffer_row: self.max_buffer_row,
2031            text,
2032        }
2033    }
2034}
2035
2036impl sum_tree::Summary for ExcerptSummary {
2037    type Context = ();
2038
2039    fn add_summary(&mut self, summary: &Self, _: &()) {
2040        debug_assert!(summary.excerpt_id > self.excerpt_id);
2041        self.excerpt_id = summary.excerpt_id.clone();
2042        self.text.add_summary(&summary.text, &());
2043        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2044    }
2045}
2046
2047impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2048    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2049        *self += &summary.text;
2050    }
2051}
2052
2053impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2054    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2055        *self += summary.text.bytes;
2056    }
2057}
2058
2059impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2060    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2061        Ord::cmp(self, &cursor_location.text.bytes)
2062    }
2063}
2064
2065impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2066    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2067        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2068    }
2069}
2070
2071impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2072    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2073        *self += summary.text.lines;
2074    }
2075}
2076
2077impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2078    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2079        *self += summary.text.lines_utf16
2080    }
2081}
2082
2083impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2084    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2085        *self = Some(&summary.excerpt_id);
2086    }
2087}
2088
2089impl<'a> MultiBufferRows<'a> {
2090    pub fn seek(&mut self, row: u32) {
2091        self.buffer_row_range = 0..0;
2092
2093        self.excerpts
2094            .seek_forward(&Point::new(row, 0), Bias::Right, &());
2095        if self.excerpts.item().is_none() {
2096            self.excerpts.prev(&());
2097
2098            if self.excerpts.item().is_none() && row == 0 {
2099                self.buffer_row_range = 0..1;
2100                return;
2101            }
2102        }
2103
2104        if let Some(excerpt) = self.excerpts.item() {
2105            let overshoot = row - self.excerpts.start().row;
2106            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
2107            self.buffer_row_range.start = excerpt_start + overshoot;
2108            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
2109        }
2110    }
2111}
2112
2113impl<'a> Iterator for MultiBufferRows<'a> {
2114    type Item = Option<u32>;
2115
2116    fn next(&mut self) -> Option<Self::Item> {
2117        loop {
2118            if !self.buffer_row_range.is_empty() {
2119                let row = Some(self.buffer_row_range.start);
2120                self.buffer_row_range.start += 1;
2121                return Some(row);
2122            }
2123            self.excerpts.item()?;
2124            self.excerpts.next(&());
2125            let excerpt = self.excerpts.item()?;
2126            self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
2127            self.buffer_row_range.end =
2128                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
2129        }
2130    }
2131}
2132
2133impl<'a> MultiBufferChunks<'a> {
2134    pub fn offset(&self) -> usize {
2135        self.range.start
2136    }
2137
2138    pub fn seek(&mut self, offset: usize) {
2139        self.range.start = offset;
2140        self.excerpts.seek(&offset, Bias::Right, &());
2141        if let Some(excerpt) = self.excerpts.item() {
2142            self.excerpt_chunks = Some(excerpt.chunks_in_range(
2143                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
2144                self.theme,
2145            ));
2146        } else {
2147            self.excerpt_chunks = None;
2148        }
2149    }
2150}
2151
2152impl<'a> Iterator for MultiBufferChunks<'a> {
2153    type Item = Chunk<'a>;
2154
2155    fn next(&mut self) -> Option<Self::Item> {
2156        if self.range.is_empty() {
2157            None
2158        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2159            self.range.start += chunk.text.len();
2160            Some(chunk)
2161        } else {
2162            self.excerpts.next(&());
2163            let excerpt = self.excerpts.item()?;
2164            self.excerpt_chunks = Some(
2165                excerpt.chunks_in_range(0..self.range.end - self.excerpts.start(), self.theme),
2166            );
2167            self.next()
2168        }
2169    }
2170}
2171
2172impl<'a> MultiBufferBytes<'a> {
2173    fn consume(&mut self, len: usize) {
2174        self.range.start += len;
2175        self.chunk = &self.chunk[len..];
2176
2177        if !self.range.is_empty() && self.chunk.is_empty() {
2178            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2179                self.chunk = chunk;
2180            } else {
2181                self.excerpts.next(&());
2182                if let Some(excerpt) = self.excerpts.item() {
2183                    let mut excerpt_bytes =
2184                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2185                    self.chunk = excerpt_bytes.next().unwrap();
2186                    self.excerpt_bytes = Some(excerpt_bytes);
2187                }
2188            }
2189        }
2190    }
2191}
2192
2193impl<'a> Iterator for MultiBufferBytes<'a> {
2194    type Item = &'a [u8];
2195
2196    fn next(&mut self) -> Option<Self::Item> {
2197        let chunk = self.chunk;
2198        if chunk.is_empty() {
2199            None
2200        } else {
2201            self.consume(chunk.len());
2202            Some(chunk)
2203        }
2204    }
2205}
2206
2207impl<'a> io::Read for MultiBufferBytes<'a> {
2208    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2209        let len = cmp::min(buf.len(), self.chunk.len());
2210        buf[..len].copy_from_slice(&self.chunk[..len]);
2211        if len > 0 {
2212            self.consume(len);
2213        }
2214        Ok(len)
2215    }
2216}
2217
2218impl<'a> Iterator for ExcerptBytes<'a> {
2219    type Item = &'a [u8];
2220
2221    fn next(&mut self) -> Option<Self::Item> {
2222        if let Some(chunk) = self.content_bytes.next() {
2223            if !chunk.is_empty() {
2224                return Some(chunk);
2225            }
2226        }
2227
2228        if self.footer_height > 0 {
2229            let result = &NEWLINES[..self.footer_height];
2230            self.footer_height = 0;
2231            return Some(result);
2232        }
2233
2234        None
2235    }
2236}
2237
2238impl<'a> Iterator for ExcerptChunks<'a> {
2239    type Item = Chunk<'a>;
2240
2241    fn next(&mut self) -> Option<Self::Item> {
2242        if let Some(chunk) = self.content_chunks.next() {
2243            return Some(chunk);
2244        }
2245
2246        if self.footer_height > 0 {
2247            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2248            self.footer_height = 0;
2249            return Some(Chunk {
2250                text,
2251                ..Default::default()
2252            });
2253        }
2254
2255        None
2256    }
2257}
2258
2259impl ToOffset for Point {
2260    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2261        snapshot.point_to_offset(*self)
2262    }
2263}
2264
2265impl ToOffset for PointUtf16 {
2266    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2267        snapshot.point_utf16_to_offset(*self)
2268    }
2269}
2270
2271impl ToOffset for usize {
2272    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2273        assert!(*self <= snapshot.len(), "offset is out of range");
2274        *self
2275    }
2276}
2277
2278impl ToPoint for usize {
2279    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2280        snapshot.offset_to_point(*self)
2281    }
2282}
2283
2284impl ToPoint for Point {
2285    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2286        *self
2287    }
2288}
2289
2290#[cfg(test)]
2291mod tests {
2292    use super::*;
2293    use gpui::MutableAppContext;
2294    use language::{Buffer, Rope};
2295    use rand::prelude::*;
2296    use std::env;
2297    use text::{Point, RandomCharIter};
2298    use util::test::sample_text;
2299
2300    #[gpui::test]
2301    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2302        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2303        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2304
2305        let snapshot = multibuffer.read(cx).snapshot(cx);
2306        assert_eq!(snapshot.text(), buffer.read(cx).text());
2307
2308        assert_eq!(
2309            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2310            (0..buffer.read(cx).row_count())
2311                .map(Some)
2312                .collect::<Vec<_>>()
2313        );
2314
2315        buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2316        let snapshot = multibuffer.read(cx).snapshot(cx);
2317
2318        assert_eq!(snapshot.text(), buffer.read(cx).text());
2319        assert_eq!(
2320            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2321            (0..buffer.read(cx).row_count())
2322                .map(Some)
2323                .collect::<Vec<_>>()
2324        );
2325    }
2326
2327    #[gpui::test]
2328    fn test_remote_multibuffer(cx: &mut MutableAppContext) {
2329        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
2330        let guest_buffer = cx.add_model(|cx| {
2331            let message = host_buffer.read(cx).to_proto();
2332            Buffer::from_proto(1, message, None, cx).unwrap()
2333        });
2334        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
2335        let snapshot = multibuffer.read(cx).snapshot(cx);
2336        assert_eq!(snapshot.text(), "a");
2337
2338        guest_buffer.update(cx, |buffer, cx| buffer.edit([1..1], "b", cx));
2339        let snapshot = multibuffer.read(cx).snapshot(cx);
2340        assert_eq!(snapshot.text(), "ab");
2341
2342        guest_buffer.update(cx, |buffer, cx| buffer.edit([2..2], "c", cx));
2343        let snapshot = multibuffer.read(cx).snapshot(cx);
2344        assert_eq!(snapshot.text(), "abc");
2345    }
2346
2347    #[gpui::test]
2348    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2349        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2350        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2351        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2352
2353        let subscription = multibuffer.update(cx, |multibuffer, cx| {
2354            let subscription = multibuffer.subscribe();
2355            multibuffer.push_excerpt(
2356                ExcerptProperties {
2357                    buffer: &buffer_1,
2358                    range: Point::new(1, 2)..Point::new(2, 5),
2359                },
2360                cx,
2361            );
2362            assert_eq!(
2363                subscription.consume().into_inner(),
2364                [Edit {
2365                    old: 0..0,
2366                    new: 0..10
2367                }]
2368            );
2369
2370            multibuffer.push_excerpt(
2371                ExcerptProperties {
2372                    buffer: &buffer_1,
2373                    range: Point::new(3, 3)..Point::new(4, 4),
2374                },
2375                cx,
2376            );
2377            multibuffer.push_excerpt(
2378                ExcerptProperties {
2379                    buffer: &buffer_2,
2380                    range: Point::new(3, 1)..Point::new(3, 3),
2381                },
2382                cx,
2383            );
2384            assert_eq!(
2385                subscription.consume().into_inner(),
2386                [Edit {
2387                    old: 10..10,
2388                    new: 10..22
2389                }]
2390            );
2391
2392            subscription
2393        });
2394
2395        let snapshot = multibuffer.read(cx).snapshot(cx);
2396        assert_eq!(
2397            snapshot.text(),
2398            concat!(
2399                "bbbb\n",  // Preserve newlines
2400                "ccccc\n", //
2401                "ddd\n",   //
2402                "eeee\n",  //
2403                "jj"       //
2404            )
2405        );
2406        assert_eq!(
2407            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2408            [Some(1), Some(2), Some(3), Some(4), Some(3)]
2409        );
2410        assert_eq!(
2411            snapshot.buffer_rows(2).collect::<Vec<_>>(),
2412            [Some(3), Some(4), Some(3)]
2413        );
2414        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
2415        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
2416        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(1, 5)));
2417        assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(2, 0)));
2418        assert!(snapshot.range_contains_excerpt_boundary(Point::new(1, 0)..Point::new(4, 0)));
2419        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(2, 0)..Point::new(3, 0)));
2420        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 0)..Point::new(4, 2)));
2421        assert!(!snapshot.range_contains_excerpt_boundary(Point::new(4, 2)..Point::new(4, 2)));
2422
2423        buffer_1.update(cx, |buffer, cx| {
2424            buffer.edit(
2425                [
2426                    Point::new(0, 0)..Point::new(0, 0),
2427                    Point::new(2, 1)..Point::new(2, 3),
2428                ],
2429                "\n",
2430                cx,
2431            );
2432        });
2433
2434        let snapshot = multibuffer.read(cx).snapshot(cx);
2435        assert_eq!(
2436            snapshot.text(),
2437            concat!(
2438                "bbbb\n", // Preserve newlines
2439                "c\n",    //
2440                "cc\n",   //
2441                "ddd\n",  //
2442                "eeee\n", //
2443                "jj"      //
2444            )
2445        );
2446
2447        assert_eq!(
2448            subscription.consume().into_inner(),
2449            [Edit {
2450                old: 6..8,
2451                new: 6..7
2452            }]
2453        );
2454
2455        let snapshot = multibuffer.read(cx).snapshot(cx);
2456        assert_eq!(
2457            snapshot.clip_point(Point::new(0, 5), Bias::Left),
2458            Point::new(0, 4)
2459        );
2460        assert_eq!(
2461            snapshot.clip_point(Point::new(0, 5), Bias::Right),
2462            Point::new(0, 4)
2463        );
2464        assert_eq!(
2465            snapshot.clip_point(Point::new(5, 1), Bias::Right),
2466            Point::new(5, 1)
2467        );
2468        assert_eq!(
2469            snapshot.clip_point(Point::new(5, 2), Bias::Right),
2470            Point::new(5, 2)
2471        );
2472        assert_eq!(
2473            snapshot.clip_point(Point::new(5, 3), Bias::Right),
2474            Point::new(5, 2)
2475        );
2476
2477        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
2478            let buffer_2_excerpt_id = multibuffer.excerpt_ids_for_buffer(&buffer_2)[0].clone();
2479            multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
2480            multibuffer.snapshot(cx)
2481        });
2482
2483        assert_eq!(
2484            snapshot.text(),
2485            concat!(
2486                "bbbb\n", // Preserve newlines
2487                "c\n",    //
2488                "cc\n",   //
2489                "ddd\n",  //
2490                "eeee",   //
2491            )
2492        );
2493    }
2494
2495    #[gpui::test]
2496    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2497        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2498
2499        let snapshot = multibuffer.read(cx).snapshot(cx);
2500        assert_eq!(snapshot.text(), "");
2501        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2502        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2503    }
2504
2505    #[gpui::test]
2506    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2507        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2508        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2509        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2510        buffer.update(cx, |buffer, cx| {
2511            buffer.edit([0..0], "X", cx);
2512            buffer.edit([5..5], "Y", cx);
2513        });
2514        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2515
2516        assert_eq!(old_snapshot.text(), "abcd");
2517        assert_eq!(new_snapshot.text(), "XabcdY");
2518
2519        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2520        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2521        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2522        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2523    }
2524
2525    #[gpui::test]
2526    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2527        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2528        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2529        let multibuffer = cx.add_model(|cx| {
2530            let mut multibuffer = MultiBuffer::new(0);
2531            multibuffer.push_excerpt(
2532                ExcerptProperties {
2533                    buffer: &buffer_1,
2534                    range: 0..4,
2535                },
2536                cx,
2537            );
2538            multibuffer.push_excerpt(
2539                ExcerptProperties {
2540                    buffer: &buffer_2,
2541                    range: 0..5,
2542                },
2543                cx,
2544            );
2545            multibuffer
2546        });
2547        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2548
2549        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
2550        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
2551        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2552        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
2553        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2554        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
2555
2556        buffer_1.update(cx, |buffer, cx| {
2557            buffer.edit([0..0], "W", cx);
2558            buffer.edit([5..5], "X", cx);
2559        });
2560        buffer_2.update(cx, |buffer, cx| {
2561            buffer.edit([0..0], "Y", cx);
2562            buffer.edit([6..0], "Z", cx);
2563        });
2564        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2565
2566        assert_eq!(old_snapshot.text(), "abcd\nefghi");
2567        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
2568
2569        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2570        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2571        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
2572        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2573        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2574        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2575        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
2576        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
2577        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
2578        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
2579    }
2580
2581    #[gpui::test]
2582    fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
2583        cx: &mut MutableAppContext,
2584    ) {
2585        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2586        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
2587        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2588
2589        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
2590        // Add an excerpt from buffer 1 that spans this new insertion.
2591        buffer_1.update(cx, |buffer, cx| buffer.edit([4..4], "123", cx));
2592        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
2593            multibuffer.push_excerpt(
2594                ExcerptProperties {
2595                    buffer: &buffer_1,
2596                    range: 0..7,
2597                },
2598                cx,
2599            )
2600        });
2601
2602        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
2603        assert_eq!(snapshot_1.text(), "abcd123");
2604
2605        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
2606        let (excerpt_id_2, excerpt_id_3, _) = multibuffer.update(cx, |multibuffer, cx| {
2607            multibuffer.remove_excerpts([&excerpt_id_1], cx);
2608            (
2609                multibuffer.push_excerpt(
2610                    ExcerptProperties {
2611                        buffer: &buffer_2,
2612                        range: 0..4,
2613                    },
2614                    cx,
2615                ),
2616                multibuffer.push_excerpt(
2617                    ExcerptProperties {
2618                        buffer: &buffer_2,
2619                        range: 6..10,
2620                    },
2621                    cx,
2622                ),
2623                multibuffer.push_excerpt(
2624                    ExcerptProperties {
2625                        buffer: &buffer_2,
2626                        range: 12..16,
2627                    },
2628                    cx,
2629                ),
2630            )
2631        });
2632        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
2633        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
2634
2635        // The old excerpt id has been reused.
2636        assert_eq!(excerpt_id_2, excerpt_id_1);
2637
2638        // Resolve some anchors from the previous snapshot in the new snapshot.
2639        // Although there is still an excerpt with the same id, it is for
2640        // a different buffer, so we don't attempt to resolve the old text
2641        // anchor in the new buffer.
2642        assert_eq!(
2643            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
2644            0
2645        );
2646        assert_eq!(
2647            snapshot_2.summaries_for_anchors::<usize, _>(&[
2648                snapshot_1.anchor_before(2),
2649                snapshot_1.anchor_after(3)
2650            ]),
2651            vec![0, 0]
2652        );
2653        let refresh =
2654            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
2655        assert_eq!(
2656            refresh,
2657            &[
2658                (0, snapshot_2.anchor_before(0), false),
2659                (1, snapshot_2.anchor_after(0), false),
2660            ]
2661        );
2662
2663        // Replace the middle excerpt with a smaller excerpt in buffer 2,
2664        // that intersects the old excerpt.
2665        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
2666            multibuffer.remove_excerpts([&excerpt_id_3], cx);
2667            multibuffer.insert_excerpt_after(
2668                &excerpt_id_3,
2669                ExcerptProperties {
2670                    buffer: &buffer_2,
2671                    range: 5..8,
2672                },
2673                cx,
2674            )
2675        });
2676
2677        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
2678        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
2679        assert_ne!(excerpt_id_5, excerpt_id_3);
2680
2681        // Resolve some anchors from the previous snapshot in the new snapshot.
2682        // The anchor in the middle excerpt snaps to the beginning of the
2683        // excerpt, since it is not
2684        let anchors = [
2685            snapshot_2.anchor_before(0),
2686            snapshot_2.anchor_after(2),
2687            snapshot_2.anchor_after(6),
2688            snapshot_2.anchor_after(14),
2689        ];
2690        assert_eq!(
2691            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
2692            &[0, 2, 9, 13]
2693        );
2694
2695        let new_anchors = snapshot_3.refresh_anchors(&anchors);
2696        assert_eq!(
2697            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
2698            &[(0, true), (1, true), (2, true), (3, true)]
2699        );
2700        assert_eq!(
2701            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
2702            &[0, 2, 7, 13]
2703        );
2704    }
2705
2706    #[gpui::test(iterations = 100)]
2707    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
2708        let operations = env::var("OPERATIONS")
2709            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2710            .unwrap_or(10);
2711
2712        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2713        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2714        let mut excerpt_ids = Vec::new();
2715        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
2716        let mut anchors = Vec::new();
2717        let mut old_versions = Vec::new();
2718
2719        for _ in 0..operations {
2720            match rng.gen_range(0..100) {
2721                0..=19 if !buffers.is_empty() => {
2722                    let buffer = buffers.choose(&mut rng).unwrap();
2723                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2724                }
2725                20..=29 if !expected_excerpts.is_empty() => {
2726                    let mut ids_to_remove = vec![];
2727                    for _ in 0..rng.gen_range(1..=3) {
2728                        if expected_excerpts.is_empty() {
2729                            break;
2730                        }
2731
2732                        let ix = rng.gen_range(0..expected_excerpts.len());
2733                        ids_to_remove.push(excerpt_ids.remove(ix));
2734                        let (buffer, range) = expected_excerpts.remove(ix);
2735                        let buffer = buffer.read(cx);
2736                        log::info!(
2737                            "Removing excerpt {}: {:?}",
2738                            ix,
2739                            buffer
2740                                .text_for_range(range.to_offset(&buffer))
2741                                .collect::<String>(),
2742                        );
2743                    }
2744                    ids_to_remove.sort_unstable();
2745                    multibuffer.update(cx, |multibuffer, cx| {
2746                        multibuffer.remove_excerpts(&ids_to_remove, cx)
2747                    });
2748                }
2749                30..=39 if !expected_excerpts.is_empty() => {
2750                    let multibuffer = multibuffer.read(cx).read(cx);
2751                    let offset =
2752                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2753                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
2754                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2755                    anchors.push(multibuffer.anchor_at(offset, bias));
2756                    anchors.sort_by(|a, b| a.cmp(&b, &multibuffer).unwrap());
2757                }
2758                40..=44 if !anchors.is_empty() => {
2759                    let multibuffer = multibuffer.read(cx).read(cx);
2760                    anchors = multibuffer
2761                        .refresh_anchors(&anchors)
2762                        .into_iter()
2763                        .map(|a| a.1)
2764                        .collect();
2765                }
2766                _ => {
2767                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2768                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2769                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2770                        buffers.last().unwrap()
2771                    } else {
2772                        buffers.choose(&mut rng).unwrap()
2773                    };
2774
2775                    let buffer = buffer_handle.read(cx);
2776                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2777                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2778                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2779                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
2780                    let prev_excerpt_id = excerpt_ids
2781                        .get(prev_excerpt_ix)
2782                        .cloned()
2783                        .unwrap_or(ExcerptId::max());
2784                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
2785
2786                    log::info!(
2787                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2788                        excerpt_ix,
2789                        expected_excerpts.len(),
2790                        buffer_handle.id(),
2791                        buffer.text(),
2792                        start_ix..end_ix,
2793                        &buffer.text()[start_ix..end_ix]
2794                    );
2795
2796                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2797                        multibuffer.insert_excerpt_after(
2798                            &prev_excerpt_id,
2799                            ExcerptProperties {
2800                                buffer: &buffer_handle,
2801                                range: start_ix..end_ix,
2802                            },
2803                            cx,
2804                        )
2805                    });
2806
2807                    excerpt_ids.insert(excerpt_ix, excerpt_id);
2808                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
2809                }
2810            }
2811
2812            if rng.gen_bool(0.3) {
2813                multibuffer.update(cx, |multibuffer, cx| {
2814                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2815                })
2816            }
2817
2818            let snapshot = multibuffer.read(cx).snapshot(cx);
2819
2820            let mut excerpt_starts = Vec::new();
2821            let mut expected_text = String::new();
2822            let mut expected_buffer_rows = Vec::new();
2823            for (buffer, range) in &expected_excerpts {
2824                let buffer = buffer.read(cx);
2825                let buffer_range = range.to_offset(buffer);
2826
2827                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
2828                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
2829                expected_text.push('\n');
2830
2831                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
2832                    ..=buffer.offset_to_point(buffer_range.end).row;
2833                for row in buffer_row_range {
2834                    expected_buffer_rows.push(Some(row));
2835                }
2836            }
2837            // Remove final trailing newline.
2838            if !expected_excerpts.is_empty() {
2839                expected_text.pop();
2840            }
2841
2842            // Always report one buffer row
2843            if expected_buffer_rows.is_empty() {
2844                expected_buffer_rows.push(Some(0));
2845            }
2846
2847            assert_eq!(snapshot.text(), expected_text);
2848            log::info!("MultiBuffer text: {:?}", expected_text);
2849
2850            assert_eq!(
2851                snapshot.buffer_rows(0).collect::<Vec<_>>(),
2852                expected_buffer_rows,
2853            );
2854
2855            for _ in 0..5 {
2856                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
2857                assert_eq!(
2858                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
2859                    &expected_buffer_rows[start_row..],
2860                    "buffer_rows({})",
2861                    start_row
2862                );
2863            }
2864
2865            assert_eq!(
2866                snapshot.max_buffer_row(),
2867                expected_buffer_rows
2868                    .into_iter()
2869                    .filter_map(|r| r)
2870                    .max()
2871                    .unwrap()
2872            );
2873
2874            let mut excerpt_starts = excerpt_starts.into_iter();
2875            for (buffer, range) in &expected_excerpts {
2876                let buffer_id = buffer.id();
2877                let buffer = buffer.read(cx);
2878                let buffer_range = range.to_offset(buffer);
2879                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
2880                let buffer_start_point_utf16 =
2881                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
2882
2883                let excerpt_start = excerpt_starts.next().unwrap();
2884                let mut offset = excerpt_start.bytes;
2885                let mut buffer_offset = buffer_range.start;
2886                let mut point = excerpt_start.lines;
2887                let mut buffer_point = buffer_start_point;
2888                let mut point_utf16 = excerpt_start.lines_utf16;
2889                let mut buffer_point_utf16 = buffer_start_point_utf16;
2890                for ch in buffer
2891                    .snapshot()
2892                    .chunks(buffer_range.clone(), None)
2893                    .flat_map(|c| c.text.chars())
2894                {
2895                    for _ in 0..ch.len_utf8() {
2896                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
2897                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
2898                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
2899                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
2900                        assert_eq!(
2901                            left_offset,
2902                            excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
2903                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
2904                            offset,
2905                            buffer_id,
2906                            buffer_offset,
2907                        );
2908                        assert_eq!(
2909                            right_offset,
2910                            excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
2911                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
2912                            offset,
2913                            buffer_id,
2914                            buffer_offset,
2915                        );
2916
2917                        let left_point = snapshot.clip_point(point, Bias::Left);
2918                        let right_point = snapshot.clip_point(point, Bias::Right);
2919                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
2920                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
2921                        assert_eq!(
2922                            left_point,
2923                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
2924                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
2925                            point,
2926                            buffer_id,
2927                            buffer_point,
2928                        );
2929                        assert_eq!(
2930                            right_point,
2931                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
2932                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
2933                            point,
2934                            buffer_id,
2935                            buffer_point,
2936                        );
2937
2938                        assert_eq!(
2939                            snapshot.point_to_offset(left_point),
2940                            left_offset,
2941                            "point_to_offset({:?})",
2942                            left_point,
2943                        );
2944                        assert_eq!(
2945                            snapshot.offset_to_point(left_offset),
2946                            left_point,
2947                            "offset_to_point({:?})",
2948                            left_offset,
2949                        );
2950
2951                        offset += 1;
2952                        buffer_offset += 1;
2953                        if ch == '\n' {
2954                            point += Point::new(1, 0);
2955                            buffer_point += Point::new(1, 0);
2956                        } else {
2957                            point += Point::new(0, 1);
2958                            buffer_point += Point::new(0, 1);
2959                        }
2960                    }
2961
2962                    for _ in 0..ch.len_utf16() {
2963                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
2964                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
2965                        let buffer_left_point_utf16 =
2966                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
2967                        let buffer_right_point_utf16 =
2968                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
2969                        assert_eq!(
2970                            left_point_utf16,
2971                            excerpt_start.lines_utf16
2972                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
2973                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
2974                            point_utf16,
2975                            buffer_id,
2976                            buffer_point_utf16,
2977                        );
2978                        assert_eq!(
2979                            right_point_utf16,
2980                            excerpt_start.lines_utf16
2981                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
2982                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
2983                            point_utf16,
2984                            buffer_id,
2985                            buffer_point_utf16,
2986                        );
2987
2988                        if ch == '\n' {
2989                            point_utf16 += PointUtf16::new(1, 0);
2990                            buffer_point_utf16 += PointUtf16::new(1, 0);
2991                        } else {
2992                            point_utf16 += PointUtf16::new(0, 1);
2993                            buffer_point_utf16 += PointUtf16::new(0, 1);
2994                        }
2995                    }
2996                }
2997            }
2998
2999            for (row, line) in expected_text.split('\n').enumerate() {
3000                assert_eq!(
3001                    snapshot.line_len(row as u32),
3002                    line.len() as u32,
3003                    "line_len({}).",
3004                    row
3005                );
3006            }
3007
3008            let text_rope = Rope::from(expected_text.as_str());
3009            for _ in 0..10 {
3010                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3011                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3012
3013                let text_for_range = snapshot
3014                    .text_for_range(start_ix..end_ix)
3015                    .collect::<String>();
3016                assert_eq!(
3017                    text_for_range,
3018                    &expected_text[start_ix..end_ix],
3019                    "incorrect text for range {:?}",
3020                    start_ix..end_ix
3021                );
3022
3023                let excerpted_buffer_ranges =
3024                    multibuffer.read(cx).excerpted_buffers(start_ix..end_ix, cx);
3025                let excerpted_buffers_text = excerpted_buffer_ranges
3026                    .into_iter()
3027                    .map(|(buffer, buffer_range)| {
3028                        buffer
3029                            .read(cx)
3030                            .text_for_range(buffer_range)
3031                            .collect::<String>()
3032                    })
3033                    .collect::<Vec<_>>()
3034                    .join("\n");
3035                assert_eq!(excerpted_buffers_text, text_for_range);
3036
3037                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
3038                assert_eq!(
3039                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
3040                    expected_summary,
3041                    "incorrect summary for range {:?}",
3042                    start_ix..end_ix
3043                );
3044            }
3045
3046            // Anchor resolution
3047            for (anchor, resolved_offset) in anchors
3048                .iter()
3049                .zip(snapshot.summaries_for_anchors::<usize, _>(&anchors))
3050            {
3051                assert_eq!(
3052                    snapshot.summary_for_anchor::<usize>(anchor),
3053                    resolved_offset
3054                );
3055            }
3056
3057            for _ in 0..10 {
3058                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
3059                assert_eq!(
3060                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
3061                    expected_text[..end_ix].chars().rev().collect::<String>(),
3062                );
3063            }
3064
3065            for _ in 0..10 {
3066                let end_ix = rng.gen_range(0..=text_rope.len());
3067                let start_ix = rng.gen_range(0..=end_ix);
3068                assert_eq!(
3069                    snapshot
3070                        .bytes_in_range(start_ix..end_ix)
3071                        .flatten()
3072                        .copied()
3073                        .collect::<Vec<_>>(),
3074                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3075                    "bytes_in_range({:?})",
3076                    start_ix..end_ix,
3077                );
3078            }
3079        }
3080
3081        let snapshot = multibuffer.read(cx).snapshot(cx);
3082        for (old_snapshot, subscription) in old_versions {
3083            let edits = subscription.consume().into_inner();
3084
3085            log::info!(
3086                "applying subscription edits to old text: {:?}: {:?}",
3087                old_snapshot.text(),
3088                edits,
3089            );
3090
3091            let mut text = old_snapshot.text();
3092            for edit in edits {
3093                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
3094                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
3095            }
3096            assert_eq!(text.to_string(), snapshot.text());
3097        }
3098    }
3099
3100    #[gpui::test]
3101    fn test_history(cx: &mut MutableAppContext) {
3102        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
3103        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
3104        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3105        let group_interval = multibuffer.read(cx).history.group_interval;
3106        multibuffer.update(cx, |multibuffer, cx| {
3107            multibuffer.push_excerpt(
3108                ExcerptProperties {
3109                    buffer: &buffer_1,
3110                    range: 0..buffer_1.read(cx).len(),
3111                },
3112                cx,
3113            );
3114            multibuffer.push_excerpt(
3115                ExcerptProperties {
3116                    buffer: &buffer_2,
3117                    range: 0..buffer_2.read(cx).len(),
3118                },
3119                cx,
3120            );
3121        });
3122
3123        let mut now = Instant::now();
3124
3125        multibuffer.update(cx, |multibuffer, cx| {
3126            multibuffer.start_transaction_at(now, cx);
3127            multibuffer.edit(
3128                [
3129                    Point::new(0, 0)..Point::new(0, 0),
3130                    Point::new(1, 0)..Point::new(1, 0),
3131                ],
3132                "A",
3133                cx,
3134            );
3135            multibuffer.edit(
3136                [
3137                    Point::new(0, 1)..Point::new(0, 1),
3138                    Point::new(1, 1)..Point::new(1, 1),
3139                ],
3140                "B",
3141                cx,
3142            );
3143            multibuffer.end_transaction_at(now, cx);
3144            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3145
3146            now += 2 * group_interval;
3147            multibuffer.start_transaction_at(now, cx);
3148            multibuffer.edit([2..2], "C", cx);
3149            multibuffer.end_transaction_at(now, cx);
3150            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3151
3152            multibuffer.undo(cx);
3153            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3154
3155            multibuffer.undo(cx);
3156            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3157
3158            multibuffer.redo(cx);
3159            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3160
3161            multibuffer.redo(cx);
3162            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3163
3164            buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
3165            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3166
3167            multibuffer.undo(cx);
3168            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3169
3170            multibuffer.redo(cx);
3171            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3172
3173            multibuffer.redo(cx);
3174            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3175
3176            multibuffer.undo(cx);
3177            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3178
3179            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3180            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3181
3182            multibuffer.undo(cx);
3183            assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
3184        });
3185    }
3186}