multi_buffer.rs

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