multi_buffer.rs

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