multi_buffer.rs

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