multi_buffer.rs

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