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