multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt};
   4use anyhow::Result;
   5use clock::ReplicaId;
   6use collections::{Bound, HashMap, HashSet};
   7use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
   8pub use language::Completion;
   9use language::{
  10    char_kind, 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 indent_size_for_line(&self, row: u32) -> IndentSize {
1943        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1944            let mut size = buffer.indent_size_for_line(range.start.row);
1945            size.len = size
1946                .len
1947                .min(range.end.column)
1948                .saturating_sub(range.start.column);
1949            size
1950        } else {
1951            IndentSize::spaces(0)
1952        }
1953    }
1954
1955    pub fn line_len(&self, row: u32) -> u32 {
1956        if let Some((_, range)) = self.buffer_line_for_row(row) {
1957            range.end.column - range.start.column
1958        } else {
1959            0
1960        }
1961    }
1962
1963    pub fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1964        let mut cursor = self.excerpts.cursor::<Point>();
1965        cursor.seek(&Point::new(row, 0), Bias::Right, &());
1966        if let Some(excerpt) = cursor.item() {
1967            let overshoot = row - cursor.start().row;
1968            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer);
1969            let excerpt_end = excerpt.range.context.end.to_point(&excerpt.buffer);
1970            let buffer_row = excerpt_start.row + overshoot;
1971            let line_start = Point::new(buffer_row, 0);
1972            let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1973            return Some((
1974                &excerpt.buffer,
1975                line_start.max(excerpt_start)..line_end.min(excerpt_end),
1976            ));
1977        }
1978        None
1979    }
1980
1981    pub fn max_point(&self) -> Point {
1982        self.text_summary().lines
1983    }
1984
1985    pub fn text_summary(&self) -> TextSummary {
1986        self.excerpts.summary().text.clone()
1987    }
1988
1989    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1990    where
1991        D: TextDimension,
1992        O: ToOffset,
1993    {
1994        let mut summary = D::default();
1995        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1996        let mut cursor = self.excerpts.cursor::<usize>();
1997        cursor.seek(&range.start, Bias::Right, &());
1998        if let Some(excerpt) = cursor.item() {
1999            let mut end_before_newline = cursor.end(&());
2000            if excerpt.has_trailing_newline {
2001                end_before_newline -= 1;
2002            }
2003
2004            let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2005            let start_in_excerpt = excerpt_start + (range.start - cursor.start());
2006            let end_in_excerpt =
2007                excerpt_start + (cmp::min(end_before_newline, range.end) - cursor.start());
2008            summary.add_assign(
2009                &excerpt
2010                    .buffer
2011                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
2012            );
2013
2014            if range.end > end_before_newline {
2015                summary.add_assign(&D::from_text_summary(&TextSummary::from("\n")));
2016            }
2017
2018            cursor.next(&());
2019        }
2020
2021        if range.end > *cursor.start() {
2022            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
2023                &range.end,
2024                Bias::Right,
2025                &(),
2026            )));
2027            if let Some(excerpt) = cursor.item() {
2028                range.end = cmp::max(*cursor.start(), range.end);
2029
2030                let excerpt_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2031                let end_in_excerpt = excerpt_start + (range.end - cursor.start());
2032                summary.add_assign(
2033                    &excerpt
2034                        .buffer
2035                        .text_summary_for_range(excerpt_start..end_in_excerpt),
2036                );
2037            }
2038        }
2039
2040        summary
2041    }
2042
2043    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2044    where
2045        D: TextDimension + Ord + Sub<D, Output = D>,
2046    {
2047        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2048        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
2049        if cursor.item().is_none() {
2050            cursor.next(&());
2051        }
2052
2053        let mut position = D::from_text_summary(&cursor.start().text);
2054        if let Some(excerpt) = cursor.item() {
2055            if excerpt.id == anchor.excerpt_id {
2056                let excerpt_buffer_start =
2057                    excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2058                let excerpt_buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2059                let buffer_position = cmp::min(
2060                    excerpt_buffer_end,
2061                    anchor.text_anchor.summary::<D>(&excerpt.buffer),
2062                );
2063                if buffer_position > excerpt_buffer_start {
2064                    position.add_assign(&(buffer_position - excerpt_buffer_start));
2065                }
2066            }
2067        }
2068        position
2069    }
2070
2071    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
2072    where
2073        D: TextDimension + Ord + Sub<D, Output = D>,
2074        I: 'a + IntoIterator<Item = &'a Anchor>,
2075    {
2076        if let Some((_, _, buffer)) = self.as_singleton() {
2077            return buffer
2078                .summaries_for_anchors(anchors.into_iter().map(|a| &a.text_anchor))
2079                .collect();
2080        }
2081
2082        let mut anchors = anchors.into_iter().peekable();
2083        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
2084        let mut summaries = Vec::new();
2085        while let Some(anchor) = anchors.peek() {
2086            let excerpt_id = &anchor.excerpt_id;
2087            let excerpt_anchors = iter::from_fn(|| {
2088                let anchor = anchors.peek()?;
2089                if anchor.excerpt_id == *excerpt_id {
2090                    Some(&anchors.next().unwrap().text_anchor)
2091                } else {
2092                    None
2093                }
2094            });
2095
2096            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
2097            if cursor.item().is_none() {
2098                cursor.next(&());
2099            }
2100
2101            let position = D::from_text_summary(&cursor.start().text);
2102            if let Some(excerpt) = cursor.item() {
2103                if excerpt.id == *excerpt_id {
2104                    let excerpt_buffer_start =
2105                        excerpt.range.context.start.summary::<D>(&excerpt.buffer);
2106                    let excerpt_buffer_end =
2107                        excerpt.range.context.end.summary::<D>(&excerpt.buffer);
2108                    summaries.extend(
2109                        excerpt
2110                            .buffer
2111                            .summaries_for_anchors::<D, _>(excerpt_anchors)
2112                            .map(move |summary| {
2113                                let summary = cmp::min(excerpt_buffer_end.clone(), summary);
2114                                let mut position = position.clone();
2115                                let excerpt_buffer_start = excerpt_buffer_start.clone();
2116                                if summary > excerpt_buffer_start {
2117                                    position.add_assign(&(summary - excerpt_buffer_start));
2118                                }
2119                                position
2120                            }),
2121                    );
2122                    continue;
2123                }
2124            }
2125
2126            summaries.extend(excerpt_anchors.map(|_| position.clone()));
2127        }
2128
2129        summaries
2130    }
2131
2132    pub fn refresh_anchors<'a, I>(&'a self, anchors: I) -> Vec<(usize, Anchor, bool)>
2133    where
2134        I: 'a + IntoIterator<Item = &'a Anchor>,
2135    {
2136        let mut anchors = anchors.into_iter().enumerate().peekable();
2137        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2138        let mut result = Vec::new();
2139        while let Some((_, anchor)) = anchors.peek() {
2140            let old_excerpt_id = &anchor.excerpt_id;
2141
2142            // Find the location where this anchor's excerpt should be.
2143            cursor.seek_forward(&Some(old_excerpt_id), Bias::Left, &());
2144            if cursor.item().is_none() {
2145                cursor.next(&());
2146            }
2147
2148            let next_excerpt = cursor.item();
2149            let prev_excerpt = cursor.prev_item();
2150
2151            // Process all of the anchors for this excerpt.
2152            while let Some((_, anchor)) = anchors.peek() {
2153                if anchor.excerpt_id != *old_excerpt_id {
2154                    break;
2155                }
2156                let mut kept_position = false;
2157                let (anchor_ix, anchor) = anchors.next().unwrap();
2158                let mut anchor = anchor.clone();
2159
2160                // Leave min and max anchors unchanged.
2161                if *old_excerpt_id == ExcerptId::max() || *old_excerpt_id == ExcerptId::min() {
2162                    kept_position = true;
2163                }
2164                // If the old excerpt still exists at this location, then leave
2165                // the anchor unchanged.
2166                else if next_excerpt.map_or(false, |excerpt| {
2167                    excerpt.id == *old_excerpt_id && excerpt.contains(&anchor)
2168                }) {
2169                    kept_position = true;
2170                }
2171                // If the old excerpt no longer exists at this location, then attempt to
2172                // find an equivalent position for this anchor in an adjacent excerpt.
2173                else {
2174                    for excerpt in [next_excerpt, prev_excerpt].iter().filter_map(|e| *e) {
2175                        if excerpt.contains(&anchor) {
2176                            anchor.excerpt_id = excerpt.id.clone();
2177                            kept_position = true;
2178                            break;
2179                        }
2180                    }
2181                }
2182                // If there's no adjacent excerpt that contains the anchor's position,
2183                // then report that the anchor has lost its position.
2184                if !kept_position {
2185                    anchor = if let Some(excerpt) = next_excerpt {
2186                        let mut text_anchor = excerpt
2187                            .range
2188                            .context
2189                            .start
2190                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2191                        if text_anchor
2192                            .cmp(&excerpt.range.context.end, &excerpt.buffer)
2193                            .is_gt()
2194                        {
2195                            text_anchor = excerpt.range.context.end.clone();
2196                        }
2197                        Anchor {
2198                            buffer_id: Some(excerpt.buffer_id),
2199                            excerpt_id: excerpt.id.clone(),
2200                            text_anchor,
2201                        }
2202                    } else if let Some(excerpt) = prev_excerpt {
2203                        let mut text_anchor = excerpt
2204                            .range
2205                            .context
2206                            .end
2207                            .bias(anchor.text_anchor.bias, &excerpt.buffer);
2208                        if text_anchor
2209                            .cmp(&excerpt.range.context.start, &excerpt.buffer)
2210                            .is_lt()
2211                        {
2212                            text_anchor = excerpt.range.context.start.clone();
2213                        }
2214                        Anchor {
2215                            buffer_id: Some(excerpt.buffer_id),
2216                            excerpt_id: excerpt.id.clone(),
2217                            text_anchor,
2218                        }
2219                    } else if anchor.text_anchor.bias == Bias::Left {
2220                        Anchor::min()
2221                    } else {
2222                        Anchor::max()
2223                    };
2224                }
2225
2226                result.push((anchor_ix, anchor, kept_position));
2227            }
2228        }
2229        result.sort_unstable_by(|a, b| a.1.cmp(&b.1, self));
2230        result
2231    }
2232
2233    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2234        self.anchor_at(position, Bias::Left)
2235    }
2236
2237    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2238        self.anchor_at(position, Bias::Right)
2239    }
2240
2241    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
2242        let offset = position.to_offset(self);
2243        if let Some((excerpt_id, buffer_id, buffer)) = self.as_singleton() {
2244            return Anchor {
2245                buffer_id: Some(buffer_id),
2246                excerpt_id: excerpt_id.clone(),
2247                text_anchor: buffer.anchor_at(offset, bias),
2248            };
2249        }
2250
2251        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
2252        cursor.seek(&offset, Bias::Right, &());
2253        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
2254            cursor.prev(&());
2255        }
2256        if let Some(excerpt) = cursor.item() {
2257            let mut overshoot = offset.saturating_sub(cursor.start().0);
2258            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
2259                overshoot -= 1;
2260                bias = Bias::Right;
2261            }
2262
2263            let buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
2264            let text_anchor =
2265                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
2266            Anchor {
2267                buffer_id: Some(excerpt.buffer_id),
2268                excerpt_id: excerpt.id.clone(),
2269                text_anchor,
2270            }
2271        } else if offset == 0 && bias == Bias::Left {
2272            Anchor::min()
2273        } else {
2274            Anchor::max()
2275        }
2276    }
2277
2278    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
2279        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2280        cursor.seek(&Some(&excerpt_id), Bias::Left, &());
2281        if let Some(excerpt) = cursor.item() {
2282            if excerpt.id == excerpt_id {
2283                let text_anchor = excerpt.clip_anchor(text_anchor);
2284                drop(cursor);
2285                return Anchor {
2286                    buffer_id: Some(excerpt.buffer_id),
2287                    excerpt_id,
2288                    text_anchor,
2289                };
2290            }
2291        }
2292        panic!("excerpt not found");
2293    }
2294
2295    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2296        if anchor.excerpt_id == ExcerptId::min() || anchor.excerpt_id == ExcerptId::max() {
2297            true
2298        } else if let Some(excerpt) = self.excerpt(&anchor.excerpt_id) {
2299            excerpt.buffer.can_resolve(&anchor.text_anchor)
2300        } else {
2301            false
2302        }
2303    }
2304
2305    pub fn excerpt_boundaries_in_range<'a, R, T>(
2306        &'a self,
2307        range: R,
2308    ) -> impl Iterator<Item = ExcerptBoundary> + 'a
2309    where
2310        R: RangeBounds<T>,
2311        T: ToOffset,
2312    {
2313        let start_offset;
2314        let start = match range.start_bound() {
2315            Bound::Included(start) => {
2316                start_offset = start.to_offset(self);
2317                Bound::Included(start_offset)
2318            }
2319            Bound::Excluded(start) => {
2320                start_offset = start.to_offset(self);
2321                Bound::Excluded(start_offset)
2322            }
2323            Bound::Unbounded => {
2324                start_offset = 0;
2325                Bound::Unbounded
2326            }
2327        };
2328        let end = match range.end_bound() {
2329            Bound::Included(end) => Bound::Included(end.to_offset(self)),
2330            Bound::Excluded(end) => Bound::Excluded(end.to_offset(self)),
2331            Bound::Unbounded => Bound::Unbounded,
2332        };
2333        let bounds = (start, end);
2334
2335        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
2336        cursor.seek(&start_offset, Bias::Right, &());
2337        if cursor.item().is_none() {
2338            cursor.prev(&());
2339        }
2340        if !bounds.contains(&cursor.start().0) {
2341            cursor.next(&());
2342        }
2343
2344        let mut prev_buffer_id = cursor.prev_item().map(|excerpt| excerpt.buffer_id);
2345        std::iter::from_fn(move || {
2346            if self.singleton {
2347                None
2348            } else if bounds.contains(&cursor.start().0) {
2349                let excerpt = cursor.item()?;
2350                let starts_new_buffer = Some(excerpt.buffer_id) != prev_buffer_id;
2351                let boundary = ExcerptBoundary {
2352                    id: excerpt.id.clone(),
2353                    key: excerpt.key,
2354                    row: cursor.start().1.row,
2355                    buffer: excerpt.buffer.clone(),
2356                    range: excerpt.range.clone(),
2357                    starts_new_buffer,
2358                };
2359
2360                prev_buffer_id = Some(excerpt.buffer_id);
2361                cursor.next(&());
2362                Some(boundary)
2363            } else {
2364                None
2365            }
2366        })
2367    }
2368
2369    pub fn edit_count(&self) -> usize {
2370        self.edit_count
2371    }
2372
2373    pub fn parse_count(&self) -> usize {
2374        self.parse_count
2375    }
2376
2377    pub fn enclosing_bracket_ranges<T: ToOffset>(
2378        &self,
2379        range: Range<T>,
2380    ) -> Option<(Range<usize>, Range<usize>)> {
2381        let range = range.start.to_offset(self)..range.end.to_offset(self);
2382
2383        let mut cursor = self.excerpts.cursor::<usize>();
2384        cursor.seek(&range.start, Bias::Right, &());
2385        let start_excerpt = cursor.item();
2386
2387        cursor.seek(&range.end, Bias::Right, &());
2388        let end_excerpt = cursor.item();
2389
2390        start_excerpt
2391            .zip(end_excerpt)
2392            .and_then(|(start_excerpt, end_excerpt)| {
2393                if start_excerpt.id != end_excerpt.id {
2394                    return None;
2395                }
2396
2397                let excerpt_buffer_start = start_excerpt
2398                    .range
2399                    .context
2400                    .start
2401                    .to_offset(&start_excerpt.buffer);
2402                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2403
2404                let start_in_buffer =
2405                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2406                let end_in_buffer =
2407                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2408                let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
2409                    .buffer
2410                    .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
2411
2412                if start_bracket_range.start >= excerpt_buffer_start
2413                    && end_bracket_range.end <= excerpt_buffer_end
2414                {
2415                    start_bracket_range.start =
2416                        cursor.start() + (start_bracket_range.start - excerpt_buffer_start);
2417                    start_bracket_range.end =
2418                        cursor.start() + (start_bracket_range.end - excerpt_buffer_start);
2419                    end_bracket_range.start =
2420                        cursor.start() + (end_bracket_range.start - excerpt_buffer_start);
2421                    end_bracket_range.end =
2422                        cursor.start() + (end_bracket_range.end - excerpt_buffer_start);
2423                    Some((start_bracket_range, end_bracket_range))
2424                } else {
2425                    None
2426                }
2427            })
2428    }
2429
2430    pub fn diagnostics_update_count(&self) -> usize {
2431        self.diagnostics_update_count
2432    }
2433
2434    pub fn trailing_excerpt_update_count(&self) -> usize {
2435        self.trailing_excerpt_update_count
2436    }
2437
2438    pub fn language(&self) -> Option<&Arc<Language>> {
2439        self.excerpts
2440            .iter()
2441            .next()
2442            .and_then(|excerpt| excerpt.buffer.language())
2443    }
2444
2445    pub fn is_dirty(&self) -> bool {
2446        self.is_dirty
2447    }
2448
2449    pub fn has_conflict(&self) -> bool {
2450        self.has_conflict
2451    }
2452
2453    pub fn diagnostic_group<'a, O>(
2454        &'a self,
2455        group_id: usize,
2456    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2457    where
2458        O: text::FromAnchor + 'a,
2459    {
2460        self.as_singleton()
2461            .into_iter()
2462            .flat_map(move |(_, _, buffer)| buffer.diagnostic_group(group_id))
2463    }
2464
2465    pub fn diagnostics_in_range<'a, T, O>(
2466        &'a self,
2467        range: Range<T>,
2468        reversed: bool,
2469    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
2470    where
2471        T: 'a + ToOffset,
2472        O: 'a + text::FromAnchor,
2473    {
2474        self.as_singleton()
2475            .into_iter()
2476            .flat_map(move |(_, _, buffer)| {
2477                buffer.diagnostics_in_range(
2478                    range.start.to_offset(self)..range.end.to_offset(self),
2479                    reversed,
2480                )
2481            })
2482    }
2483
2484    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
2485        let range = range.start.to_offset(self)..range.end.to_offset(self);
2486
2487        let mut cursor = self.excerpts.cursor::<usize>();
2488        cursor.seek(&range.start, Bias::Right, &());
2489        let start_excerpt = cursor.item();
2490
2491        cursor.seek(&range.end, Bias::Right, &());
2492        let end_excerpt = cursor.item();
2493
2494        start_excerpt
2495            .zip(end_excerpt)
2496            .and_then(|(start_excerpt, end_excerpt)| {
2497                if start_excerpt.id != end_excerpt.id {
2498                    return None;
2499                }
2500
2501                let excerpt_buffer_start = start_excerpt
2502                    .range
2503                    .context
2504                    .start
2505                    .to_offset(&start_excerpt.buffer);
2506                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.len;
2507
2508                let start_in_buffer =
2509                    excerpt_buffer_start + range.start.saturating_sub(*cursor.start());
2510                let end_in_buffer =
2511                    excerpt_buffer_start + range.end.saturating_sub(*cursor.start());
2512                let mut ancestor_buffer_range = start_excerpt
2513                    .buffer
2514                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
2515                ancestor_buffer_range.start =
2516                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
2517                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
2518
2519                let start = cursor.start() + (ancestor_buffer_range.start - excerpt_buffer_start);
2520                let end = cursor.start() + (ancestor_buffer_range.end - excerpt_buffer_start);
2521                Some(start..end)
2522            })
2523    }
2524
2525    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
2526        let (excerpt_id, _, buffer) = self.as_singleton()?;
2527        let outline = buffer.outline(theme)?;
2528        Some(Outline::new(
2529            outline
2530                .items
2531                .into_iter()
2532                .map(|item| OutlineItem {
2533                    depth: item.depth,
2534                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2535                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2536                    text: item.text,
2537                    highlight_ranges: item.highlight_ranges,
2538                    name_ranges: item.name_ranges,
2539                })
2540                .collect(),
2541        ))
2542    }
2543
2544    pub fn symbols_containing<T: ToOffset>(
2545        &self,
2546        offset: T,
2547        theme: Option<&SyntaxTheme>,
2548    ) -> Option<(usize, Vec<OutlineItem<Anchor>>)> {
2549        let anchor = self.anchor_before(offset);
2550        let excerpt_id = anchor.excerpt_id();
2551        let excerpt = self.excerpt(excerpt_id)?;
2552        Some((
2553            excerpt.buffer_id,
2554            excerpt
2555                .buffer
2556                .symbols_containing(anchor.text_anchor, theme)
2557                .into_iter()
2558                .flatten()
2559                .map(|item| OutlineItem {
2560                    depth: item.depth,
2561                    range: self.anchor_in_excerpt(excerpt_id.clone(), item.range.start)
2562                        ..self.anchor_in_excerpt(excerpt_id.clone(), item.range.end),
2563                    text: item.text,
2564                    highlight_ranges: item.highlight_ranges,
2565                    name_ranges: item.name_ranges,
2566                })
2567                .collect(),
2568        ))
2569    }
2570
2571    fn excerpt<'a>(&'a self, excerpt_id: &'a ExcerptId) -> Option<&'a Excerpt> {
2572        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2573        cursor.seek(&Some(excerpt_id), Bias::Left, &());
2574        if let Some(excerpt) = cursor.item() {
2575            if excerpt.id == *excerpt_id {
2576                return Some(excerpt);
2577            }
2578        }
2579        None
2580    }
2581
2582    pub fn remote_selections_in_range<'a>(
2583        &'a self,
2584        range: &'a Range<Anchor>,
2585    ) -> impl 'a + Iterator<Item = (ReplicaId, bool, Selection<Anchor>)> {
2586        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
2587        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
2588        cursor
2589            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
2590            .flat_map(move |excerpt| {
2591                let mut query_range =
2592                    excerpt.range.context.start.clone()..excerpt.range.context.end.clone();
2593                if excerpt.id == range.start.excerpt_id {
2594                    query_range.start = range.start.text_anchor.clone();
2595                }
2596                if excerpt.id == range.end.excerpt_id {
2597                    query_range.end = range.end.text_anchor.clone();
2598                }
2599
2600                excerpt
2601                    .buffer
2602                    .remote_selections_in_range(query_range)
2603                    .flat_map(move |(replica_id, line_mode, selections)| {
2604                        selections.map(move |selection| {
2605                            let mut start = Anchor {
2606                                buffer_id: Some(excerpt.buffer_id),
2607                                excerpt_id: excerpt.id.clone(),
2608                                text_anchor: selection.start.clone(),
2609                            };
2610                            let mut end = Anchor {
2611                                buffer_id: Some(excerpt.buffer_id),
2612                                excerpt_id: excerpt.id.clone(),
2613                                text_anchor: selection.end.clone(),
2614                            };
2615                            if range.start.cmp(&start, self).is_gt() {
2616                                start = range.start.clone();
2617                            }
2618                            if range.end.cmp(&end, self).is_lt() {
2619                                end = range.end.clone();
2620                            }
2621
2622                            (
2623                                replica_id,
2624                                line_mode,
2625                                Selection {
2626                                    id: selection.id,
2627                                    start,
2628                                    end,
2629                                    reversed: selection.reversed,
2630                                    goal: selection.goal,
2631                                },
2632                            )
2633                        })
2634                    })
2635            })
2636    }
2637}
2638
2639#[cfg(any(test, feature = "test-support"))]
2640impl MultiBufferSnapshot {
2641    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
2642        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
2643        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
2644        start..end
2645    }
2646}
2647
2648impl History {
2649    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
2650        self.transaction_depth += 1;
2651        if self.transaction_depth == 1 {
2652            let id = self.next_transaction_id.tick();
2653            self.undo_stack.push(Transaction {
2654                id,
2655                buffer_transactions: Default::default(),
2656                first_edit_at: now,
2657                last_edit_at: now,
2658                suppress_grouping: false,
2659            });
2660            Some(id)
2661        } else {
2662            None
2663        }
2664    }
2665
2666    fn end_transaction(
2667        &mut self,
2668        now: Instant,
2669        buffer_transactions: HashMap<usize, TransactionId>,
2670    ) -> bool {
2671        assert_ne!(self.transaction_depth, 0);
2672        self.transaction_depth -= 1;
2673        if self.transaction_depth == 0 {
2674            if buffer_transactions.is_empty() {
2675                self.undo_stack.pop();
2676                false
2677            } else {
2678                self.redo_stack.clear();
2679                let transaction = self.undo_stack.last_mut().unwrap();
2680                transaction.last_edit_at = now;
2681                for (buffer_id, transaction_id) in buffer_transactions {
2682                    transaction
2683                        .buffer_transactions
2684                        .entry(buffer_id)
2685                        .or_insert(transaction_id);
2686                }
2687                true
2688            }
2689        } else {
2690            false
2691        }
2692    }
2693
2694    fn push_transaction<'a, T>(&mut self, buffer_transactions: T, now: Instant)
2695    where
2696        T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
2697    {
2698        assert_eq!(self.transaction_depth, 0);
2699        let transaction = Transaction {
2700            id: self.next_transaction_id.tick(),
2701            buffer_transactions: buffer_transactions
2702                .into_iter()
2703                .map(|(buffer, transaction)| (buffer.id(), transaction.id))
2704                .collect(),
2705            first_edit_at: now,
2706            last_edit_at: now,
2707            suppress_grouping: false,
2708        };
2709        if !transaction.buffer_transactions.is_empty() {
2710            self.undo_stack.push(transaction);
2711            self.redo_stack.clear();
2712        }
2713    }
2714
2715    fn finalize_last_transaction(&mut self) {
2716        if let Some(transaction) = self.undo_stack.last_mut() {
2717            transaction.suppress_grouping = true;
2718        }
2719    }
2720
2721    fn pop_undo(&mut self) -> Option<&mut Transaction> {
2722        assert_eq!(self.transaction_depth, 0);
2723        if let Some(transaction) = self.undo_stack.pop() {
2724            self.redo_stack.push(transaction);
2725            self.redo_stack.last_mut()
2726        } else {
2727            None
2728        }
2729    }
2730
2731    fn pop_redo(&mut self) -> Option<&mut Transaction> {
2732        assert_eq!(self.transaction_depth, 0);
2733        if let Some(transaction) = self.redo_stack.pop() {
2734            self.undo_stack.push(transaction);
2735            self.undo_stack.last_mut()
2736        } else {
2737            None
2738        }
2739    }
2740
2741    fn group(&mut self) -> Option<TransactionId> {
2742        let mut count = 0;
2743        let mut transactions = self.undo_stack.iter();
2744        if let Some(mut transaction) = transactions.next_back() {
2745            while let Some(prev_transaction) = transactions.next_back() {
2746                if !prev_transaction.suppress_grouping
2747                    && transaction.first_edit_at - prev_transaction.last_edit_at
2748                        <= self.group_interval
2749                {
2750                    transaction = prev_transaction;
2751                    count += 1;
2752                } else {
2753                    break;
2754                }
2755            }
2756        }
2757        self.group_trailing(count)
2758    }
2759
2760    fn group_until(&mut self, transaction_id: TransactionId) {
2761        let mut count = 0;
2762        for transaction in self.undo_stack.iter().rev() {
2763            if transaction.id == transaction_id {
2764                self.group_trailing(count);
2765                break;
2766            } else if transaction.suppress_grouping {
2767                break;
2768            } else {
2769                count += 1;
2770            }
2771        }
2772    }
2773
2774    fn group_trailing(&mut self, n: usize) -> Option<TransactionId> {
2775        let new_len = self.undo_stack.len() - n;
2776        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
2777        if let Some(last_transaction) = transactions_to_keep.last_mut() {
2778            if let Some(transaction) = transactions_to_merge.last() {
2779                last_transaction.last_edit_at = transaction.last_edit_at;
2780            }
2781            for to_merge in transactions_to_merge {
2782                for (buffer_id, transaction_id) in &to_merge.buffer_transactions {
2783                    last_transaction
2784                        .buffer_transactions
2785                        .entry(*buffer_id)
2786                        .or_insert(*transaction_id);
2787                }
2788            }
2789        }
2790
2791        self.undo_stack.truncate(new_len);
2792        self.undo_stack.last().map(|t| t.id)
2793    }
2794}
2795
2796impl Excerpt {
2797    fn new(
2798        id: ExcerptId,
2799        key: usize,
2800        buffer_id: usize,
2801        buffer: BufferSnapshot,
2802        range: ExcerptRange<text::Anchor>,
2803        has_trailing_newline: bool,
2804    ) -> Self {
2805        Excerpt {
2806            id,
2807            key,
2808            max_buffer_row: range.context.end.to_point(&buffer).row,
2809            text_summary: buffer
2810                .text_summary_for_range::<TextSummary, _>(range.context.to_offset(&buffer)),
2811            buffer_id,
2812            buffer,
2813            range,
2814            has_trailing_newline,
2815        }
2816    }
2817
2818    fn chunks_in_range<'a>(
2819        &'a self,
2820        range: Range<usize>,
2821        language_aware: bool,
2822    ) -> ExcerptChunks<'a> {
2823        let content_start = self.range.context.start.to_offset(&self.buffer);
2824        let chunks_start = content_start + range.start;
2825        let chunks_end = content_start + cmp::min(range.end, self.text_summary.len);
2826
2827        let footer_height = if self.has_trailing_newline
2828            && range.start <= self.text_summary.len
2829            && range.end > self.text_summary.len
2830        {
2831            1
2832        } else {
2833            0
2834        };
2835
2836        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, language_aware);
2837
2838        ExcerptChunks {
2839            content_chunks,
2840            footer_height,
2841        }
2842    }
2843
2844    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
2845        let content_start = self.range.context.start.to_offset(&self.buffer);
2846        let bytes_start = content_start + range.start;
2847        let bytes_end = content_start + cmp::min(range.end, self.text_summary.len);
2848        let footer_height = if self.has_trailing_newline
2849            && range.start <= self.text_summary.len
2850            && range.end > self.text_summary.len
2851        {
2852            1
2853        } else {
2854            0
2855        };
2856        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
2857
2858        ExcerptBytes {
2859            content_bytes,
2860            footer_height,
2861        }
2862    }
2863
2864    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
2865        if text_anchor
2866            .cmp(&self.range.context.start, &self.buffer)
2867            .is_lt()
2868        {
2869            self.range.context.start.clone()
2870        } else if text_anchor
2871            .cmp(&self.range.context.end, &self.buffer)
2872            .is_gt()
2873        {
2874            self.range.context.end.clone()
2875        } else {
2876            text_anchor
2877        }
2878    }
2879
2880    fn contains(&self, anchor: &Anchor) -> bool {
2881        Some(self.buffer_id) == anchor.buffer_id
2882            && self
2883                .range
2884                .context
2885                .start
2886                .cmp(&anchor.text_anchor, &self.buffer)
2887                .is_le()
2888            && self
2889                .range
2890                .context
2891                .end
2892                .cmp(&anchor.text_anchor, &self.buffer)
2893                .is_ge()
2894    }
2895}
2896
2897impl fmt::Debug for Excerpt {
2898    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2899        f.debug_struct("Excerpt")
2900            .field("id", &self.id)
2901            .field("buffer_id", &self.buffer_id)
2902            .field("range", &self.range)
2903            .field("text_summary", &self.text_summary)
2904            .field("has_trailing_newline", &self.has_trailing_newline)
2905            .finish()
2906    }
2907}
2908
2909impl sum_tree::Item for Excerpt {
2910    type Summary = ExcerptSummary;
2911
2912    fn summary(&self) -> Self::Summary {
2913        let mut text = self.text_summary.clone();
2914        if self.has_trailing_newline {
2915            text += TextSummary::from("\n");
2916        }
2917        ExcerptSummary {
2918            excerpt_id: self.id.clone(),
2919            max_buffer_row: self.max_buffer_row,
2920            text,
2921        }
2922    }
2923}
2924
2925impl sum_tree::Summary for ExcerptSummary {
2926    type Context = ();
2927
2928    fn add_summary(&mut self, summary: &Self, _: &()) {
2929        debug_assert!(summary.excerpt_id > self.excerpt_id);
2930        self.excerpt_id = summary.excerpt_id.clone();
2931        self.text.add_summary(&summary.text, &());
2932        self.max_buffer_row = cmp::max(self.max_buffer_row, summary.max_buffer_row);
2933    }
2934}
2935
2936impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
2937    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2938        *self += &summary.text;
2939    }
2940}
2941
2942impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
2943    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2944        *self += summary.text.len;
2945    }
2946}
2947
2948impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
2949    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2950        Ord::cmp(self, &cursor_location.text.len)
2951    }
2952}
2953
2954impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
2955    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
2956        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
2957    }
2958}
2959
2960impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for OffsetUtf16 {
2961    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2962        *self += summary.text.len_utf16;
2963    }
2964}
2965
2966impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
2967    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2968        *self += summary.text.lines;
2969    }
2970}
2971
2972impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
2973    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2974        *self += summary.text.lines_utf16()
2975    }
2976}
2977
2978impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
2979    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
2980        *self = Some(&summary.excerpt_id);
2981    }
2982}
2983
2984impl<'a> MultiBufferRows<'a> {
2985    pub fn seek(&mut self, row: u32) {
2986        self.buffer_row_range = 0..0;
2987
2988        self.excerpts
2989            .seek_forward(&Point::new(row, 0), Bias::Right, &());
2990        if self.excerpts.item().is_none() {
2991            self.excerpts.prev(&());
2992
2993            if self.excerpts.item().is_none() && row == 0 {
2994                self.buffer_row_range = 0..1;
2995                return;
2996            }
2997        }
2998
2999        if let Some(excerpt) = self.excerpts.item() {
3000            let overshoot = row - self.excerpts.start().row;
3001            let excerpt_start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3002            self.buffer_row_range.start = excerpt_start + overshoot;
3003            self.buffer_row_range.end = excerpt_start + excerpt.text_summary.lines.row + 1;
3004        }
3005    }
3006}
3007
3008impl<'a> Iterator for MultiBufferRows<'a> {
3009    type Item = Option<u32>;
3010
3011    fn next(&mut self) -> Option<Self::Item> {
3012        loop {
3013            if !self.buffer_row_range.is_empty() {
3014                let row = Some(self.buffer_row_range.start);
3015                self.buffer_row_range.start += 1;
3016                return Some(row);
3017            }
3018            self.excerpts.item()?;
3019            self.excerpts.next(&());
3020            let excerpt = self.excerpts.item()?;
3021            self.buffer_row_range.start = excerpt.range.context.start.to_point(&excerpt.buffer).row;
3022            self.buffer_row_range.end =
3023                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1;
3024        }
3025    }
3026}
3027
3028impl<'a> MultiBufferChunks<'a> {
3029    pub fn offset(&self) -> usize {
3030        self.range.start
3031    }
3032
3033    pub fn seek(&mut self, offset: usize) {
3034        self.range.start = offset;
3035        self.excerpts.seek(&offset, Bias::Right, &());
3036        if let Some(excerpt) = self.excerpts.item() {
3037            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3038                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
3039                self.language_aware,
3040            ));
3041        } else {
3042            self.excerpt_chunks = None;
3043        }
3044    }
3045}
3046
3047impl<'a> Iterator for MultiBufferChunks<'a> {
3048    type Item = Chunk<'a>;
3049
3050    fn next(&mut self) -> Option<Self::Item> {
3051        if self.range.is_empty() {
3052            None
3053        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
3054            self.range.start += chunk.text.len();
3055            Some(chunk)
3056        } else {
3057            self.excerpts.next(&());
3058            let excerpt = self.excerpts.item()?;
3059            self.excerpt_chunks = Some(excerpt.chunks_in_range(
3060                0..self.range.end - self.excerpts.start(),
3061                self.language_aware,
3062            ));
3063            self.next()
3064        }
3065    }
3066}
3067
3068impl<'a> MultiBufferBytes<'a> {
3069    fn consume(&mut self, len: usize) {
3070        self.range.start += len;
3071        self.chunk = &self.chunk[len..];
3072
3073        if !self.range.is_empty() && self.chunk.is_empty() {
3074            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
3075                self.chunk = chunk;
3076            } else {
3077                self.excerpts.next(&());
3078                if let Some(excerpt) = self.excerpts.item() {
3079                    let mut excerpt_bytes =
3080                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
3081                    self.chunk = excerpt_bytes.next().unwrap();
3082                    self.excerpt_bytes = Some(excerpt_bytes);
3083                }
3084            }
3085        }
3086    }
3087}
3088
3089impl<'a> Iterator for MultiBufferBytes<'a> {
3090    type Item = &'a [u8];
3091
3092    fn next(&mut self) -> Option<Self::Item> {
3093        let chunk = self.chunk;
3094        if chunk.is_empty() {
3095            None
3096        } else {
3097            self.consume(chunk.len());
3098            Some(chunk)
3099        }
3100    }
3101}
3102
3103impl<'a> io::Read for MultiBufferBytes<'a> {
3104    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3105        let len = cmp::min(buf.len(), self.chunk.len());
3106        buf[..len].copy_from_slice(&self.chunk[..len]);
3107        if len > 0 {
3108            self.consume(len);
3109        }
3110        Ok(len)
3111    }
3112}
3113
3114impl<'a> Iterator for ExcerptBytes<'a> {
3115    type Item = &'a [u8];
3116
3117    fn next(&mut self) -> Option<Self::Item> {
3118        if let Some(chunk) = self.content_bytes.next() {
3119            if !chunk.is_empty() {
3120                return Some(chunk);
3121            }
3122        }
3123
3124        if self.footer_height > 0 {
3125            let result = &NEWLINES[..self.footer_height];
3126            self.footer_height = 0;
3127            return Some(result);
3128        }
3129
3130        None
3131    }
3132}
3133
3134impl<'a> Iterator for ExcerptChunks<'a> {
3135    type Item = Chunk<'a>;
3136
3137    fn next(&mut self) -> Option<Self::Item> {
3138        if let Some(chunk) = self.content_chunks.next() {
3139            return Some(chunk);
3140        }
3141
3142        if self.footer_height > 0 {
3143            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
3144            self.footer_height = 0;
3145            return Some(Chunk {
3146                text,
3147                ..Default::default()
3148            });
3149        }
3150
3151        None
3152    }
3153}
3154
3155impl ToOffset for Point {
3156    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3157        snapshot.point_to_offset(*self)
3158    }
3159}
3160
3161impl ToOffset for PointUtf16 {
3162    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3163        snapshot.point_utf16_to_offset(*self)
3164    }
3165}
3166
3167impl ToOffset for usize {
3168    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3169        assert!(*self <= snapshot.len(), "offset is out of range");
3170        *self
3171    }
3172}
3173
3174impl ToOffset for OffsetUtf16 {
3175    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
3176        snapshot.offset_utf16_to_offset(*self)
3177    }
3178}
3179
3180impl ToOffsetUtf16 for OffsetUtf16 {
3181    fn to_offset_utf16(&self, _snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3182        *self
3183    }
3184}
3185
3186impl ToOffsetUtf16 for usize {
3187    fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
3188        snapshot.offset_to_offset_utf16(*self)
3189    }
3190}
3191
3192impl ToPoint for usize {
3193    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
3194        snapshot.offset_to_point(*self)
3195    }
3196}
3197
3198impl ToPoint for Point {
3199    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
3200        *self
3201    }
3202}
3203
3204impl ToPointUtf16 for usize {
3205    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3206        snapshot.offset_to_point_utf16(*self)
3207    }
3208}
3209
3210impl ToPointUtf16 for Point {
3211    fn to_point_utf16<'a>(&self, snapshot: &MultiBufferSnapshot) -> PointUtf16 {
3212        snapshot.point_to_point_utf16(*self)
3213    }
3214}
3215
3216impl ToPointUtf16 for PointUtf16 {
3217    fn to_point_utf16<'a>(&self, _: &MultiBufferSnapshot) -> PointUtf16 {
3218        *self
3219    }
3220}
3221
3222#[cfg(test)]
3223mod tests {
3224    use super::*;
3225    use gpui::MutableAppContext;
3226    use language::{Buffer, Rope};
3227    use rand::prelude::*;
3228    use settings::Settings;
3229    use std::{env, rc::Rc};
3230    use text::{Point, RandomCharIter};
3231    use util::test::sample_text;
3232
3233    #[gpui::test]
3234    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
3235        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3236        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3237
3238        let snapshot = multibuffer.read(cx).snapshot(cx);
3239        assert_eq!(snapshot.text(), buffer.read(cx).text());
3240
3241        assert_eq!(
3242            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3243            (0..buffer.read(cx).row_count())
3244                .map(Some)
3245                .collect::<Vec<_>>()
3246        );
3247
3248        buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
3249        let snapshot = multibuffer.read(cx).snapshot(cx);
3250
3251        assert_eq!(snapshot.text(), buffer.read(cx).text());
3252        assert_eq!(
3253            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3254            (0..buffer.read(cx).row_count())
3255                .map(Some)
3256                .collect::<Vec<_>>()
3257        );
3258    }
3259
3260    #[gpui::test]
3261    fn test_remote_multibuffer(cx: &mut MutableAppContext) {
3262        let host_buffer = cx.add_model(|cx| Buffer::new(0, "a", cx));
3263        let guest_buffer = cx.add_model(|cx| {
3264            let message = host_buffer.read(cx).to_proto();
3265            Buffer::from_proto(1, message, None, cx).unwrap()
3266        });
3267        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
3268        let snapshot = multibuffer.read(cx).snapshot(cx);
3269        assert_eq!(snapshot.text(), "a");
3270
3271        guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
3272        let snapshot = multibuffer.read(cx).snapshot(cx);
3273        assert_eq!(snapshot.text(), "ab");
3274
3275        guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
3276        let snapshot = multibuffer.read(cx).snapshot(cx);
3277        assert_eq!(snapshot.text(), "abc");
3278    }
3279
3280    #[gpui::test]
3281    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
3282        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
3283        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
3284        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3285
3286        let events = Rc::new(RefCell::new(Vec::<Event>::new()));
3287        multibuffer.update(cx, |_, cx| {
3288            let events = events.clone();
3289            cx.subscribe(&multibuffer, move |_, _, event, _| {
3290                events.borrow_mut().push(event.clone())
3291            })
3292            .detach();
3293        });
3294
3295        let subscription = multibuffer.update(cx, |multibuffer, cx| {
3296            let subscription = multibuffer.subscribe();
3297            multibuffer.push_excerpts(
3298                buffer_1.clone(),
3299                [ExcerptRange {
3300                    context: Point::new(1, 2)..Point::new(2, 5),
3301                    primary: None,
3302                }],
3303                cx,
3304            );
3305            assert_eq!(
3306                subscription.consume().into_inner(),
3307                [Edit {
3308                    old: 0..0,
3309                    new: 0..10
3310                }]
3311            );
3312
3313            multibuffer.push_excerpts(
3314                buffer_1.clone(),
3315                [ExcerptRange {
3316                    context: Point::new(3, 3)..Point::new(4, 4),
3317                    primary: None,
3318                }],
3319                cx,
3320            );
3321            multibuffer.push_excerpts(
3322                buffer_2.clone(),
3323                [ExcerptRange {
3324                    context: Point::new(3, 1)..Point::new(3, 3),
3325                    primary: None,
3326                }],
3327                cx,
3328            );
3329            assert_eq!(
3330                subscription.consume().into_inner(),
3331                [Edit {
3332                    old: 10..10,
3333                    new: 10..22
3334                }]
3335            );
3336
3337            subscription
3338        });
3339
3340        // Adding excerpts emits an edited event.
3341        assert_eq!(
3342            events.borrow().as_slice(),
3343            &[Event::Edited, Event::Edited, Event::Edited]
3344        );
3345
3346        let snapshot = multibuffer.read(cx).snapshot(cx);
3347        assert_eq!(
3348            snapshot.text(),
3349            concat!(
3350                "bbbb\n",  // Preserve newlines
3351                "ccccc\n", //
3352                "ddd\n",   //
3353                "eeee\n",  //
3354                "jj"       //
3355            )
3356        );
3357        assert_eq!(
3358            snapshot.buffer_rows(0).collect::<Vec<_>>(),
3359            [Some(1), Some(2), Some(3), Some(4), Some(3)]
3360        );
3361        assert_eq!(
3362            snapshot.buffer_rows(2).collect::<Vec<_>>(),
3363            [Some(3), Some(4), Some(3)]
3364        );
3365        assert_eq!(snapshot.buffer_rows(4).collect::<Vec<_>>(), [Some(3)]);
3366        assert_eq!(snapshot.buffer_rows(5).collect::<Vec<_>>(), []);
3367
3368        assert_eq!(
3369            boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
3370            &[
3371                (0, "bbbb\nccccc".to_string(), true),
3372                (2, "ddd\neeee".to_string(), false),
3373                (4, "jj".to_string(), true),
3374            ]
3375        );
3376        assert_eq!(
3377            boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
3378            &[(0, "bbbb\nccccc".to_string(), true)]
3379        );
3380        assert_eq!(
3381            boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
3382            &[]
3383        );
3384        assert_eq!(
3385            boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
3386            &[]
3387        );
3388        assert_eq!(
3389            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3390            &[(2, "ddd\neeee".to_string(), false)]
3391        );
3392        assert_eq!(
3393            boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
3394            &[(2, "ddd\neeee".to_string(), false)]
3395        );
3396        assert_eq!(
3397            boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
3398            &[(2, "ddd\neeee".to_string(), false)]
3399        );
3400        assert_eq!(
3401            boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
3402            &[(4, "jj".to_string(), true)]
3403        );
3404        assert_eq!(
3405            boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
3406            &[]
3407        );
3408
3409        buffer_1.update(cx, |buffer, cx| {
3410            let text = "\n";
3411            buffer.edit(
3412                [
3413                    (Point::new(0, 0)..Point::new(0, 0), text),
3414                    (Point::new(2, 1)..Point::new(2, 3), text),
3415                ],
3416                None,
3417                cx,
3418            );
3419        });
3420
3421        let snapshot = multibuffer.read(cx).snapshot(cx);
3422        assert_eq!(
3423            snapshot.text(),
3424            concat!(
3425                "bbbb\n", // Preserve newlines
3426                "c\n",    //
3427                "cc\n",   //
3428                "ddd\n",  //
3429                "eeee\n", //
3430                "jj"      //
3431            )
3432        );
3433
3434        assert_eq!(
3435            subscription.consume().into_inner(),
3436            [Edit {
3437                old: 6..8,
3438                new: 6..7
3439            }]
3440        );
3441
3442        let snapshot = multibuffer.read(cx).snapshot(cx);
3443        assert_eq!(
3444            snapshot.clip_point(Point::new(0, 5), Bias::Left),
3445            Point::new(0, 4)
3446        );
3447        assert_eq!(
3448            snapshot.clip_point(Point::new(0, 5), Bias::Right),
3449            Point::new(0, 4)
3450        );
3451        assert_eq!(
3452            snapshot.clip_point(Point::new(5, 1), Bias::Right),
3453            Point::new(5, 1)
3454        );
3455        assert_eq!(
3456            snapshot.clip_point(Point::new(5, 2), Bias::Right),
3457            Point::new(5, 2)
3458        );
3459        assert_eq!(
3460            snapshot.clip_point(Point::new(5, 3), Bias::Right),
3461            Point::new(5, 2)
3462        );
3463
3464        let snapshot = multibuffer.update(cx, |multibuffer, cx| {
3465            let (buffer_2_excerpt_id, _) =
3466                multibuffer.excerpts_for_buffer(&buffer_2, cx)[0].clone();
3467            multibuffer.remove_excerpts(&[buffer_2_excerpt_id], cx);
3468            multibuffer.snapshot(cx)
3469        });
3470
3471        assert_eq!(
3472            snapshot.text(),
3473            concat!(
3474                "bbbb\n", // Preserve newlines
3475                "c\n",    //
3476                "cc\n",   //
3477                "ddd\n",  //
3478                "eeee",   //
3479            )
3480        );
3481
3482        fn boundaries_in_range(
3483            range: Range<Point>,
3484            snapshot: &MultiBufferSnapshot,
3485        ) -> Vec<(u32, String, bool)> {
3486            snapshot
3487                .excerpt_boundaries_in_range(range)
3488                .map(|boundary| {
3489                    (
3490                        boundary.row,
3491                        boundary
3492                            .buffer
3493                            .text_for_range(boundary.range.context)
3494                            .collect::<String>(),
3495                        boundary.starts_new_buffer,
3496                    )
3497                })
3498                .collect::<Vec<_>>()
3499        }
3500    }
3501
3502    #[gpui::test]
3503    fn test_excerpts_with_context_lines(cx: &mut MutableAppContext) {
3504        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(20, 3, 'a'), cx));
3505        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3506        let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
3507            multibuffer.push_excerpts_with_context_lines(
3508                buffer.clone(),
3509                vec![
3510                    Point::new(3, 2)..Point::new(4, 2),
3511                    Point::new(7, 1)..Point::new(7, 3),
3512                    Point::new(15, 0)..Point::new(15, 0),
3513                ],
3514                2,
3515                cx,
3516            )
3517        });
3518
3519        let snapshot = multibuffer.read(cx).snapshot(cx);
3520        assert_eq!(
3521            snapshot.text(),
3522            "bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
3523        );
3524
3525        assert_eq!(
3526            anchor_ranges
3527                .iter()
3528                .map(|range| range.to_point(&snapshot))
3529                .collect::<Vec<_>>(),
3530            vec![
3531                Point::new(2, 2)..Point::new(3, 2),
3532                Point::new(6, 1)..Point::new(6, 3),
3533                Point::new(12, 0)..Point::new(12, 0)
3534            ]
3535        );
3536    }
3537
3538    #[gpui::test]
3539    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
3540        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3541
3542        let snapshot = multibuffer.read(cx).snapshot(cx);
3543        assert_eq!(snapshot.text(), "");
3544        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
3545        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
3546    }
3547
3548    #[gpui::test]
3549    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
3550        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3551        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3552        let old_snapshot = multibuffer.read(cx).snapshot(cx);
3553        buffer.update(cx, |buffer, cx| {
3554            buffer.edit([(0..0, "X")], None, cx);
3555            buffer.edit([(5..5, "Y")], None, cx);
3556        });
3557        let new_snapshot = multibuffer.read(cx).snapshot(cx);
3558
3559        assert_eq!(old_snapshot.text(), "abcd");
3560        assert_eq!(new_snapshot.text(), "XabcdY");
3561
3562        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3563        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3564        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
3565        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
3566    }
3567
3568    #[gpui::test]
3569    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
3570        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3571        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
3572        let multibuffer = cx.add_model(|cx| {
3573            let mut multibuffer = MultiBuffer::new(0);
3574            multibuffer.push_excerpts(
3575                buffer_1.clone(),
3576                [ExcerptRange {
3577                    context: 0..4,
3578                    primary: None,
3579                }],
3580                cx,
3581            );
3582            multibuffer.push_excerpts(
3583                buffer_2.clone(),
3584                [ExcerptRange {
3585                    context: 0..5,
3586                    primary: None,
3587                }],
3588                cx,
3589            );
3590            multibuffer
3591        });
3592        let old_snapshot = multibuffer.read(cx).snapshot(cx);
3593
3594        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
3595        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
3596        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3597        assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
3598        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3599        assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
3600
3601        buffer_1.update(cx, |buffer, cx| {
3602            buffer.edit([(0..0, "W")], None, cx);
3603            buffer.edit([(5..5, "X")], None, cx);
3604        });
3605        buffer_2.update(cx, |buffer, cx| {
3606            buffer.edit([(0..0, "Y")], None, cx);
3607            buffer.edit([(6..6, "Z")], None, cx);
3608        });
3609        let new_snapshot = multibuffer.read(cx).snapshot(cx);
3610
3611        assert_eq!(old_snapshot.text(), "abcd\nefghi");
3612        assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
3613
3614        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
3615        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
3616        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
3617        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
3618        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
3619        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
3620        assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
3621        assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
3622        assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
3623        assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
3624    }
3625
3626    #[gpui::test]
3627    fn test_multibuffer_resolving_anchors_after_replacing_their_excerpts(
3628        cx: &mut MutableAppContext,
3629    ) {
3630        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
3631        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "ABCDEFGHIJKLMNOP", cx));
3632        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3633
3634        // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
3635        // Add an excerpt from buffer 1 that spans this new insertion.
3636        buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
3637        let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
3638            multibuffer
3639                .push_excerpts(
3640                    buffer_1.clone(),
3641                    [ExcerptRange {
3642                        context: 0..7,
3643                        primary: None,
3644                    }],
3645                    cx,
3646                )
3647                .pop()
3648                .unwrap()
3649        });
3650
3651        let snapshot_1 = multibuffer.read(cx).snapshot(cx);
3652        assert_eq!(snapshot_1.text(), "abcd123");
3653
3654        // Replace the buffer 1 excerpt with new excerpts from buffer 2.
3655        let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
3656            multibuffer.remove_excerpts([&excerpt_id_1], cx);
3657            let mut ids = multibuffer
3658                .push_excerpts(
3659                    buffer_2.clone(),
3660                    [
3661                        ExcerptRange {
3662                            context: 0..4,
3663                            primary: None,
3664                        },
3665                        ExcerptRange {
3666                            context: 6..10,
3667                            primary: None,
3668                        },
3669                        ExcerptRange {
3670                            context: 12..16,
3671                            primary: None,
3672                        },
3673                    ],
3674                    cx,
3675                )
3676                .into_iter();
3677            (ids.next().unwrap(), ids.next().unwrap())
3678        });
3679        let snapshot_2 = multibuffer.read(cx).snapshot(cx);
3680        assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
3681
3682        // The old excerpt id doesn't get reused.
3683        assert_ne!(excerpt_id_2, excerpt_id_1);
3684
3685        // Resolve some anchors from the previous snapshot in the new snapshot.
3686        // Although there is still an excerpt with the same id, it is for
3687        // a different buffer, so we don't attempt to resolve the old text
3688        // anchor in the new buffer.
3689        assert_eq!(
3690            snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
3691            0
3692        );
3693        assert_eq!(
3694            snapshot_2.summaries_for_anchors::<usize, _>(&[
3695                snapshot_1.anchor_before(2),
3696                snapshot_1.anchor_after(3)
3697            ]),
3698            vec![0, 0]
3699        );
3700        let refresh =
3701            snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
3702        assert_eq!(
3703            refresh,
3704            &[
3705                (0, snapshot_2.anchor_before(0), false),
3706                (1, snapshot_2.anchor_after(0), false),
3707            ]
3708        );
3709
3710        // Replace the middle excerpt with a smaller excerpt in buffer 2,
3711        // that intersects the old excerpt.
3712        let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
3713            multibuffer.remove_excerpts([&excerpt_id_3], cx);
3714            multibuffer
3715                .insert_excerpts_after(
3716                    &excerpt_id_3,
3717                    buffer_2.clone(),
3718                    [ExcerptRange {
3719                        context: 5..8,
3720                        primary: None,
3721                    }],
3722                    cx,
3723                )
3724                .pop()
3725                .unwrap()
3726        });
3727
3728        let snapshot_3 = multibuffer.read(cx).snapshot(cx);
3729        assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
3730        assert_ne!(excerpt_id_5, excerpt_id_3);
3731
3732        // Resolve some anchors from the previous snapshot in the new snapshot.
3733        // The anchor in the middle excerpt snaps to the beginning of the
3734        // excerpt, since it is not
3735        let anchors = [
3736            snapshot_2.anchor_before(0),
3737            snapshot_2.anchor_after(2),
3738            snapshot_2.anchor_after(6),
3739            snapshot_2.anchor_after(14),
3740        ];
3741        assert_eq!(
3742            snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
3743            &[0, 2, 5, 13]
3744        );
3745
3746        let new_anchors = snapshot_3.refresh_anchors(&anchors);
3747        assert_eq!(
3748            new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
3749            &[(0, true), (1, true), (2, true), (3, true)]
3750        );
3751        assert_eq!(
3752            snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
3753            &[0, 2, 7, 13]
3754        );
3755    }
3756
3757    #[gpui::test(iterations = 100)]
3758    fn test_random_multibuffer(cx: &mut MutableAppContext, mut rng: StdRng) {
3759        let operations = env::var("OPERATIONS")
3760            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3761            .unwrap_or(10);
3762
3763        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
3764        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
3765        let mut excerpt_ids = Vec::new();
3766        let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
3767        let mut anchors = Vec::new();
3768        let mut old_versions = Vec::new();
3769
3770        for _ in 0..operations {
3771            match rng.gen_range(0..100) {
3772                0..=19 if !buffers.is_empty() => {
3773                    let buffer = buffers.choose(&mut rng).unwrap();
3774                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
3775                }
3776                20..=29 if !expected_excerpts.is_empty() => {
3777                    let mut ids_to_remove = vec![];
3778                    for _ in 0..rng.gen_range(1..=3) {
3779                        if expected_excerpts.is_empty() {
3780                            break;
3781                        }
3782
3783                        let ix = rng.gen_range(0..expected_excerpts.len());
3784                        ids_to_remove.push(excerpt_ids.remove(ix));
3785                        let (buffer, range) = expected_excerpts.remove(ix);
3786                        let buffer = buffer.read(cx);
3787                        log::info!(
3788                            "Removing excerpt {}: {:?}",
3789                            ix,
3790                            buffer
3791                                .text_for_range(range.to_offset(&buffer))
3792                                .collect::<String>(),
3793                        );
3794                    }
3795                    ids_to_remove.sort_unstable();
3796                    multibuffer.update(cx, |multibuffer, cx| {
3797                        multibuffer.remove_excerpts(&ids_to_remove, cx)
3798                    });
3799                }
3800                30..=39 if !expected_excerpts.is_empty() => {
3801                    let multibuffer = multibuffer.read(cx).read(cx);
3802                    let offset =
3803                        multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
3804                    let bias = if rng.gen() { Bias::Left } else { Bias::Right };
3805                    log::info!("Creating anchor at {} with bias {:?}", offset, bias);
3806                    anchors.push(multibuffer.anchor_at(offset, bias));
3807                    anchors.sort_by(|a, b| a.cmp(&b, &multibuffer));
3808                }
3809                40..=44 if !anchors.is_empty() => {
3810                    let multibuffer = multibuffer.read(cx).read(cx);
3811                    let prev_len = anchors.len();
3812                    anchors = multibuffer
3813                        .refresh_anchors(&anchors)
3814                        .into_iter()
3815                        .map(|a| a.1)
3816                        .collect();
3817
3818                    // Ensure the newly-refreshed anchors point to a valid excerpt and don't
3819                    // overshoot its boundaries.
3820                    assert_eq!(anchors.len(), prev_len);
3821                    let mut cursor = multibuffer.excerpts.cursor::<Option<&ExcerptId>>();
3822                    for anchor in &anchors {
3823                        if anchor.excerpt_id == ExcerptId::min()
3824                            || anchor.excerpt_id == ExcerptId::max()
3825                        {
3826                            continue;
3827                        }
3828
3829                        cursor.seek_forward(&Some(&anchor.excerpt_id), Bias::Left, &());
3830                        let excerpt = cursor.item().unwrap();
3831                        assert_eq!(excerpt.id, anchor.excerpt_id);
3832                        assert!(excerpt.contains(anchor));
3833                    }
3834                }
3835                _ => {
3836                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
3837                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
3838                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
3839                        buffers.last().unwrap()
3840                    } else {
3841                        buffers.choose(&mut rng).unwrap()
3842                    };
3843
3844                    let buffer = buffer_handle.read(cx);
3845                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
3846                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
3847                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3848                    let prev_excerpt_ix = rng.gen_range(0..=expected_excerpts.len());
3849                    let prev_excerpt_id = excerpt_ids
3850                        .get(prev_excerpt_ix)
3851                        .cloned()
3852                        .unwrap_or(ExcerptId::max());
3853                    let excerpt_ix = (prev_excerpt_ix + 1).min(expected_excerpts.len());
3854
3855                    log::info!(
3856                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3857                        excerpt_ix,
3858                        expected_excerpts.len(),
3859                        buffer_handle.id(),
3860                        buffer.text(),
3861                        start_ix..end_ix,
3862                        &buffer.text()[start_ix..end_ix]
3863                    );
3864
3865                    let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3866                        multibuffer
3867                            .insert_excerpts_after(
3868                                &prev_excerpt_id,
3869                                buffer_handle.clone(),
3870                                [ExcerptRange {
3871                                    context: start_ix..end_ix,
3872                                    primary: None,
3873                                }],
3874                                cx,
3875                            )
3876                            .pop()
3877                            .unwrap()
3878                    });
3879
3880                    excerpt_ids.insert(excerpt_ix, excerpt_id);
3881                    expected_excerpts.insert(excerpt_ix, (buffer_handle.clone(), anchor_range));
3882                }
3883            }
3884
3885            if rng.gen_bool(0.3) {
3886                multibuffer.update(cx, |multibuffer, cx| {
3887                    old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3888                })
3889            }
3890
3891            let snapshot = multibuffer.read(cx).snapshot(cx);
3892
3893            let mut excerpt_starts = Vec::new();
3894            let mut expected_text = String::new();
3895            let mut expected_buffer_rows = Vec::new();
3896            for (buffer, range) in &expected_excerpts {
3897                let buffer = buffer.read(cx);
3898                let buffer_range = range.to_offset(buffer);
3899
3900                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
3901                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
3902                expected_text.push('\n');
3903
3904                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
3905                    ..=buffer.offset_to_point(buffer_range.end).row;
3906                for row in buffer_row_range {
3907                    expected_buffer_rows.push(Some(row));
3908                }
3909            }
3910            // Remove final trailing newline.
3911            if !expected_excerpts.is_empty() {
3912                expected_text.pop();
3913            }
3914
3915            // Always report one buffer row
3916            if expected_buffer_rows.is_empty() {
3917                expected_buffer_rows.push(Some(0));
3918            }
3919
3920            assert_eq!(snapshot.text(), expected_text);
3921            log::info!("MultiBuffer text: {:?}", expected_text);
3922
3923            assert_eq!(
3924                snapshot.buffer_rows(0).collect::<Vec<_>>(),
3925                expected_buffer_rows,
3926            );
3927
3928            for _ in 0..5 {
3929                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
3930                assert_eq!(
3931                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
3932                    &expected_buffer_rows[start_row..],
3933                    "buffer_rows({})",
3934                    start_row
3935                );
3936            }
3937
3938            assert_eq!(
3939                snapshot.max_buffer_row(),
3940                expected_buffer_rows
3941                    .into_iter()
3942                    .filter_map(|r| r)
3943                    .max()
3944                    .unwrap()
3945            );
3946
3947            let mut excerpt_starts = excerpt_starts.into_iter();
3948            for (buffer, range) in &expected_excerpts {
3949                let buffer_id = buffer.id();
3950                let buffer = buffer.read(cx);
3951                let buffer_range = range.to_offset(buffer);
3952                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
3953                let buffer_start_point_utf16 =
3954                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
3955
3956                let excerpt_start = excerpt_starts.next().unwrap();
3957                let mut offset = excerpt_start.len;
3958                let mut buffer_offset = buffer_range.start;
3959                let mut point = excerpt_start.lines;
3960                let mut buffer_point = buffer_start_point;
3961                let mut point_utf16 = excerpt_start.lines_utf16();
3962                let mut buffer_point_utf16 = buffer_start_point_utf16;
3963                for ch in buffer
3964                    .snapshot()
3965                    .chunks(buffer_range.clone(), false)
3966                    .flat_map(|c| c.text.chars())
3967                {
3968                    for _ in 0..ch.len_utf8() {
3969                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
3970                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
3971                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
3972                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
3973                        assert_eq!(
3974                            left_offset,
3975                            excerpt_start.len + (buffer_left_offset - buffer_range.start),
3976                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
3977                            offset,
3978                            buffer_id,
3979                            buffer_offset,
3980                        );
3981                        assert_eq!(
3982                            right_offset,
3983                            excerpt_start.len + (buffer_right_offset - buffer_range.start),
3984                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
3985                            offset,
3986                            buffer_id,
3987                            buffer_offset,
3988                        );
3989
3990                        let left_point = snapshot.clip_point(point, Bias::Left);
3991                        let right_point = snapshot.clip_point(point, Bias::Right);
3992                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
3993                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
3994                        assert_eq!(
3995                            left_point,
3996                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
3997                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
3998                            point,
3999                            buffer_id,
4000                            buffer_point,
4001                        );
4002                        assert_eq!(
4003                            right_point,
4004                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
4005                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
4006                            point,
4007                            buffer_id,
4008                            buffer_point,
4009                        );
4010
4011                        assert_eq!(
4012                            snapshot.point_to_offset(left_point),
4013                            left_offset,
4014                            "point_to_offset({:?})",
4015                            left_point,
4016                        );
4017                        assert_eq!(
4018                            snapshot.offset_to_point(left_offset),
4019                            left_point,
4020                            "offset_to_point({:?})",
4021                            left_offset,
4022                        );
4023
4024                        offset += 1;
4025                        buffer_offset += 1;
4026                        if ch == '\n' {
4027                            point += Point::new(1, 0);
4028                            buffer_point += Point::new(1, 0);
4029                        } else {
4030                            point += Point::new(0, 1);
4031                            buffer_point += Point::new(0, 1);
4032                        }
4033                    }
4034
4035                    for _ in 0..ch.len_utf16() {
4036                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
4037                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
4038                        let buffer_left_point_utf16 =
4039                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
4040                        let buffer_right_point_utf16 =
4041                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
4042                        assert_eq!(
4043                            left_point_utf16,
4044                            excerpt_start.lines_utf16()
4045                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
4046                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
4047                            point_utf16,
4048                            buffer_id,
4049                            buffer_point_utf16,
4050                        );
4051                        assert_eq!(
4052                            right_point_utf16,
4053                            excerpt_start.lines_utf16()
4054                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
4055                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
4056                            point_utf16,
4057                            buffer_id,
4058                            buffer_point_utf16,
4059                        );
4060
4061                        if ch == '\n' {
4062                            point_utf16 += PointUtf16::new(1, 0);
4063                            buffer_point_utf16 += PointUtf16::new(1, 0);
4064                        } else {
4065                            point_utf16 += PointUtf16::new(0, 1);
4066                            buffer_point_utf16 += PointUtf16::new(0, 1);
4067                        }
4068                    }
4069                }
4070            }
4071
4072            for (row, line) in expected_text.split('\n').enumerate() {
4073                assert_eq!(
4074                    snapshot.line_len(row as u32),
4075                    line.len() as u32,
4076                    "line_len({}).",
4077                    row
4078                );
4079            }
4080
4081            let text_rope = Rope::from(expected_text.as_str());
4082            for _ in 0..10 {
4083                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4084                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
4085
4086                let text_for_range = snapshot
4087                    .text_for_range(start_ix..end_ix)
4088                    .collect::<String>();
4089                assert_eq!(
4090                    text_for_range,
4091                    &expected_text[start_ix..end_ix],
4092                    "incorrect text for range {:?}",
4093                    start_ix..end_ix
4094                );
4095
4096                let excerpted_buffer_ranges = multibuffer
4097                    .read(cx)
4098                    .range_to_buffer_ranges(start_ix..end_ix, cx);
4099                let excerpted_buffers_text = excerpted_buffer_ranges
4100                    .into_iter()
4101                    .map(|(buffer, buffer_range)| {
4102                        buffer
4103                            .read(cx)
4104                            .text_for_range(buffer_range)
4105                            .collect::<String>()
4106                    })
4107                    .collect::<Vec<_>>()
4108                    .join("\n");
4109                assert_eq!(excerpted_buffers_text, text_for_range);
4110
4111                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
4112                assert_eq!(
4113                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
4114                    expected_summary,
4115                    "incorrect summary for range {:?}",
4116                    start_ix..end_ix
4117                );
4118            }
4119
4120            // Anchor resolution
4121            let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
4122            assert_eq!(anchors.len(), summaries.len());
4123            for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
4124                assert!(resolved_offset <= snapshot.len());
4125                assert_eq!(
4126                    snapshot.summary_for_anchor::<usize>(anchor),
4127                    resolved_offset
4128                );
4129            }
4130
4131            for _ in 0..10 {
4132                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
4133                assert_eq!(
4134                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
4135                    expected_text[..end_ix].chars().rev().collect::<String>(),
4136                );
4137            }
4138
4139            for _ in 0..10 {
4140                let end_ix = rng.gen_range(0..=text_rope.len());
4141                let start_ix = rng.gen_range(0..=end_ix);
4142                assert_eq!(
4143                    snapshot
4144                        .bytes_in_range(start_ix..end_ix)
4145                        .flatten()
4146                        .copied()
4147                        .collect::<Vec<_>>(),
4148                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
4149                    "bytes_in_range({:?})",
4150                    start_ix..end_ix,
4151                );
4152            }
4153        }
4154
4155        let snapshot = multibuffer.read(cx).snapshot(cx);
4156        for (old_snapshot, subscription) in old_versions {
4157            let edits = subscription.consume().into_inner();
4158
4159            log::info!(
4160                "applying subscription edits to old text: {:?}: {:?}",
4161                old_snapshot.text(),
4162                edits,
4163            );
4164
4165            let mut text = old_snapshot.text();
4166            for edit in edits {
4167                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
4168                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
4169            }
4170            assert_eq!(text.to_string(), snapshot.text());
4171        }
4172    }
4173
4174    #[gpui::test]
4175    fn test_history(cx: &mut MutableAppContext) {
4176        cx.set_global(Settings::test(cx));
4177        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
4178        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
4179        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
4180        let group_interval = multibuffer.read(cx).history.group_interval;
4181        multibuffer.update(cx, |multibuffer, cx| {
4182            multibuffer.push_excerpts(
4183                buffer_1.clone(),
4184                [ExcerptRange {
4185                    context: 0..buffer_1.read(cx).len(),
4186                    primary: None,
4187                }],
4188                cx,
4189            );
4190            multibuffer.push_excerpts(
4191                buffer_2.clone(),
4192                [ExcerptRange {
4193                    context: 0..buffer_2.read(cx).len(),
4194                    primary: None,
4195                }],
4196                cx,
4197            );
4198        });
4199
4200        let mut now = Instant::now();
4201
4202        multibuffer.update(cx, |multibuffer, cx| {
4203            let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
4204            multibuffer.edit(
4205                [
4206                    (Point::new(0, 0)..Point::new(0, 0), "A"),
4207                    (Point::new(1, 0)..Point::new(1, 0), "A"),
4208                ],
4209                None,
4210                cx,
4211            );
4212            multibuffer.edit(
4213                [
4214                    (Point::new(0, 1)..Point::new(0, 1), "B"),
4215                    (Point::new(1, 1)..Point::new(1, 1), "B"),
4216                ],
4217                None,
4218                cx,
4219            );
4220            multibuffer.end_transaction_at(now, cx);
4221            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4222
4223            // Edit buffer 1 through the multibuffer
4224            now += 2 * group_interval;
4225            multibuffer.start_transaction_at(now, cx);
4226            multibuffer.edit([(2..2, "C")], None, cx);
4227            multibuffer.end_transaction_at(now, cx);
4228            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
4229
4230            // Edit buffer 1 independently
4231            buffer_1.update(cx, |buffer_1, cx| {
4232                buffer_1.start_transaction_at(now);
4233                buffer_1.edit([(3..3, "D")], None, cx);
4234                buffer_1.end_transaction_at(now, cx);
4235
4236                now += 2 * group_interval;
4237                buffer_1.start_transaction_at(now);
4238                buffer_1.edit([(4..4, "E")], None, cx);
4239                buffer_1.end_transaction_at(now, cx);
4240            });
4241            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4242
4243            // An undo in the multibuffer undoes the multibuffer transaction
4244            // and also any individual buffer edits that have occured since
4245            // that transaction.
4246            multibuffer.undo(cx);
4247            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4248
4249            multibuffer.undo(cx);
4250            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4251
4252            multibuffer.redo(cx);
4253            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4254
4255            multibuffer.redo(cx);
4256            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
4257
4258            // Undo buffer 2 independently.
4259            buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
4260            assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
4261
4262            // An undo in the multibuffer undoes the components of the
4263            // the last multibuffer transaction that are not already undone.
4264            multibuffer.undo(cx);
4265            assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
4266
4267            multibuffer.undo(cx);
4268            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4269
4270            multibuffer.redo(cx);
4271            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
4272
4273            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
4274            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4275
4276            // Redo stack gets cleared after an edit.
4277            now += 2 * group_interval;
4278            multibuffer.start_transaction_at(now, cx);
4279            multibuffer.edit([(0..0, "X")], None, cx);
4280            multibuffer.end_transaction_at(now, cx);
4281            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4282            multibuffer.redo(cx);
4283            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4284            multibuffer.undo(cx);
4285            assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
4286            multibuffer.undo(cx);
4287            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4288
4289            // Transactions can be grouped manually.
4290            multibuffer.redo(cx);
4291            multibuffer.redo(cx);
4292            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4293            multibuffer.group_until_transaction(transaction_1, cx);
4294            multibuffer.undo(cx);
4295            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
4296            multibuffer.redo(cx);
4297            assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
4298        });
4299    }
4300}