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