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