multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt};
   4use anyhow::Result;
   5use clock::ReplicaId;
   6use collections::HashMap;
   7use gpui::{AppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task};
   8use language::{
   9    Buffer, BufferChunks, BufferSnapshot, Chunk, DiagnosticEntry, Event, File, Language, Selection,
  10    ToOffset as _, ToPoint as _, TransactionId,
  11};
  12use std::{
  13    cell::{Ref, RefCell},
  14    cmp, io,
  15    iter::{self, FromIterator, Peekable},
  16    ops::{Range, Sub},
  17    sync::Arc,
  18    time::{Duration, Instant, SystemTime},
  19};
  20use sum_tree::{Bias, Cursor, SumTree};
  21use text::{
  22    locator::Locator,
  23    rope::TextDimension,
  24    subscription::{Subscription, Topic},
  25    AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary,
  26};
  27use theme::SyntaxTheme;
  28
  29const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
  30
  31pub type ExcerptId = Locator;
  32
  33pub struct MultiBuffer {
  34    snapshot: RefCell<MultiBufferSnapshot>,
  35    buffers: HashMap<usize, BufferState>,
  36    subscriptions: Topic,
  37    singleton: bool,
  38    replica_id: ReplicaId,
  39}
  40
  41pub trait ToOffset: 'static {
  42    fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
  43}
  44
  45pub trait ToPoint: 'static {
  46    fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
  47}
  48
  49pub trait FromAnchor: 'static {
  50    fn from_anchor(anchor: &Anchor, snapshot: &MultiBufferSnapshot) -> Self;
  51}
  52
  53#[derive(Debug)]
  54struct BufferState {
  55    buffer: ModelHandle<Buffer>,
  56    last_version: clock::Global,
  57    last_parse_count: usize,
  58    last_diagnostics_update_count: usize,
  59    excerpts: Vec<ExcerptId>,
  60}
  61
  62#[derive(Clone, Default)]
  63pub struct MultiBufferSnapshot {
  64    excerpts: SumTree<Excerpt>,
  65    parse_count: usize,
  66    diagnostics_update_count: usize,
  67}
  68
  69pub struct ExcerptProperties<'a, T> {
  70    pub buffer: &'a ModelHandle<Buffer>,
  71    pub range: Range<T>,
  72    pub header_height: u8,
  73}
  74
  75#[derive(Clone)]
  76struct Excerpt {
  77    id: ExcerptId,
  78    buffer_id: usize,
  79    buffer: BufferSnapshot,
  80    range: Range<text::Anchor>,
  81    text_summary: TextSummary,
  82    header_height: u8,
  83    has_trailing_newline: bool,
  84}
  85
  86#[derive(Clone, Debug, Default)]
  87struct ExcerptSummary {
  88    excerpt_id: ExcerptId,
  89    text: TextSummary,
  90}
  91
  92pub struct MultiBufferChunks<'a> {
  93    range: Range<usize>,
  94    cursor: Cursor<'a, Excerpt, usize>,
  95    header_height: u8,
  96    has_trailing_newline: bool,
  97    excerpt_chunks: Option<BufferChunks<'a>>,
  98    theme: Option<&'a SyntaxTheme>,
  99}
 100
 101pub struct MultiBufferBytes<'a> {
 102    chunks: Peekable<MultiBufferChunks<'a>>,
 103}
 104
 105impl MultiBuffer {
 106    pub fn new(replica_id: ReplicaId) -> Self {
 107        Self {
 108            snapshot: Default::default(),
 109            buffers: Default::default(),
 110            subscriptions: Default::default(),
 111            singleton: false,
 112            replica_id,
 113        }
 114    }
 115
 116    pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
 117        let mut this = Self::new(buffer.read(cx).replica_id());
 118        this.singleton = true;
 119        this.push_excerpt(
 120            ExcerptProperties {
 121                buffer: &buffer,
 122                range: text::Anchor::min()..text::Anchor::max(),
 123                header_height: 0,
 124            },
 125            cx,
 126        );
 127        this
 128    }
 129
 130    pub fn build_simple(text: &str, cx: &mut MutableAppContext) -> ModelHandle<Self> {
 131        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 132        cx.add_model(|cx| Self::singleton(buffer, cx))
 133    }
 134
 135    pub fn replica_id(&self) -> ReplicaId {
 136        self.replica_id
 137    }
 138
 139    pub fn transaction_group_interval(&self, cx: &AppContext) -> Duration {
 140        self.as_singleton()
 141            .unwrap()
 142            .read(cx)
 143            .transaction_group_interval()
 144    }
 145
 146    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
 147        self.sync(cx);
 148        self.snapshot.borrow().clone()
 149    }
 150
 151    pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
 152        self.sync(cx);
 153        self.snapshot.borrow()
 154    }
 155
 156    pub fn as_singleton(&self) -> Option<&ModelHandle<Buffer>> {
 157        if self.buffers.len() == 1 {
 158            return Some(&self.buffers.values().next().unwrap().buffer);
 159        } else {
 160            None
 161        }
 162    }
 163
 164    pub fn subscribe(&mut self) -> Subscription {
 165        self.subscriptions.subscribe()
 166    }
 167
 168    pub fn edit<I, S, T>(&mut self, ranges: I, new_text: T, cx: &mut ModelContext<Self>)
 169    where
 170        I: IntoIterator<Item = Range<S>>,
 171        S: ToOffset,
 172        T: Into<String>,
 173    {
 174        self.edit_internal(ranges, new_text, false, cx)
 175    }
 176
 177    pub fn edit_with_autoindent<I, S, T>(
 178        &mut self,
 179        ranges: I,
 180        new_text: T,
 181        cx: &mut ModelContext<Self>,
 182    ) where
 183        I: IntoIterator<Item = Range<S>>,
 184        S: ToOffset,
 185        T: Into<String>,
 186    {
 187        self.edit_internal(ranges, new_text, true, cx)
 188    }
 189
 190    pub fn edit_internal<I, S, T>(
 191        &mut self,
 192        ranges_iter: I,
 193        new_text: T,
 194        autoindent: bool,
 195        cx: &mut ModelContext<Self>,
 196    ) where
 197        I: IntoIterator<Item = Range<S>>,
 198        S: ToOffset,
 199        T: Into<String>,
 200    {
 201        if let Some(buffer) = self.as_singleton() {
 202            let snapshot = self.read(cx);
 203            let ranges = ranges_iter
 204                .into_iter()
 205                .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot));
 206            return buffer.update(cx, |buffer, cx| {
 207                if autoindent {
 208                    buffer.edit_with_autoindent(ranges, new_text, cx)
 209                } else {
 210                    buffer.edit(ranges, new_text, cx)
 211                }
 212            });
 213        }
 214
 215        let snapshot = self.read(cx);
 216        let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, bool)>> = Default::default();
 217        let mut cursor = snapshot.excerpts.cursor::<usize>();
 218        for range in ranges_iter {
 219            let start = range.start.to_offset(&snapshot);
 220            let end = range.end.to_offset(&snapshot);
 221            cursor.seek(&start, Bias::Right, &());
 222            let start_excerpt = cursor.item().expect("start offset out of bounds");
 223            let start_overshoot =
 224                (start - cursor.start()).saturating_sub(start_excerpt.header_height as usize);
 225            let buffer_start =
 226                start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot;
 227
 228            cursor.seek(&end, Bias::Right, &());
 229            let end_excerpt = cursor.item().expect("end offset out of bounds");
 230            let end_overshoot =
 231                (end - cursor.start()).saturating_sub(end_excerpt.header_height as usize);
 232            let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot;
 233
 234            if start_excerpt.id == end_excerpt.id {
 235                buffer_edits
 236                    .entry(start_excerpt.buffer_id)
 237                    .or_insert(Vec::new())
 238                    .push((buffer_start..buffer_end, true));
 239            } else {
 240                let start_excerpt_range =
 241                    buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
 242                let end_excerpt_range =
 243                    end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end;
 244                buffer_edits
 245                    .entry(start_excerpt.buffer_id)
 246                    .or_insert(Vec::new())
 247                    .push((start_excerpt_range, true));
 248                buffer_edits
 249                    .entry(end_excerpt.buffer_id)
 250                    .or_insert(Vec::new())
 251                    .push((end_excerpt_range, false));
 252
 253                cursor.seek(&start, Bias::Right, &());
 254                cursor.next(&());
 255                while let Some(excerpt) = cursor.item() {
 256                    if excerpt.id == end_excerpt.id {
 257                        break;
 258                    }
 259
 260                    let excerpt_range = start_excerpt.range.end.to_offset(&start_excerpt.buffer)
 261                        ..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
 262                    buffer_edits
 263                        .entry(excerpt.buffer_id)
 264                        .or_insert(Vec::new())
 265                        .push((excerpt_range, false));
 266                    cursor.next(&());
 267                }
 268            }
 269        }
 270
 271        let new_text = new_text.into();
 272        for (buffer_id, mut edits) in buffer_edits {
 273            edits.sort_unstable_by_key(|(range, _)| range.start);
 274            self.buffers[&buffer_id].buffer.update(cx, |buffer, cx| {
 275                let mut edits = edits.into_iter().peekable();
 276                let mut insertions = Vec::new();
 277                let mut deletions = Vec::new();
 278                while let Some((mut range, mut is_insertion)) = edits.next() {
 279                    while let Some((next_range, next_is_insertion)) = edits.peek() {
 280                        if range.end >= next_range.start {
 281                            range.end = cmp::max(next_range.end, range.end);
 282                            is_insertion |= *next_is_insertion;
 283                            edits.next();
 284                        } else {
 285                            break;
 286                        }
 287                    }
 288
 289                    if is_insertion {
 290                        insertions.push(
 291                            buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 292                        );
 293                    } else {
 294                        deletions.push(
 295                            buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 296                        );
 297                    }
 298                }
 299
 300                if autoindent {
 301                    buffer.edit_with_autoindent(deletions, "", cx);
 302                    buffer.edit_with_autoindent(insertions, new_text.clone(), cx);
 303                } else {
 304                    buffer.edit(deletions, "", cx);
 305                    buffer.edit(insertions, new_text.clone(), cx);
 306                }
 307            })
 308        }
 309    }
 310
 311    pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 312        self.start_transaction_at(Instant::now(), cx)
 313    }
 314
 315    pub(crate) fn start_transaction_at(
 316        &mut self,
 317        now: Instant,
 318        cx: &mut ModelContext<Self>,
 319    ) -> Option<TransactionId> {
 320        // TODO
 321        self.as_singleton()
 322            .unwrap()
 323            .update(cx, |buffer, _| buffer.start_transaction_at(now))
 324    }
 325
 326    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 327        // TODO
 328        self.as_singleton()
 329            .unwrap()
 330            .update(cx, |buffer, cx| buffer.end_transaction(cx))
 331    }
 332
 333    pub(crate) fn end_transaction_at(
 334        &mut self,
 335        now: Instant,
 336        cx: &mut ModelContext<Self>,
 337    ) -> Option<TransactionId> {
 338        // TODO
 339        self.as_singleton()
 340            .unwrap()
 341            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 342    }
 343
 344    pub fn set_active_selections(
 345        &mut self,
 346        selections: &[Selection<Anchor>],
 347        cx: &mut ModelContext<Self>,
 348    ) {
 349        let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
 350            Default::default();
 351        let snapshot = self.read(cx);
 352        let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
 353        for selection in selections {
 354            cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &());
 355            while let Some(excerpt) = cursor.item() {
 356                if excerpt.id > selection.end.excerpt_id {
 357                    break;
 358                }
 359
 360                let mut start = excerpt.range.start.clone();
 361                let mut end = excerpt.range.end.clone();
 362                if excerpt.id == selection.start.excerpt_id {
 363                    start = selection.start.text_anchor.clone();
 364                }
 365                if excerpt.id == selection.end.excerpt_id {
 366                    end = selection.end.text_anchor.clone();
 367                }
 368                selections_by_buffer
 369                    .entry(excerpt.buffer_id)
 370                    .or_default()
 371                    .push(Selection {
 372                        id: selection.id,
 373                        start,
 374                        end,
 375                        reversed: selection.reversed,
 376                        goal: selection.goal,
 377                    });
 378
 379                cursor.next(&());
 380            }
 381        }
 382
 383        for (buffer_id, mut selections) in selections_by_buffer {
 384            self.buffers[&buffer_id].buffer.update(cx, |buffer, cx| {
 385                selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap());
 386                let mut selections = selections.into_iter().peekable();
 387                let merged_selections = Arc::from_iter(iter::from_fn(|| {
 388                    let mut selection = selections.next()?;
 389                    while let Some(next_selection) = selections.peek() {
 390                        if selection
 391                            .end
 392                            .cmp(&next_selection.start, buffer)
 393                            .unwrap()
 394                            .is_ge()
 395                        {
 396                            let next_selection = selections.next().unwrap();
 397                            if next_selection
 398                                .end
 399                                .cmp(&selection.end, buffer)
 400                                .unwrap()
 401                                .is_ge()
 402                            {
 403                                selection.end = next_selection.end;
 404                            }
 405                        } else {
 406                            break;
 407                        }
 408                    }
 409                    Some(selection)
 410                }));
 411                buffer.set_active_selections(merged_selections, cx);
 412            });
 413        }
 414    }
 415
 416    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 417        for buffer in self.buffers.values() {
 418            buffer
 419                .buffer
 420                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 421        }
 422    }
 423
 424    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 425        // TODO
 426        self.as_singleton()
 427            .unwrap()
 428            .update(cx, |buffer, cx| buffer.undo(cx))
 429    }
 430
 431    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 432        // TODO
 433        self.as_singleton()
 434            .unwrap()
 435            .update(cx, |buffer, cx| buffer.redo(cx))
 436    }
 437
 438    pub fn push_excerpt<O>(
 439        &mut self,
 440        props: ExcerptProperties<O>,
 441        cx: &mut ModelContext<Self>,
 442    ) -> ExcerptId
 443    where
 444        O: text::ToOffset,
 445    {
 446        self.sync(cx);
 447
 448        let buffer = &props.buffer;
 449        cx.subscribe(buffer, Self::on_buffer_event).detach();
 450
 451        let buffer = props.buffer.read(cx);
 452        let range = buffer.anchor_before(&props.range.start)..buffer.anchor_after(&props.range.end);
 453        let mut snapshot = self.snapshot.borrow_mut();
 454        let prev_id = snapshot.excerpts.last().map(|e| &e.id);
 455        let id = ExcerptId::between(prev_id.unwrap_or(&ExcerptId::min()), &ExcerptId::max());
 456
 457        let edit_start = snapshot.excerpts.summary().text.bytes;
 458        let excerpt = Excerpt::new(
 459            id.clone(),
 460            props.buffer.id(),
 461            buffer.snapshot(),
 462            range,
 463            props.header_height,
 464            !self.singleton,
 465        );
 466        let edit = Edit {
 467            old: edit_start..edit_start,
 468            new: edit_start..edit_start + excerpt.text_summary.bytes,
 469        };
 470        snapshot.excerpts.push(excerpt, &());
 471        self.buffers
 472            .entry(props.buffer.id())
 473            .or_insert_with(|| BufferState {
 474                buffer: props.buffer.clone(),
 475                last_version: buffer.version(),
 476                last_parse_count: buffer.parse_count(),
 477                last_diagnostics_update_count: buffer.diagnostics_update_count(),
 478                excerpts: Default::default(),
 479            })
 480            .excerpts
 481            .push(id.clone());
 482
 483        self.subscriptions.publish_mut([edit]);
 484
 485        id
 486    }
 487
 488    fn on_buffer_event(
 489        &mut self,
 490        _: ModelHandle<Buffer>,
 491        event: &Event,
 492        cx: &mut ModelContext<Self>,
 493    ) {
 494        cx.emit(event.clone());
 495    }
 496
 497    pub fn save(
 498        &mut self,
 499        cx: &mut ModelContext<Self>,
 500    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 501        self.as_singleton()
 502            .unwrap()
 503            .update(cx, |buffer, cx| buffer.save(cx))
 504    }
 505
 506    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 507        self.buffers
 508            .values()
 509            .next()
 510            .and_then(|state| state.buffer.read(cx).language())
 511    }
 512
 513    pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
 514        self.as_singleton().unwrap().read(cx).file()
 515    }
 516
 517    pub fn is_dirty(&self, cx: &AppContext) -> bool {
 518        self.as_singleton().unwrap().read(cx).is_dirty()
 519    }
 520
 521    pub fn has_conflict(&self, cx: &AppContext) -> bool {
 522        self.as_singleton().unwrap().read(cx).has_conflict()
 523    }
 524
 525    pub fn is_parsing(&self, cx: &AppContext) -> bool {
 526        self.as_singleton().unwrap().read(cx).is_parsing()
 527    }
 528
 529    fn sync(&self, cx: &AppContext) {
 530        let mut snapshot = self.snapshot.borrow_mut();
 531        let mut excerpts_to_edit = Vec::new();
 532        let mut reparsed = false;
 533        let mut diagnostics_updated = false;
 534        for buffer_state in self.buffers.values() {
 535            let buffer = buffer_state.buffer.read(cx);
 536            let buffer_edited = buffer.version().gt(&buffer_state.last_version);
 537            let buffer_reparsed = buffer.parse_count() > buffer_state.last_parse_count;
 538            let buffer_diagnostics_updated =
 539                buffer.diagnostics_update_count() > buffer_state.last_diagnostics_update_count;
 540            if buffer_edited || buffer_reparsed || buffer_diagnostics_updated {
 541                excerpts_to_edit.extend(
 542                    buffer_state
 543                        .excerpts
 544                        .iter()
 545                        .map(|excerpt_id| (excerpt_id, buffer_state, buffer_edited)),
 546                );
 547            }
 548
 549            reparsed |= buffer_reparsed;
 550            diagnostics_updated |= buffer_diagnostics_updated;
 551        }
 552        if reparsed {
 553            snapshot.parse_count += 1;
 554        }
 555        if diagnostics_updated {
 556            snapshot.diagnostics_update_count += 1;
 557        }
 558        excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
 559
 560        let mut edits = Vec::new();
 561        let mut new_excerpts = SumTree::new();
 562        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 563
 564        for (id, buffer_state, buffer_edited) in excerpts_to_edit {
 565            new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
 566            let old_excerpt = cursor.item().unwrap();
 567            let buffer = buffer_state.buffer.read(cx);
 568
 569            let mut new_excerpt;
 570            if buffer_edited {
 571                edits.extend(
 572                    buffer
 573                        .edits_since_in_range::<usize>(
 574                            old_excerpt.buffer.version(),
 575                            old_excerpt.range.clone(),
 576                        )
 577                        .map(|mut edit| {
 578                            let excerpt_old_start =
 579                                cursor.start().1 + old_excerpt.header_height as usize;
 580                            let excerpt_new_start = new_excerpts.summary().text.bytes
 581                                + old_excerpt.header_height as usize;
 582                            edit.old.start += excerpt_old_start;
 583                            edit.old.end += excerpt_old_start;
 584                            edit.new.start += excerpt_new_start;
 585                            edit.new.end += excerpt_new_start;
 586                            edit
 587                        }),
 588                );
 589
 590                new_excerpt = Excerpt::new(
 591                    id.clone(),
 592                    buffer_state.buffer.id(),
 593                    buffer.snapshot(),
 594                    old_excerpt.range.clone(),
 595                    old_excerpt.header_height,
 596                    !self.singleton,
 597                );
 598            } else {
 599                new_excerpt = old_excerpt.clone();
 600                new_excerpt.buffer = buffer.snapshot();
 601            }
 602
 603            new_excerpts.push(new_excerpt, &());
 604            cursor.next(&());
 605        }
 606        new_excerpts.push_tree(cursor.suffix(&()), &());
 607
 608        drop(cursor);
 609        snapshot.excerpts = new_excerpts;
 610
 611        self.subscriptions.publish(edits);
 612    }
 613}
 614
 615#[cfg(any(test, feature = "test-support"))]
 616impl MultiBuffer {
 617    pub fn randomly_edit<R: rand::Rng>(
 618        &mut self,
 619        rng: &mut R,
 620        count: usize,
 621        cx: &mut ModelContext<Self>,
 622    ) {
 623        self.as_singleton()
 624            .unwrap()
 625            .update(cx, |buffer, cx| buffer.randomly_edit(rng, count, cx));
 626        self.sync(cx);
 627    }
 628}
 629
 630impl Entity for MultiBuffer {
 631    type Event = language::Event;
 632}
 633
 634impl MultiBufferSnapshot {
 635    pub fn text(&self) -> String {
 636        self.chunks(0..self.len(), None)
 637            .map(|chunk| chunk.text)
 638            .collect()
 639    }
 640
 641    pub fn reversed_chars_at<'a, T: ToOffset>(
 642        &'a self,
 643        position: T,
 644    ) -> impl Iterator<Item = char> + 'a {
 645        // TODO
 646        let offset = position.to_offset(self);
 647        self.as_singleton().unwrap().reversed_chars_at(offset)
 648    }
 649
 650    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
 651        let offset = position.to_offset(self);
 652        self.text_for_range(offset..self.len())
 653            .flat_map(|chunk| chunk.chars())
 654    }
 655
 656    pub fn text_for_range<'a, T: ToOffset>(
 657        &'a self,
 658        range: Range<T>,
 659    ) -> impl Iterator<Item = &'a str> {
 660        self.chunks(range, None).map(|chunk| chunk.text)
 661    }
 662
 663    pub fn is_line_blank(&self, row: u32) -> bool {
 664        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
 665            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
 666    }
 667
 668    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
 669    where
 670        T: ToOffset,
 671    {
 672        let offset = position.to_offset(self);
 673        self.as_singleton().unwrap().contains_str_at(offset, needle)
 674    }
 675
 676    fn as_singleton(&self) -> Option<&BufferSnapshot> {
 677        let mut excerpts = self.excerpts.iter();
 678        let buffer = excerpts.next().map(|excerpt| &excerpt.buffer);
 679        if excerpts.next().is_none() {
 680            buffer
 681        } else {
 682            None
 683        }
 684    }
 685
 686    pub fn len(&self) -> usize {
 687        self.excerpts.summary().text.bytes
 688    }
 689
 690    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
 691        let mut cursor = self.excerpts.cursor::<usize>();
 692        cursor.seek(&offset, Bias::Right, &());
 693        if let Some(excerpt) = cursor.item() {
 694            let start_after_header = *cursor.start() + excerpt.header_height as usize;
 695            if offset < start_after_header {
 696                *cursor.start()
 697            } else {
 698                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 699                let buffer_offset = excerpt
 700                    .buffer
 701                    .clip_offset(excerpt_start + (offset - start_after_header), bias);
 702                let offset_in_excerpt = if buffer_offset > excerpt_start {
 703                    buffer_offset - excerpt_start
 704                } else {
 705                    0
 706                };
 707                start_after_header + offset_in_excerpt
 708            }
 709        } else {
 710            self.excerpts.summary().text.bytes
 711        }
 712    }
 713
 714    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
 715        let mut cursor = self.excerpts.cursor::<Point>();
 716        cursor.seek(&point, Bias::Right, &());
 717        if let Some(excerpt) = cursor.item() {
 718            let start_after_header = *cursor.start() + Point::new(excerpt.header_height as u32, 0);
 719            if point < start_after_header {
 720                *cursor.start()
 721            } else {
 722                let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
 723                let buffer_point = excerpt
 724                    .buffer
 725                    .clip_point(excerpt_start + (point - start_after_header), bias);
 726                let point_in_excerpt = if buffer_point > excerpt_start {
 727                    buffer_point - excerpt_start
 728                } else {
 729                    Point::zero()
 730                };
 731                start_after_header + point_in_excerpt
 732            }
 733        } else {
 734            self.excerpts.summary().text.lines
 735        }
 736    }
 737
 738    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
 739        let mut cursor = self.excerpts.cursor::<PointUtf16>();
 740        cursor.seek(&point, Bias::Right, &());
 741        if let Some(excerpt) = cursor.item() {
 742            let start_after_header =
 743                *cursor.start() + PointUtf16::new(excerpt.header_height as u32, 0);
 744            if point < start_after_header {
 745                *cursor.start()
 746            } else {
 747                let excerpt_start = excerpt
 748                    .buffer
 749                    .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
 750                let buffer_point = excerpt
 751                    .buffer
 752                    .clip_point_utf16(excerpt_start + (point - start_after_header), bias);
 753                let point_in_excerpt = if buffer_point > excerpt_start {
 754                    buffer_point - excerpt_start
 755                } else {
 756                    PointUtf16::new(0, 0)
 757                };
 758                start_after_header + point_in_excerpt
 759            }
 760        } else {
 761            self.excerpts.summary().text.lines_utf16
 762        }
 763    }
 764
 765    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
 766        MultiBufferBytes {
 767            chunks: self.chunks(range, None).peekable(),
 768        }
 769    }
 770
 771    pub fn chunks<'a, T: ToOffset>(
 772        &'a self,
 773        range: Range<T>,
 774        theme: Option<&'a SyntaxTheme>,
 775    ) -> MultiBufferChunks<'a> {
 776        let mut result = MultiBufferChunks {
 777            range: 0..range.end.to_offset(self),
 778            cursor: self.excerpts.cursor::<usize>(),
 779            header_height: 0,
 780            excerpt_chunks: None,
 781            has_trailing_newline: false,
 782            theme,
 783        };
 784        result.seek(range.start.to_offset(self));
 785        result
 786    }
 787
 788    pub fn offset_to_point(&self, offset: usize) -> Point {
 789        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
 790        cursor.seek(&offset, Bias::Right, &());
 791        if let Some(excerpt) = cursor.item() {
 792            let (start_offset, start_point) = cursor.start();
 793            let overshoot = offset - start_offset;
 794            let header_height = excerpt.header_height as usize;
 795            if overshoot < header_height {
 796                *start_point
 797            } else {
 798                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
 799                let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
 800                let buffer_point = excerpt
 801                    .buffer
 802                    .offset_to_point(excerpt_start_offset + (overshoot - header_height));
 803                *start_point
 804                    + Point::new(header_height as u32, 0)
 805                    + (buffer_point - excerpt_start_point)
 806            }
 807        } else {
 808            self.excerpts.summary().text.lines
 809        }
 810    }
 811
 812    pub fn point_to_offset(&self, point: Point) -> usize {
 813        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
 814        cursor.seek(&point, Bias::Right, &());
 815        if let Some(excerpt) = cursor.item() {
 816            let (start_point, start_offset) = cursor.start();
 817            let overshoot = point - start_point;
 818            let header_height = Point::new(excerpt.header_height as u32, 0);
 819            if overshoot < header_height {
 820                *start_offset
 821            } else {
 822                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
 823                let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
 824                let buffer_offset = excerpt
 825                    .buffer
 826                    .point_to_offset(excerpt_start_point + (overshoot - header_height));
 827                *start_offset + excerpt.header_height as usize + buffer_offset
 828                    - excerpt_start_offset
 829            }
 830        } else {
 831            self.excerpts.summary().text.bytes
 832        }
 833    }
 834
 835    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
 836        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
 837        cursor.seek(&point, Bias::Right, &());
 838        if let Some(excerpt) = cursor.item() {
 839            let (start_point, start_offset) = cursor.start();
 840            let overshoot = point - start_point;
 841            let header_height = PointUtf16::new(excerpt.header_height as u32, 0);
 842            if overshoot < header_height {
 843                *start_offset
 844            } else {
 845                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
 846                let excerpt_start_point = excerpt
 847                    .buffer
 848                    .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
 849                let buffer_offset = excerpt
 850                    .buffer
 851                    .point_utf16_to_offset(excerpt_start_point + (overshoot - header_height));
 852                *start_offset
 853                    + excerpt.header_height as usize
 854                    + (buffer_offset - excerpt_start_offset)
 855            }
 856        } else {
 857            self.excerpts.summary().text.bytes
 858        }
 859    }
 860
 861    pub fn indent_column_for_line(&self, row: u32) -> u32 {
 862        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
 863            buffer
 864                .indent_column_for_line(range.start.row)
 865                .min(range.end.column)
 866                .saturating_sub(range.start.column)
 867        } else {
 868            0
 869        }
 870    }
 871
 872    pub fn line_len(&self, row: u32) -> u32 {
 873        if let Some((_, range)) = self.buffer_line_for_row(row) {
 874            range.end.column - range.start.column
 875        } else {
 876            0
 877        }
 878    }
 879
 880    fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
 881        let mut cursor = self.excerpts.cursor::<Point>();
 882        cursor.seek(&Point::new(row, 0), Bias::Right, &());
 883        if let Some(excerpt) = cursor.item() {
 884            let overshoot = row - cursor.start().row;
 885            let header_height = excerpt.header_height as u32;
 886            if overshoot >= header_height {
 887                let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
 888                let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
 889                let buffer_row = excerpt_start.row + overshoot - header_height;
 890                let line_start = Point::new(buffer_row, 0);
 891                let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
 892                return Some((
 893                    &excerpt.buffer,
 894                    line_start.max(excerpt_start)..line_end.min(excerpt_end),
 895                ));
 896            }
 897        }
 898        None
 899    }
 900
 901    pub fn max_point(&self) -> Point {
 902        self.text_summary().lines
 903    }
 904
 905    pub fn text_summary(&self) -> TextSummary {
 906        self.excerpts.summary().text
 907    }
 908
 909    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
 910    where
 911        D: TextDimension,
 912        O: ToOffset,
 913    {
 914        let mut summary = D::default();
 915        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
 916        let mut cursor = self.excerpts.cursor::<usize>();
 917        cursor.seek(&range.start, Bias::Right, &());
 918        if let Some(excerpt) = cursor.item() {
 919            let start_after_header = cursor.start() + excerpt.header_height as usize;
 920            if range.start < start_after_header {
 921                let header_len = cmp::min(range.end, start_after_header) - range.start;
 922                summary.add_assign(&D::from_text_summary(&TextSummary {
 923                    bytes: header_len,
 924                    lines: Point::new(header_len as u32, 0),
 925                    lines_utf16: PointUtf16::new(header_len as u32, 0),
 926                    first_line_chars: 0,
 927                    last_line_chars: 0,
 928                    longest_row: 0,
 929                    longest_row_chars: 0,
 930                }));
 931                range.start = start_after_header;
 932                range.end = cmp::max(range.start, range.end);
 933            }
 934
 935            let mut end_before_newline = cursor.end(&());
 936            if excerpt.has_trailing_newline {
 937                end_before_newline -= 1;
 938            }
 939
 940            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 941            let start_in_excerpt = excerpt_start + (range.start - start_after_header);
 942            let end_in_excerpt =
 943                excerpt_start + (cmp::min(end_before_newline, range.end) - start_after_header);
 944            summary.add_assign(
 945                &excerpt
 946                    .buffer
 947                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
 948            );
 949
 950            if range.end > end_before_newline {
 951                summary.add_assign(&D::from_text_summary(&TextSummary {
 952                    bytes: 1,
 953                    lines: Point::new(1 as u32, 0),
 954                    lines_utf16: PointUtf16::new(1 as u32, 0),
 955                    first_line_chars: 0,
 956                    last_line_chars: 0,
 957                    longest_row: 0,
 958                    longest_row_chars: 0,
 959                }));
 960            }
 961
 962            cursor.next(&());
 963        }
 964
 965        if range.end > *cursor.start() {
 966            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
 967                &range.end,
 968                Bias::Right,
 969                &(),
 970            )));
 971            if let Some(excerpt) = cursor.item() {
 972                let start_after_header = cursor.start() + excerpt.header_height as usize;
 973                let header_len =
 974                    cmp::min(range.end - cursor.start(), excerpt.header_height as usize);
 975                summary.add_assign(&D::from_text_summary(&TextSummary {
 976                    bytes: header_len,
 977                    lines: Point::new(header_len as u32, 0),
 978                    lines_utf16: PointUtf16::new(header_len as u32, 0),
 979                    first_line_chars: 0,
 980                    last_line_chars: 0,
 981                    longest_row: 0,
 982                    longest_row_chars: 0,
 983                }));
 984                range.end = cmp::max(start_after_header, range.end);
 985
 986                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 987                let end_in_excerpt = excerpt_start + (range.end - start_after_header);
 988                summary.add_assign(
 989                    &excerpt
 990                        .buffer
 991                        .text_summary_for_range(excerpt_start..end_in_excerpt),
 992                );
 993                cursor.next(&());
 994            }
 995        }
 996
 997        summary
 998    }
 999
1000    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1001    where
1002        D: TextDimension + Ord + Sub<D, Output = D>,
1003    {
1004        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1005        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1006        if let Some(excerpt) = cursor.item() {
1007            if excerpt.id == anchor.excerpt_id {
1008                let mut excerpt_start = D::from_text_summary(&cursor.start().text);
1009                excerpt_start.add_summary(&excerpt.header_summary(), &());
1010                let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1011                let buffer_point = anchor.text_anchor.summary::<D>(&excerpt.buffer);
1012                if buffer_point > excerpt_buffer_start {
1013                    excerpt_start.add_assign(&(buffer_point - excerpt_buffer_start));
1014                }
1015                return excerpt_start;
1016            }
1017        }
1018        D::from_text_summary(&cursor.start().text)
1019    }
1020
1021    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1022    where
1023        D: TextDimension + Ord + Sub<D, Output = D>,
1024        I: 'a + IntoIterator<Item = &'a Anchor>,
1025    {
1026        let mut anchors = anchors.into_iter().peekable();
1027        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1028        let mut summaries = Vec::new();
1029        while let Some(anchor) = anchors.peek() {
1030            let excerpt_id = &anchor.excerpt_id;
1031            let excerpt_anchors = iter::from_fn(|| {
1032                let anchor = anchors.peek()?;
1033                if anchor.excerpt_id == *excerpt_id {
1034                    Some(&anchors.next().unwrap().text_anchor)
1035                } else {
1036                    None
1037                }
1038            });
1039
1040            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1041            if let Some(excerpt) = cursor.item() {
1042                if excerpt.id == *excerpt_id {
1043                    let mut excerpt_start = D::from_text_summary(&cursor.start().text);
1044                    excerpt_start.add_summary(&excerpt.header_summary(), &());
1045                    let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1046                    summaries.extend(
1047                        excerpt
1048                            .buffer
1049                            .summaries_for_anchors::<D, _>(excerpt_anchors)
1050                            .map(move |summary| {
1051                                let mut excerpt_start = excerpt_start.clone();
1052                                let excerpt_buffer_start = excerpt_buffer_start.clone();
1053                                if summary > excerpt_buffer_start {
1054                                    excerpt_start.add_assign(&(summary - excerpt_buffer_start));
1055                                }
1056                                excerpt_start
1057                            }),
1058                    );
1059                    continue;
1060                }
1061            }
1062
1063            let summary = D::from_text_summary(&cursor.start().text);
1064            summaries.extend(excerpt_anchors.map(|_| summary.clone()));
1065        }
1066
1067        summaries
1068    }
1069
1070    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1071        self.anchor_at(position, Bias::Left)
1072    }
1073
1074    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1075        self.anchor_at(position, Bias::Right)
1076    }
1077
1078    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1079        let offset = position.to_offset(self);
1080        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1081        cursor.seek(&offset, bias, &());
1082        if let Some(excerpt) = cursor.item() {
1083            let overshoot =
1084                (offset - cursor.start().0).saturating_sub(excerpt.header_height as usize);
1085            let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1086            Anchor {
1087                excerpt_id: excerpt.id.clone(),
1088                text_anchor: excerpt.buffer.anchor_at(buffer_start + overshoot, bias),
1089            }
1090        } else if offset == 0 && bias == Bias::Left {
1091            Anchor::min()
1092        } else {
1093            Anchor::max()
1094        }
1095    }
1096
1097    pub fn parse_count(&self) -> usize {
1098        self.parse_count
1099    }
1100
1101    pub fn enclosing_bracket_ranges<T: ToOffset>(
1102        &self,
1103        range: Range<T>,
1104    ) -> Option<(Range<usize>, Range<usize>)> {
1105        let range = range.start.to_offset(self)..range.end.to_offset(self);
1106        self.as_singleton().unwrap().enclosing_bracket_ranges(range)
1107    }
1108
1109    pub fn diagnostics_update_count(&self) -> usize {
1110        self.diagnostics_update_count
1111    }
1112
1113    pub fn language(&self) -> Option<&Arc<Language>> {
1114        self.excerpts
1115            .iter()
1116            .next()
1117            .and_then(|excerpt| excerpt.buffer.language())
1118    }
1119
1120    pub fn diagnostic_group<'a, O>(
1121        &'a self,
1122        group_id: usize,
1123    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1124    where
1125        O: text::FromAnchor + 'a,
1126    {
1127        self.as_singleton().unwrap().diagnostic_group(group_id)
1128    }
1129
1130    pub fn diagnostics_in_range<'a, T, O>(
1131        &'a self,
1132        range: Range<T>,
1133    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1134    where
1135        T: 'a + ToOffset,
1136        O: 'a + text::FromAnchor,
1137    {
1138        let range = range.start.to_offset(self)..range.end.to_offset(self);
1139        self.as_singleton().unwrap().diagnostics_in_range(range)
1140    }
1141
1142    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1143        let range = range.start.to_offset(self)..range.end.to_offset(self);
1144        self.as_singleton()
1145            .unwrap()
1146            .range_for_syntax_ancestor(range)
1147    }
1148
1149    fn buffer_snapshot_for_excerpt<'a>(
1150        &'a self,
1151        excerpt_id: &'a ExcerptId,
1152    ) -> Option<&'a BufferSnapshot> {
1153        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1154        cursor.seek(&Some(excerpt_id), Bias::Left, &());
1155        if let Some(excerpt) = cursor.item() {
1156            if excerpt.id == *excerpt_id {
1157                return Some(&excerpt.buffer);
1158            }
1159        }
1160        None
1161    }
1162
1163    pub fn remote_selections_in_range<'a>(
1164        &'a self,
1165        range: &'a Range<Anchor>,
1166    ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1167        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1168        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1169        cursor
1170            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1171            .flat_map(move |excerpt| {
1172                let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1173                if excerpt.id == range.start.excerpt_id {
1174                    query_range.start = range.start.text_anchor.clone();
1175                }
1176                if excerpt.id == range.end.excerpt_id {
1177                    query_range.end = range.end.text_anchor.clone();
1178                }
1179
1180                excerpt
1181                    .buffer
1182                    .remote_selections_in_range(query_range)
1183                    .flat_map(move |(replica_id, selections)| {
1184                        selections.map(move |selection| {
1185                            let mut start = Anchor {
1186                                excerpt_id: excerpt.id.clone(),
1187                                text_anchor: selection.start.clone(),
1188                            };
1189                            let mut end = Anchor {
1190                                excerpt_id: excerpt.id.clone(),
1191                                text_anchor: selection.end.clone(),
1192                            };
1193                            if range.start.cmp(&start, self).unwrap().is_gt() {
1194                                start = range.start.clone();
1195                            }
1196                            if range.end.cmp(&end, self).unwrap().is_lt() {
1197                                end = range.end.clone();
1198                            }
1199
1200                            (
1201                                replica_id,
1202                                Selection {
1203                                    id: selection.id,
1204                                    start,
1205                                    end,
1206                                    reversed: selection.reversed,
1207                                    goal: selection.goal,
1208                                },
1209                            )
1210                        })
1211                    })
1212            })
1213    }
1214}
1215
1216impl Excerpt {
1217    fn new(
1218        id: ExcerptId,
1219        buffer_id: usize,
1220        buffer: BufferSnapshot,
1221        range: Range<text::Anchor>,
1222        header_height: u8,
1223        has_trailing_newline: bool,
1224    ) -> Self {
1225        let mut text_summary =
1226            buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer));
1227        if header_height > 0 {
1228            text_summary.first_line_chars = 0;
1229            text_summary.lines.row += header_height as u32;
1230            text_summary.lines_utf16.row += header_height as u32;
1231            text_summary.bytes += header_height as usize;
1232            text_summary.longest_row += header_height as u32;
1233        }
1234        if has_trailing_newline {
1235            text_summary.last_line_chars = 0;
1236            text_summary.lines.row += 1;
1237            text_summary.lines.column = 0;
1238            text_summary.lines_utf16.row += 1;
1239            text_summary.lines_utf16.column = 0;
1240            text_summary.bytes += 1;
1241        }
1242
1243        Excerpt {
1244            id,
1245            buffer_id,
1246            buffer,
1247            range,
1248            text_summary,
1249            header_height,
1250            has_trailing_newline,
1251        }
1252    }
1253
1254    fn header_summary(&self) -> TextSummary {
1255        TextSummary {
1256            bytes: self.header_height as usize,
1257            lines: Point::new(self.header_height as u32, 0),
1258            lines_utf16: PointUtf16::new(self.header_height as u32, 0),
1259            first_line_chars: 0,
1260            last_line_chars: 0,
1261            longest_row: 0,
1262            longest_row_chars: 0,
1263        }
1264    }
1265}
1266
1267impl sum_tree::Item for Excerpt {
1268    type Summary = ExcerptSummary;
1269
1270    fn summary(&self) -> Self::Summary {
1271        ExcerptSummary {
1272            excerpt_id: self.id.clone(),
1273            text: self.text_summary.clone(),
1274        }
1275    }
1276}
1277
1278impl sum_tree::Summary for ExcerptSummary {
1279    type Context = ();
1280
1281    fn add_summary(&mut self, summary: &Self, _: &()) {
1282        debug_assert!(summary.excerpt_id > self.excerpt_id);
1283        self.excerpt_id = summary.excerpt_id.clone();
1284        self.text.add_summary(&summary.text, &());
1285    }
1286}
1287
1288impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
1289    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1290        *self += &summary.text;
1291    }
1292}
1293
1294impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
1295    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1296        *self += summary.text.bytes;
1297    }
1298}
1299
1300impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
1301    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1302        Ord::cmp(self, &cursor_location.text.bytes)
1303    }
1304}
1305
1306impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
1307    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1308        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
1309    }
1310}
1311
1312impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
1313    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1314        *self += summary.text.lines;
1315    }
1316}
1317
1318impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
1319    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1320        *self += summary.text.lines_utf16
1321    }
1322}
1323
1324impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
1325    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1326        *self = Some(&summary.excerpt_id);
1327    }
1328}
1329
1330impl<'a> MultiBufferChunks<'a> {
1331    pub fn offset(&self) -> usize {
1332        self.range.start
1333    }
1334
1335    pub fn seek(&mut self, offset: usize) {
1336        self.range.start = offset;
1337        self.cursor.seek_forward(&offset, Bias::Right, &());
1338        self.header_height = 0;
1339        self.excerpt_chunks = None;
1340        if let Some(excerpt) = self.cursor.item() {
1341            let buffer_range = excerpt.range.to_offset(&excerpt.buffer);
1342            self.header_height = excerpt.header_height;
1343            self.has_trailing_newline = excerpt.has_trailing_newline;
1344
1345            let buffer_start;
1346            let start_overshoot = self.range.start - self.cursor.start();
1347            if start_overshoot < excerpt.header_height as usize {
1348                self.header_height -= start_overshoot as u8;
1349                buffer_start = buffer_range.start;
1350            } else {
1351                buffer_start =
1352                    buffer_range.start + start_overshoot - excerpt.header_height as usize;
1353                self.header_height = 0;
1354            }
1355
1356            let buffer_end;
1357            let end_overshoot = self.range.end - self.cursor.start();
1358            if end_overshoot < excerpt.header_height as usize {
1359                self.header_height -= excerpt.header_height - end_overshoot as u8;
1360                buffer_end = buffer_start;
1361            } else {
1362                buffer_end = cmp::min(
1363                    buffer_range.end,
1364                    buffer_range.start + end_overshoot - excerpt.header_height as usize,
1365                );
1366            }
1367
1368            self.excerpt_chunks = Some(excerpt.buffer.chunks(buffer_start..buffer_end, self.theme));
1369        }
1370    }
1371}
1372
1373impl<'a> Iterator for MultiBufferChunks<'a> {
1374    type Item = Chunk<'a>;
1375
1376    fn next(&mut self) -> Option<Self::Item> {
1377        loop {
1378            if self.header_height > 0 {
1379                let chunk = Chunk {
1380                    text: unsafe {
1381                        std::str::from_utf8_unchecked(&NEWLINES[..self.header_height as usize])
1382                    },
1383                    ..Default::default()
1384                };
1385                self.range.start += self.header_height as usize;
1386                self.header_height = 0;
1387                return Some(chunk);
1388            }
1389
1390            if let Some(excerpt_chunks) = self.excerpt_chunks.as_mut() {
1391                if let Some(chunk) = excerpt_chunks.next() {
1392                    self.range.start += chunk.text.len();
1393                    return Some(chunk);
1394                }
1395                self.excerpt_chunks.take();
1396                if self.has_trailing_newline && self.cursor.end(&()) <= self.range.end {
1397                    self.range.start += 1;
1398                    return Some(Chunk {
1399                        text: "\n",
1400                        ..Default::default()
1401                    });
1402                }
1403            }
1404
1405            self.cursor.next(&());
1406            if *self.cursor.start() >= self.range.end {
1407                return None;
1408            }
1409
1410            let excerpt = self.cursor.item()?;
1411            let buffer_range = excerpt.range.to_offset(&excerpt.buffer);
1412
1413            let buffer_end = cmp::min(
1414                buffer_range.end,
1415                buffer_range.start + self.range.end
1416                    - excerpt.header_height as usize
1417                    - self.cursor.start(),
1418            );
1419
1420            self.header_height = excerpt.header_height;
1421            self.has_trailing_newline = excerpt.has_trailing_newline;
1422            self.excerpt_chunks = Some(
1423                excerpt
1424                    .buffer
1425                    .chunks(buffer_range.start..buffer_end, self.theme),
1426            );
1427        }
1428    }
1429}
1430
1431impl<'a> Iterator for MultiBufferBytes<'a> {
1432    type Item = &'a [u8];
1433
1434    fn next(&mut self) -> Option<Self::Item> {
1435        self.chunks.next().map(|chunk| chunk.text.as_bytes())
1436    }
1437}
1438
1439impl<'a> io::Read for MultiBufferBytes<'a> {
1440    fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1441        todo!()
1442    }
1443}
1444
1445impl ToOffset for Point {
1446    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
1447        snapshot.point_to_offset(*self)
1448    }
1449}
1450
1451impl ToOffset for PointUtf16 {
1452    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
1453        snapshot.point_utf16_to_offset(*self)
1454    }
1455}
1456
1457impl ToOffset for usize {
1458    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
1459        assert!(*self <= snapshot.len(), "offset is out of range");
1460        *self
1461    }
1462}
1463
1464impl ToPoint for usize {
1465    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
1466        snapshot.offset_to_point(*self)
1467    }
1468}
1469
1470impl ToPoint for Point {
1471    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
1472        *self
1473    }
1474}
1475
1476#[cfg(test)]
1477mod tests {
1478    use super::*;
1479    use gpui::MutableAppContext;
1480    use language::Buffer;
1481    use rand::prelude::*;
1482    use std::env;
1483    use text::{Point, RandomCharIter};
1484    use util::test::sample_text;
1485
1486    #[gpui::test]
1487    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
1488        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
1489        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
1490        assert_eq!(
1491            multibuffer.read(cx).snapshot(cx).text(),
1492            buffer.read(cx).text()
1493        );
1494
1495        buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX", cx));
1496        assert_eq!(
1497            multibuffer.read(cx).snapshot(cx).text(),
1498            buffer.read(cx).text()
1499        );
1500    }
1501
1502    #[gpui::test]
1503    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
1504        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
1505        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
1506
1507        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
1508
1509        let subscription = multibuffer.update(cx, |multibuffer, cx| {
1510            let subscription = multibuffer.subscribe();
1511            multibuffer.push_excerpt(
1512                ExcerptProperties {
1513                    buffer: &buffer_1,
1514                    range: Point::new(1, 2)..Point::new(2, 5),
1515                    header_height: 2,
1516                },
1517                cx,
1518            );
1519            assert_eq!(
1520                subscription.consume().into_inner(),
1521                [Edit {
1522                    old: 0..0,
1523                    new: 0..13
1524                }]
1525            );
1526
1527            multibuffer.push_excerpt(
1528                ExcerptProperties {
1529                    buffer: &buffer_1,
1530                    range: Point::new(3, 3)..Point::new(4, 4),
1531                    header_height: 1,
1532                },
1533                cx,
1534            );
1535            multibuffer.push_excerpt(
1536                ExcerptProperties {
1537                    buffer: &buffer_2,
1538                    range: Point::new(3, 1)..Point::new(3, 3),
1539                    header_height: 3,
1540                },
1541                cx,
1542            );
1543            assert_eq!(
1544                subscription.consume().into_inner(),
1545                [Edit {
1546                    old: 13..13,
1547                    new: 13..29
1548                }]
1549            );
1550
1551            subscription
1552        });
1553
1554        assert_eq!(
1555            multibuffer.read(cx).snapshot(cx).text(),
1556            concat!(
1557                "\n",      // Preserve newlines
1558                "\n",      //
1559                "bbbb\n",  //
1560                "ccccc\n", //
1561                "\n",      //
1562                "ddd\n",   //
1563                "eeee\n",  //
1564                "\n",      //
1565                "\n",      //
1566                "\n",      //
1567                "jj\n"     //
1568            )
1569        );
1570
1571        buffer_1.update(cx, |buffer, cx| {
1572            buffer.edit(
1573                [
1574                    Point::new(0, 0)..Point::new(0, 0),
1575                    Point::new(2, 1)..Point::new(2, 3),
1576                ],
1577                "\n",
1578                cx,
1579            );
1580        });
1581
1582        assert_eq!(
1583            multibuffer.read(cx).snapshot(cx).text(),
1584            concat!(
1585                "\n",     // Preserve newlines
1586                "\n",     //
1587                "bbbb\n", //
1588                "c\n",    //
1589                "cc\n",   //
1590                "\n",     //
1591                "ddd\n",  //
1592                "eeee\n", //
1593                "\n",     //
1594                "\n",     //
1595                "\n",     //
1596                "jj\n"    //
1597            )
1598        );
1599
1600        assert_eq!(
1601            subscription.consume().into_inner(),
1602            [Edit {
1603                old: 8..10,
1604                new: 8..9
1605            }]
1606        );
1607    }
1608
1609    #[gpui::test(iterations = 100)]
1610    fn test_random_excerpts(cx: &mut MutableAppContext, mut rng: StdRng) {
1611        let operations = env::var("OPERATIONS")
1612            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1613            .unwrap_or(10);
1614
1615        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
1616        let list = cx.add_model(|_| MultiBuffer::new(0));
1617        let mut excerpt_ids = Vec::new();
1618        let mut expected_excerpts = Vec::new();
1619        let mut old_versions = Vec::new();
1620
1621        for _ in 0..operations {
1622            match rng.gen_range(0..100) {
1623                0..=19 if !buffers.is_empty() => {
1624                    let buffer = buffers.choose(&mut rng).unwrap();
1625                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 1, cx));
1626                }
1627                _ => {
1628                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
1629                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
1630                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
1631                        buffers.last().unwrap()
1632                    } else {
1633                        buffers.choose(&mut rng).unwrap()
1634                    };
1635
1636                    let buffer = buffer_handle.read(cx);
1637                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1638                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1639                    let header_height = rng.gen_range(0..=5);
1640                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
1641                    log::info!(
1642                        "Pushing excerpt wih header {}, buffer {}: {:?}[{:?}] = {:?}",
1643                        header_height,
1644                        buffer_handle.id(),
1645                        buffer.text(),
1646                        start_ix..end_ix,
1647                        &buffer.text()[start_ix..end_ix]
1648                    );
1649
1650                    let excerpt_id = list.update(cx, |list, cx| {
1651                        list.push_excerpt(
1652                            ExcerptProperties {
1653                                buffer: &buffer_handle,
1654                                range: start_ix..end_ix,
1655                                header_height,
1656                            },
1657                            cx,
1658                        )
1659                    });
1660                    excerpt_ids.push(excerpt_id);
1661                    expected_excerpts.push((buffer_handle.clone(), anchor_range, header_height));
1662                }
1663            }
1664
1665            if rng.gen_bool(0.3) {
1666                list.update(cx, |list, cx| {
1667                    old_versions.push((list.snapshot(cx), list.subscribe()));
1668                })
1669            }
1670
1671            let snapshot = list.read(cx).snapshot(cx);
1672
1673            let mut excerpt_starts = Vec::new();
1674            let mut expected_text = String::new();
1675            for (buffer, range, header_height) in &expected_excerpts {
1676                let buffer = buffer.read(cx);
1677                let buffer_range = range.to_offset(buffer);
1678
1679                for _ in 0..*header_height {
1680                    expected_text.push('\n');
1681                }
1682
1683                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
1684                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
1685                expected_text.push('\n');
1686            }
1687
1688            assert_eq!(snapshot.text(), expected_text);
1689
1690            let mut excerpt_starts = excerpt_starts.into_iter();
1691            for (buffer, range, _) in &expected_excerpts {
1692                let buffer_id = buffer.id();
1693                let buffer = buffer.read(cx);
1694                let buffer_range = range.to_offset(buffer);
1695                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
1696                let buffer_start_point_utf16 =
1697                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
1698
1699                let excerpt_start = excerpt_starts.next().unwrap();
1700                let mut offset = excerpt_start.bytes;
1701                let mut buffer_offset = buffer_range.start;
1702                let mut point = excerpt_start.lines;
1703                let mut buffer_point = buffer_start_point;
1704                let mut point_utf16 = excerpt_start.lines_utf16;
1705                let mut buffer_point_utf16 = buffer_start_point_utf16;
1706                for byte in buffer.bytes_in_range(buffer_range.clone()).flatten() {
1707                    let left_offset = snapshot.clip_offset(offset, Bias::Left);
1708                    let right_offset = snapshot.clip_offset(offset, Bias::Right);
1709                    let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
1710                    let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
1711                    assert_eq!(
1712                        left_offset,
1713                        excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
1714                        "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
1715                        offset,
1716                        buffer_id,
1717                        buffer_offset,
1718                    );
1719                    assert_eq!(
1720                        right_offset,
1721                        excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
1722                        "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
1723                        offset,
1724                        buffer_id,
1725                        buffer_offset,
1726                    );
1727
1728                    let left_point = snapshot.clip_point(point, Bias::Left);
1729                    let right_point = snapshot.clip_point(point, Bias::Right);
1730                    let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
1731                    let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
1732                    assert_eq!(
1733                        left_point,
1734                        excerpt_start.lines + (buffer_left_point - buffer_start_point),
1735                        "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
1736                        point,
1737                        buffer_id,
1738                        buffer_point,
1739                    );
1740                    assert_eq!(
1741                        right_point,
1742                        excerpt_start.lines + (buffer_right_point - buffer_start_point),
1743                        "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
1744                        point,
1745                        buffer_id,
1746                        buffer_point,
1747                    );
1748
1749                    let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
1750                    let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
1751                    let buffer_left_point_utf16 =
1752                        buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
1753                    let buffer_right_point_utf16 =
1754                        buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
1755                    assert_eq!(
1756                        left_point_utf16,
1757                        excerpt_start.lines_utf16
1758                            + (buffer_left_point_utf16 - buffer_start_point_utf16),
1759                        "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
1760                        point_utf16,
1761                        buffer_id,
1762                        buffer_point_utf16,
1763                    );
1764                    assert_eq!(
1765                        right_point_utf16,
1766                        excerpt_start.lines_utf16
1767                            + (buffer_right_point_utf16 - buffer_start_point_utf16),
1768                        "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
1769                        point_utf16,
1770                        buffer_id,
1771                        buffer_point_utf16,
1772                    );
1773
1774                    assert_eq!(
1775                        snapshot.point_to_offset(left_point),
1776                        left_offset,
1777                        "point_to_offset({:?})",
1778                        left_point,
1779                    );
1780                    assert_eq!(
1781                        snapshot.offset_to_point(left_offset),
1782                        left_point,
1783                        "offset_to_point({:?})",
1784                        left_offset,
1785                    );
1786
1787                    offset += 1;
1788                    buffer_offset += 1;
1789                    if *byte == b'\n' {
1790                        point += Point::new(1, 0);
1791                        point_utf16 += PointUtf16::new(1, 0);
1792                        buffer_point += Point::new(1, 0);
1793                        buffer_point_utf16 += PointUtf16::new(1, 0);
1794                    } else {
1795                        point += Point::new(0, 1);
1796                        point_utf16 += PointUtf16::new(0, 1);
1797                        buffer_point += Point::new(0, 1);
1798                        buffer_point_utf16 += PointUtf16::new(0, 1);
1799                    }
1800                }
1801            }
1802
1803            for (row, line) in expected_text.split('\n').enumerate() {
1804                assert_eq!(
1805                    snapshot.line_len(row as u32),
1806                    line.len() as u32,
1807                    "line_len({}).",
1808                    row
1809                );
1810            }
1811
1812            for _ in 0..10 {
1813                let end_ix = snapshot.clip_offset(rng.gen_range(0..=snapshot.len()), Bias::Right);
1814                let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1815
1816                assert_eq!(
1817                    snapshot
1818                        .text_for_range(start_ix..end_ix)
1819                        .collect::<String>(),
1820                    &expected_text[start_ix..end_ix],
1821                    "incorrect text for range {:?}",
1822                    start_ix..end_ix
1823                );
1824
1825                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
1826                assert_eq!(
1827                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
1828                    expected_summary,
1829                    "incorrect summary for range {:?}",
1830                    start_ix..end_ix
1831                );
1832            }
1833        }
1834
1835        let snapshot = list.read(cx).snapshot(cx);
1836        for (old_snapshot, subscription) in old_versions {
1837            let edits = subscription.consume().into_inner();
1838
1839            log::info!(
1840                "applying edits since old text: {:?}: {:?}",
1841                old_snapshot.text(),
1842                edits,
1843            );
1844
1845            let mut text = old_snapshot.text();
1846            for edit in edits {
1847                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
1848                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
1849            }
1850            assert_eq!(text.to_string(), snapshot.text());
1851        }
1852    }
1853}