multi_buffer.rs

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