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