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::{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        // TODO
 350        let this = self.read(cx);
 351        self.as_singleton().unwrap().update(cx, |buffer, cx| {
 352            let buffer_snapshot = buffer.snapshot();
 353            let selections = selections.iter().map(|selection| Selection {
 354                id: selection.id,
 355                start: buffer_snapshot.anchor_before(selection.start.to_offset(&this)),
 356                end: buffer_snapshot.anchor_before(selection.end.to_offset(&this)),
 357                reversed: selection.reversed,
 358                goal: selection.goal,
 359            });
 360            buffer.set_active_selections(Arc::from_iter(selections), cx);
 361        });
 362    }
 363
 364    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 365        for buffer in self.buffers.values() {
 366            buffer
 367                .buffer
 368                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 369        }
 370    }
 371
 372    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 373        // TODO
 374        self.as_singleton()
 375            .unwrap()
 376            .update(cx, |buffer, cx| buffer.undo(cx))
 377    }
 378
 379    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 380        // TODO
 381        self.as_singleton()
 382            .unwrap()
 383            .update(cx, |buffer, cx| buffer.redo(cx))
 384    }
 385
 386    pub fn push_excerpt<O>(
 387        &mut self,
 388        props: ExcerptProperties<O>,
 389        cx: &mut ModelContext<Self>,
 390    ) -> ExcerptId
 391    where
 392        O: text::ToOffset,
 393    {
 394        self.sync(cx);
 395
 396        let buffer = &props.buffer;
 397        cx.subscribe(buffer, Self::on_buffer_event).detach();
 398
 399        let buffer = props.buffer.read(cx);
 400        let range = buffer.anchor_before(&props.range.start)..buffer.anchor_after(&props.range.end);
 401        let mut snapshot = self.snapshot.borrow_mut();
 402        let prev_id = snapshot.excerpts.last().map(|e| &e.id);
 403        let id = ExcerptId::between(prev_id.unwrap_or(&ExcerptId::min()), &ExcerptId::max());
 404
 405        let edit_start = snapshot.excerpts.summary().text.bytes;
 406        let excerpt = Excerpt::new(
 407            id.clone(),
 408            props.buffer.id(),
 409            buffer.snapshot(),
 410            range,
 411            props.header_height,
 412            !self.singleton,
 413        );
 414        let edit = Edit {
 415            old: edit_start..edit_start,
 416            new: edit_start..edit_start + excerpt.text_summary.bytes,
 417        };
 418        snapshot.excerpts.push(excerpt, &());
 419        self.buffers
 420            .entry(props.buffer.id())
 421            .or_insert_with(|| BufferState {
 422                buffer: props.buffer.clone(),
 423                last_version: buffer.version(),
 424                last_parse_count: buffer.parse_count(),
 425                last_diagnostics_update_count: buffer.diagnostics_update_count(),
 426                excerpts: Default::default(),
 427            })
 428            .excerpts
 429            .push(id.clone());
 430
 431        self.subscriptions.publish_mut([edit]);
 432
 433        id
 434    }
 435
 436    fn on_buffer_event(
 437        &mut self,
 438        _: ModelHandle<Buffer>,
 439        event: &Event,
 440        cx: &mut ModelContext<Self>,
 441    ) {
 442        cx.emit(event.clone());
 443    }
 444
 445    pub fn save(
 446        &mut self,
 447        cx: &mut ModelContext<Self>,
 448    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 449        self.as_singleton()
 450            .unwrap()
 451            .update(cx, |buffer, cx| buffer.save(cx))
 452    }
 453
 454    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 455        self.buffers
 456            .values()
 457            .next()
 458            .and_then(|state| state.buffer.read(cx).language())
 459    }
 460
 461    pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
 462        self.as_singleton().unwrap().read(cx).file()
 463    }
 464
 465    pub fn is_dirty(&self, cx: &AppContext) -> bool {
 466        self.as_singleton().unwrap().read(cx).is_dirty()
 467    }
 468
 469    pub fn has_conflict(&self, cx: &AppContext) -> bool {
 470        self.as_singleton().unwrap().read(cx).has_conflict()
 471    }
 472
 473    pub fn is_parsing(&self, cx: &AppContext) -> bool {
 474        self.as_singleton().unwrap().read(cx).is_parsing()
 475    }
 476
 477    fn sync(&self, cx: &AppContext) {
 478        let mut snapshot = self.snapshot.borrow_mut();
 479        let mut excerpts_to_edit = Vec::new();
 480        let mut reparsed = false;
 481        let mut diagnostics_updated = false;
 482        for buffer_state in self.buffers.values() {
 483            let buffer = buffer_state.buffer.read(cx);
 484            let buffer_edited = buffer.version().gt(&buffer_state.last_version);
 485            let buffer_reparsed = buffer.parse_count() > buffer_state.last_parse_count;
 486            let buffer_diagnostics_updated =
 487                buffer.diagnostics_update_count() > buffer_state.last_diagnostics_update_count;
 488            if buffer_edited || buffer_reparsed || buffer_diagnostics_updated {
 489                excerpts_to_edit.extend(
 490                    buffer_state
 491                        .excerpts
 492                        .iter()
 493                        .map(|excerpt_id| (excerpt_id, buffer_state, buffer_edited)),
 494                );
 495            }
 496
 497            reparsed |= buffer_reparsed;
 498            diagnostics_updated |= buffer_diagnostics_updated;
 499        }
 500        if reparsed {
 501            snapshot.parse_count += 1;
 502        }
 503        if diagnostics_updated {
 504            snapshot.diagnostics_update_count += 1;
 505        }
 506        excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
 507
 508        let mut edits = Vec::new();
 509        let mut new_excerpts = SumTree::new();
 510        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 511
 512        for (id, buffer_state, buffer_edited) in excerpts_to_edit {
 513            new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
 514            let old_excerpt = cursor.item().unwrap();
 515            let buffer = buffer_state.buffer.read(cx);
 516
 517            let mut new_excerpt;
 518            if buffer_edited {
 519                edits.extend(
 520                    buffer
 521                        .edits_since_in_range::<usize>(
 522                            old_excerpt.buffer.version(),
 523                            old_excerpt.range.clone(),
 524                        )
 525                        .map(|mut edit| {
 526                            let excerpt_old_start =
 527                                cursor.start().1 + old_excerpt.header_height as usize;
 528                            let excerpt_new_start = new_excerpts.summary().text.bytes
 529                                + old_excerpt.header_height as usize;
 530                            edit.old.start += excerpt_old_start;
 531                            edit.old.end += excerpt_old_start;
 532                            edit.new.start += excerpt_new_start;
 533                            edit.new.end += excerpt_new_start;
 534                            edit
 535                        }),
 536                );
 537
 538                new_excerpt = Excerpt::new(
 539                    id.clone(),
 540                    buffer_state.buffer.id(),
 541                    buffer.snapshot(),
 542                    old_excerpt.range.clone(),
 543                    old_excerpt.header_height,
 544                    !self.singleton,
 545                );
 546            } else {
 547                new_excerpt = old_excerpt.clone();
 548                new_excerpt.buffer = buffer.snapshot();
 549            }
 550
 551            new_excerpts.push(new_excerpt, &());
 552            cursor.next(&());
 553        }
 554        new_excerpts.push_tree(cursor.suffix(&()), &());
 555
 556        drop(cursor);
 557        snapshot.excerpts = new_excerpts;
 558
 559        self.subscriptions.publish(edits);
 560    }
 561}
 562
 563#[cfg(any(test, feature = "test-support"))]
 564impl MultiBuffer {
 565    pub fn randomly_edit<R: rand::Rng>(
 566        &mut self,
 567        rng: &mut R,
 568        count: usize,
 569        cx: &mut ModelContext<Self>,
 570    ) {
 571        self.as_singleton()
 572            .unwrap()
 573            .update(cx, |buffer, cx| buffer.randomly_edit(rng, count, cx));
 574        self.sync(cx);
 575    }
 576}
 577
 578impl Entity for MultiBuffer {
 579    type Event = language::Event;
 580}
 581
 582impl MultiBufferSnapshot {
 583    pub fn text(&self) -> String {
 584        self.chunks(0..self.len(), None)
 585            .map(|chunk| chunk.text)
 586            .collect()
 587    }
 588
 589    pub fn reversed_chars_at<'a, T: ToOffset>(
 590        &'a self,
 591        position: T,
 592    ) -> impl Iterator<Item = char> + 'a {
 593        // TODO
 594        let offset = position.to_offset(self);
 595        self.as_singleton().unwrap().reversed_chars_at(offset)
 596    }
 597
 598    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
 599        let offset = position.to_offset(self);
 600        self.text_for_range(offset..self.len())
 601            .flat_map(|chunk| chunk.chars())
 602    }
 603
 604    pub fn text_for_range<'a, T: ToOffset>(
 605        &'a self,
 606        range: Range<T>,
 607    ) -> impl Iterator<Item = &'a str> {
 608        self.chunks(range, None).map(|chunk| chunk.text)
 609    }
 610
 611    pub fn is_line_blank(&self, row: u32) -> bool {
 612        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
 613            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
 614    }
 615
 616    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
 617    where
 618        T: ToOffset,
 619    {
 620        let offset = position.to_offset(self);
 621        self.as_singleton().unwrap().contains_str_at(offset, needle)
 622    }
 623
 624    fn as_singleton(&self) -> Option<&BufferSnapshot> {
 625        let mut excerpts = self.excerpts.iter();
 626        let buffer = excerpts.next().map(|excerpt| &excerpt.buffer);
 627        if excerpts.next().is_none() {
 628            buffer
 629        } else {
 630            None
 631        }
 632    }
 633
 634    pub fn len(&self) -> usize {
 635        self.excerpts.summary().text.bytes
 636    }
 637
 638    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
 639        let mut cursor = self.excerpts.cursor::<usize>();
 640        cursor.seek(&offset, Bias::Right, &());
 641        if let Some(excerpt) = cursor.item() {
 642            let start_after_header = *cursor.start() + excerpt.header_height as usize;
 643            if offset < start_after_header {
 644                *cursor.start()
 645            } else {
 646                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 647                let buffer_offset = excerpt
 648                    .buffer
 649                    .clip_offset(excerpt_start + (offset - start_after_header), bias);
 650                let offset_in_excerpt = if buffer_offset > excerpt_start {
 651                    buffer_offset - excerpt_start
 652                } else {
 653                    0
 654                };
 655                start_after_header + offset_in_excerpt
 656            }
 657        } else {
 658            self.excerpts.summary().text.bytes
 659        }
 660    }
 661
 662    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
 663        let mut cursor = self.excerpts.cursor::<Point>();
 664        cursor.seek(&point, Bias::Right, &());
 665        if let Some(excerpt) = cursor.item() {
 666            let start_after_header = *cursor.start() + Point::new(excerpt.header_height as u32, 0);
 667            if point < start_after_header {
 668                *cursor.start()
 669            } else {
 670                let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
 671                let buffer_point = excerpt
 672                    .buffer
 673                    .clip_point(excerpt_start + (point - start_after_header), bias);
 674                let point_in_excerpt = if buffer_point > excerpt_start {
 675                    buffer_point - excerpt_start
 676                } else {
 677                    Point::zero()
 678                };
 679                start_after_header + point_in_excerpt
 680            }
 681        } else {
 682            self.excerpts.summary().text.lines
 683        }
 684    }
 685
 686    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
 687        let mut cursor = self.excerpts.cursor::<PointUtf16>();
 688        cursor.seek(&point, Bias::Right, &());
 689        if let Some(excerpt) = cursor.item() {
 690            let start_after_header =
 691                *cursor.start() + PointUtf16::new(excerpt.header_height as u32, 0);
 692            if point < start_after_header {
 693                *cursor.start()
 694            } else {
 695                let excerpt_start = excerpt
 696                    .buffer
 697                    .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
 698                let buffer_point = excerpt
 699                    .buffer
 700                    .clip_point_utf16(excerpt_start + (point - start_after_header), bias);
 701                let point_in_excerpt = if buffer_point > excerpt_start {
 702                    buffer_point - excerpt_start
 703                } else {
 704                    PointUtf16::new(0, 0)
 705                };
 706                start_after_header + point_in_excerpt
 707            }
 708        } else {
 709            self.excerpts.summary().text.lines_utf16
 710        }
 711    }
 712
 713    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
 714        MultiBufferBytes {
 715            chunks: self.chunks(range, None).peekable(),
 716        }
 717    }
 718
 719    pub fn chunks<'a, T: ToOffset>(
 720        &'a self,
 721        range: Range<T>,
 722        theme: Option<&'a SyntaxTheme>,
 723    ) -> MultiBufferChunks<'a> {
 724        let mut result = MultiBufferChunks {
 725            range: 0..range.end.to_offset(self),
 726            cursor: self.excerpts.cursor::<usize>(),
 727            header_height: 0,
 728            excerpt_chunks: None,
 729            has_trailing_newline: false,
 730            theme,
 731        };
 732        result.seek(range.start.to_offset(self));
 733        result
 734    }
 735
 736    pub fn offset_to_point(&self, offset: usize) -> Point {
 737        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
 738        cursor.seek(&offset, Bias::Right, &());
 739        if let Some(excerpt) = cursor.item() {
 740            let (start_offset, start_point) = cursor.start();
 741            let overshoot = offset - start_offset;
 742            let header_height = excerpt.header_height as usize;
 743            if overshoot < header_height {
 744                *start_point
 745            } else {
 746                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
 747                let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
 748                let buffer_point = excerpt
 749                    .buffer
 750                    .offset_to_point(excerpt_start_offset + (overshoot - header_height));
 751                *start_point
 752                    + Point::new(header_height as u32, 0)
 753                    + (buffer_point - excerpt_start_point)
 754            }
 755        } else {
 756            self.excerpts.summary().text.lines
 757        }
 758    }
 759
 760    pub fn point_to_offset(&self, point: Point) -> usize {
 761        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
 762        cursor.seek(&point, Bias::Right, &());
 763        if let Some(excerpt) = cursor.item() {
 764            let (start_point, start_offset) = cursor.start();
 765            let overshoot = point - start_point;
 766            let header_height = Point::new(excerpt.header_height as u32, 0);
 767            if overshoot < header_height {
 768                *start_offset
 769            } else {
 770                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
 771                let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
 772                let buffer_offset = excerpt
 773                    .buffer
 774                    .point_to_offset(excerpt_start_point + (overshoot - header_height));
 775                *start_offset + excerpt.header_height as usize + buffer_offset
 776                    - excerpt_start_offset
 777            }
 778        } else {
 779            self.excerpts.summary().text.bytes
 780        }
 781    }
 782
 783    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
 784        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
 785        cursor.seek(&point, Bias::Right, &());
 786        if let Some(excerpt) = cursor.item() {
 787            let (start_point, start_offset) = cursor.start();
 788            let overshoot = point - start_point;
 789            let header_height = PointUtf16::new(excerpt.header_height as u32, 0);
 790            if overshoot < header_height {
 791                *start_offset
 792            } else {
 793                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
 794                let excerpt_start_point = excerpt
 795                    .buffer
 796                    .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
 797                let buffer_offset = excerpt
 798                    .buffer
 799                    .point_utf16_to_offset(excerpt_start_point + (overshoot - header_height));
 800                *start_offset
 801                    + excerpt.header_height as usize
 802                    + (buffer_offset - excerpt_start_offset)
 803            }
 804        } else {
 805            self.excerpts.summary().text.bytes
 806        }
 807    }
 808
 809    pub fn indent_column_for_line(&self, row: u32) -> u32 {
 810        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
 811            buffer
 812                .indent_column_for_line(range.start.row)
 813                .min(range.end.column)
 814                .saturating_sub(range.start.column)
 815        } else {
 816            0
 817        }
 818    }
 819
 820    pub fn line_len(&self, row: u32) -> u32 {
 821        if let Some((_, range)) = self.buffer_line_for_row(row) {
 822            range.end.column - range.start.column
 823        } else {
 824            0
 825        }
 826    }
 827
 828    fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
 829        let mut cursor = self.excerpts.cursor::<Point>();
 830        cursor.seek(&Point::new(row, 0), Bias::Right, &());
 831        if let Some(excerpt) = cursor.item() {
 832            let overshoot = row - cursor.start().row;
 833            let header_height = excerpt.header_height as u32;
 834            if overshoot >= header_height {
 835                let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
 836                let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
 837                let buffer_row = excerpt_start.row + overshoot - header_height;
 838                let line_start = Point::new(buffer_row, 0);
 839                let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
 840                return Some((
 841                    &excerpt.buffer,
 842                    line_start.max(excerpt_start)..line_end.min(excerpt_end),
 843                ));
 844            }
 845        }
 846        None
 847    }
 848
 849    pub fn max_point(&self) -> Point {
 850        self.text_summary().lines
 851    }
 852
 853    pub fn text_summary(&self) -> TextSummary {
 854        self.excerpts.summary().text
 855    }
 856
 857    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
 858    where
 859        D: TextDimension,
 860        O: ToOffset,
 861    {
 862        let mut summary = D::default();
 863        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
 864        let mut cursor = self.excerpts.cursor::<usize>();
 865        cursor.seek(&range.start, Bias::Right, &());
 866        if let Some(excerpt) = cursor.item() {
 867            let start_after_header = cursor.start() + excerpt.header_height as usize;
 868            if range.start < start_after_header {
 869                let header_len = cmp::min(range.end, start_after_header) - range.start;
 870                summary.add_assign(&D::from_text_summary(&TextSummary {
 871                    bytes: header_len,
 872                    lines: Point::new(header_len as u32, 0),
 873                    lines_utf16: PointUtf16::new(header_len as u32, 0),
 874                    first_line_chars: 0,
 875                    last_line_chars: 0,
 876                    longest_row: 0,
 877                    longest_row_chars: 0,
 878                }));
 879                range.start = start_after_header;
 880                range.end = cmp::max(range.start, range.end);
 881            }
 882
 883            let mut end_before_newline = cursor.end(&());
 884            if excerpt.has_trailing_newline {
 885                end_before_newline -= 1;
 886            }
 887
 888            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 889            let start_in_excerpt = excerpt_start + (range.start - start_after_header);
 890            let end_in_excerpt =
 891                excerpt_start + (cmp::min(end_before_newline, range.end) - start_after_header);
 892            summary.add_assign(
 893                &excerpt
 894                    .buffer
 895                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
 896            );
 897
 898            if range.end > end_before_newline {
 899                summary.add_assign(&D::from_text_summary(&TextSummary {
 900                    bytes: 1,
 901                    lines: Point::new(1 as u32, 0),
 902                    lines_utf16: PointUtf16::new(1 as u32, 0),
 903                    first_line_chars: 0,
 904                    last_line_chars: 0,
 905                    longest_row: 0,
 906                    longest_row_chars: 0,
 907                }));
 908            }
 909
 910            cursor.next(&());
 911        }
 912
 913        if range.end > *cursor.start() {
 914            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
 915                &range.end,
 916                Bias::Right,
 917                &(),
 918            )));
 919            if let Some(excerpt) = cursor.item() {
 920                let start_after_header = cursor.start() + excerpt.header_height as usize;
 921                let header_len =
 922                    cmp::min(range.end - cursor.start(), excerpt.header_height as usize);
 923                summary.add_assign(&D::from_text_summary(&TextSummary {
 924                    bytes: header_len,
 925                    lines: Point::new(header_len as u32, 0),
 926                    lines_utf16: PointUtf16::new(header_len as u32, 0),
 927                    first_line_chars: 0,
 928                    last_line_chars: 0,
 929                    longest_row: 0,
 930                    longest_row_chars: 0,
 931                }));
 932                range.end = cmp::max(start_after_header, range.end);
 933
 934                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 935                let end_in_excerpt = excerpt_start + (range.end - start_after_header);
 936                summary.add_assign(
 937                    &excerpt
 938                        .buffer
 939                        .text_summary_for_range(excerpt_start..end_in_excerpt),
 940                );
 941                cursor.next(&());
 942            }
 943        }
 944
 945        summary
 946    }
 947
 948    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
 949    where
 950        D: TextDimension + Ord + Sub<D, Output = D>,
 951    {
 952        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
 953        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
 954        if let Some(excerpt) = cursor.item() {
 955            if excerpt.id == anchor.excerpt_id {
 956                let mut excerpt_start = D::from_text_summary(&cursor.start().text);
 957                excerpt_start.add_summary(&excerpt.header_summary(), &());
 958                let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
 959                let buffer_point = anchor.text_anchor.summary::<D>(&excerpt.buffer);
 960                if buffer_point > excerpt_buffer_start {
 961                    excerpt_start.add_assign(&(buffer_point - excerpt_buffer_start));
 962                }
 963                return excerpt_start;
 964            }
 965        }
 966        D::from_text_summary(&cursor.start().text)
 967    }
 968
 969    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
 970    where
 971        D: TextDimension + Ord + Sub<D, Output = D>,
 972        I: 'a + IntoIterator<Item = &'a Anchor>,
 973    {
 974        let mut anchors = anchors.into_iter().peekable();
 975        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
 976        let mut summaries = Vec::new();
 977        while let Some(anchor) = anchors.peek() {
 978            let excerpt_id = &anchor.excerpt_id;
 979            let excerpt_anchors = std::iter::from_fn(|| {
 980                let anchor = anchors.peek()?;
 981                if anchor.excerpt_id == *excerpt_id {
 982                    Some(&anchors.next().unwrap().text_anchor)
 983                } else {
 984                    None
 985                }
 986            });
 987
 988            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
 989            if let Some(excerpt) = cursor.item() {
 990                if excerpt.id == *excerpt_id {
 991                    let mut excerpt_start = D::from_text_summary(&cursor.start().text);
 992                    excerpt_start.add_summary(&excerpt.header_summary(), &());
 993                    let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
 994                    summaries.extend(
 995                        excerpt
 996                            .buffer
 997                            .summaries_for_anchors::<D, _>(excerpt_anchors)
 998                            .map(move |summary| {
 999                                let mut excerpt_start = excerpt_start.clone();
1000                                let excerpt_buffer_start = excerpt_buffer_start.clone();
1001                                if summary > excerpt_buffer_start {
1002                                    excerpt_start.add_assign(&(summary - excerpt_buffer_start));
1003                                }
1004                                excerpt_start
1005                            }),
1006                    );
1007                    continue;
1008                }
1009            }
1010
1011            let summary = D::from_text_summary(&cursor.start().text);
1012            summaries.extend(excerpt_anchors.map(|_| summary.clone()));
1013        }
1014
1015        summaries
1016    }
1017
1018    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1019        self.anchor_at(position, Bias::Left)
1020    }
1021
1022    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1023        self.anchor_at(position, Bias::Right)
1024    }
1025
1026    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1027        let offset = position.to_offset(self);
1028        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1029        cursor.seek(&offset, bias, &());
1030        if let Some(excerpt) = cursor.item() {
1031            let overshoot =
1032                (offset - cursor.start().0).saturating_sub(excerpt.header_height as usize);
1033            let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1034            Anchor {
1035                excerpt_id: excerpt.id.clone(),
1036                text_anchor: excerpt.buffer.anchor_at(buffer_start + overshoot, bias),
1037            }
1038        } else if offset == 0 && bias == Bias::Left {
1039            Anchor::min()
1040        } else {
1041            Anchor::max()
1042        }
1043    }
1044
1045    pub fn parse_count(&self) -> usize {
1046        self.parse_count
1047    }
1048
1049    pub fn enclosing_bracket_ranges<T: ToOffset>(
1050        &self,
1051        range: Range<T>,
1052    ) -> Option<(Range<usize>, Range<usize>)> {
1053        let range = range.start.to_offset(self)..range.end.to_offset(self);
1054        self.as_singleton().unwrap().enclosing_bracket_ranges(range)
1055    }
1056
1057    pub fn diagnostics_update_count(&self) -> usize {
1058        self.diagnostics_update_count
1059    }
1060
1061    pub fn language(&self) -> Option<&Arc<Language>> {
1062        self.excerpts
1063            .iter()
1064            .next()
1065            .and_then(|excerpt| excerpt.buffer.language())
1066    }
1067
1068    pub fn diagnostic_group<'a, O>(
1069        &'a self,
1070        group_id: usize,
1071    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1072    where
1073        O: text::FromAnchor + 'a,
1074    {
1075        self.as_singleton().unwrap().diagnostic_group(group_id)
1076    }
1077
1078    pub fn diagnostics_in_range<'a, T, O>(
1079        &'a self,
1080        range: Range<T>,
1081    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1082    where
1083        T: 'a + ToOffset,
1084        O: 'a + text::FromAnchor,
1085    {
1086        let range = range.start.to_offset(self)..range.end.to_offset(self);
1087        self.as_singleton().unwrap().diagnostics_in_range(range)
1088    }
1089
1090    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1091        let range = range.start.to_offset(self)..range.end.to_offset(self);
1092        self.as_singleton()
1093            .unwrap()
1094            .range_for_syntax_ancestor(range)
1095    }
1096
1097    fn buffer_snapshot_for_excerpt<'a>(
1098        &'a self,
1099        excerpt_id: &'a ExcerptId,
1100    ) -> Option<&'a BufferSnapshot> {
1101        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1102        cursor.seek(&Some(excerpt_id), Bias::Left, &());
1103        if let Some(excerpt) = cursor.item() {
1104            if excerpt.id == *excerpt_id {
1105                return Some(&excerpt.buffer);
1106            }
1107        }
1108        None
1109    }
1110
1111    pub fn remote_selections_in_range<'a>(
1112        &'a self,
1113        range: Range<Anchor>,
1114    ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = Selection<Anchor>>)> {
1115        // TODO
1116        let excerpt_id = self.excerpts.first().unwrap().id.clone();
1117        self.as_singleton()
1118            .unwrap()
1119            .remote_selections_in_range(range.start.text_anchor..range.end.text_anchor)
1120            .map(move |(replica_id, selections)| {
1121                let excerpt_id = excerpt_id.clone();
1122                (
1123                    replica_id,
1124                    selections.map(move |s| Selection {
1125                        id: s.id,
1126                        start: Anchor {
1127                            excerpt_id: excerpt_id.clone(),
1128                            text_anchor: s.start.clone(),
1129                        },
1130                        end: Anchor {
1131                            excerpt_id: excerpt_id.clone(),
1132                            text_anchor: s.end.clone(),
1133                        },
1134                        reversed: s.reversed,
1135                        goal: s.goal,
1136                    }),
1137                )
1138            })
1139    }
1140}
1141
1142impl Excerpt {
1143    fn new(
1144        id: ExcerptId,
1145        buffer_id: usize,
1146        buffer: BufferSnapshot,
1147        range: Range<text::Anchor>,
1148        header_height: u8,
1149        has_trailing_newline: bool,
1150    ) -> Self {
1151        let mut text_summary =
1152            buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer));
1153        if header_height > 0 {
1154            text_summary.first_line_chars = 0;
1155            text_summary.lines.row += header_height as u32;
1156            text_summary.lines_utf16.row += header_height as u32;
1157            text_summary.bytes += header_height as usize;
1158            text_summary.longest_row += header_height as u32;
1159        }
1160        if has_trailing_newline {
1161            text_summary.last_line_chars = 0;
1162            text_summary.lines.row += 1;
1163            text_summary.lines.column = 0;
1164            text_summary.lines_utf16.row += 1;
1165            text_summary.lines_utf16.column = 0;
1166            text_summary.bytes += 1;
1167        }
1168
1169        Excerpt {
1170            id,
1171            buffer_id,
1172            buffer,
1173            range,
1174            text_summary,
1175            header_height,
1176            has_trailing_newline,
1177        }
1178    }
1179
1180    fn header_summary(&self) -> TextSummary {
1181        TextSummary {
1182            bytes: self.header_height as usize,
1183            lines: Point::new(self.header_height as u32, 0),
1184            lines_utf16: PointUtf16::new(self.header_height as u32, 0),
1185            first_line_chars: 0,
1186            last_line_chars: 0,
1187            longest_row: 0,
1188            longest_row_chars: 0,
1189        }
1190    }
1191}
1192
1193impl sum_tree::Item for Excerpt {
1194    type Summary = ExcerptSummary;
1195
1196    fn summary(&self) -> Self::Summary {
1197        ExcerptSummary {
1198            excerpt_id: self.id.clone(),
1199            text: self.text_summary.clone(),
1200        }
1201    }
1202}
1203
1204impl sum_tree::Summary for ExcerptSummary {
1205    type Context = ();
1206
1207    fn add_summary(&mut self, summary: &Self, _: &()) {
1208        debug_assert!(summary.excerpt_id > self.excerpt_id);
1209        self.excerpt_id = summary.excerpt_id.clone();
1210        self.text.add_summary(&summary.text, &());
1211    }
1212}
1213
1214impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
1215    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1216        *self += &summary.text;
1217    }
1218}
1219
1220impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
1221    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1222        *self += summary.text.bytes;
1223    }
1224}
1225
1226impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
1227    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1228        Ord::cmp(self, &cursor_location.text.bytes)
1229    }
1230}
1231
1232impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
1233    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1234        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
1235    }
1236}
1237
1238impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
1239    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1240        *self += summary.text.lines;
1241    }
1242}
1243
1244impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
1245    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1246        *self += summary.text.lines_utf16
1247    }
1248}
1249
1250impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
1251    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1252        *self = Some(&summary.excerpt_id);
1253    }
1254}
1255
1256impl<'a> MultiBufferChunks<'a> {
1257    pub fn offset(&self) -> usize {
1258        self.range.start
1259    }
1260
1261    pub fn seek(&mut self, offset: usize) {
1262        self.range.start = offset;
1263        self.cursor.seek_forward(&offset, Bias::Right, &());
1264        self.header_height = 0;
1265        self.excerpt_chunks = None;
1266        if let Some(excerpt) = self.cursor.item() {
1267            let buffer_range = excerpt.range.to_offset(&excerpt.buffer);
1268            self.header_height = excerpt.header_height;
1269            self.has_trailing_newline = excerpt.has_trailing_newline;
1270
1271            let buffer_start;
1272            let start_overshoot = self.range.start - self.cursor.start();
1273            if start_overshoot < excerpt.header_height as usize {
1274                self.header_height -= start_overshoot as u8;
1275                buffer_start = buffer_range.start;
1276            } else {
1277                buffer_start =
1278                    buffer_range.start + start_overshoot - excerpt.header_height as usize;
1279                self.header_height = 0;
1280            }
1281
1282            let buffer_end;
1283            let end_overshoot = self.range.end - self.cursor.start();
1284            if end_overshoot < excerpt.header_height as usize {
1285                self.header_height -= excerpt.header_height - end_overshoot as u8;
1286                buffer_end = buffer_start;
1287            } else {
1288                buffer_end = cmp::min(
1289                    buffer_range.end,
1290                    buffer_range.start + end_overshoot - excerpt.header_height as usize,
1291                );
1292            }
1293
1294            self.excerpt_chunks = Some(excerpt.buffer.chunks(buffer_start..buffer_end, self.theme));
1295        }
1296    }
1297}
1298
1299impl<'a> Iterator for MultiBufferChunks<'a> {
1300    type Item = Chunk<'a>;
1301
1302    fn next(&mut self) -> Option<Self::Item> {
1303        loop {
1304            if self.header_height > 0 {
1305                let chunk = Chunk {
1306                    text: unsafe {
1307                        std::str::from_utf8_unchecked(&NEWLINES[..self.header_height as usize])
1308                    },
1309                    ..Default::default()
1310                };
1311                self.range.start += self.header_height as usize;
1312                self.header_height = 0;
1313                return Some(chunk);
1314            }
1315
1316            if let Some(excerpt_chunks) = self.excerpt_chunks.as_mut() {
1317                if let Some(chunk) = excerpt_chunks.next() {
1318                    self.range.start += chunk.text.len();
1319                    return Some(chunk);
1320                }
1321                self.excerpt_chunks.take();
1322                if self.has_trailing_newline && self.cursor.end(&()) <= self.range.end {
1323                    self.range.start += 1;
1324                    return Some(Chunk {
1325                        text: "\n",
1326                        ..Default::default()
1327                    });
1328                }
1329            }
1330
1331            self.cursor.next(&());
1332            if *self.cursor.start() >= self.range.end {
1333                return None;
1334            }
1335
1336            let excerpt = self.cursor.item()?;
1337            let buffer_range = excerpt.range.to_offset(&excerpt.buffer);
1338
1339            let buffer_end = cmp::min(
1340                buffer_range.end,
1341                buffer_range.start + self.range.end
1342                    - excerpt.header_height as usize
1343                    - self.cursor.start(),
1344            );
1345
1346            self.header_height = excerpt.header_height;
1347            self.has_trailing_newline = excerpt.has_trailing_newline;
1348            self.excerpt_chunks = Some(
1349                excerpt
1350                    .buffer
1351                    .chunks(buffer_range.start..buffer_end, self.theme),
1352            );
1353        }
1354    }
1355}
1356
1357impl<'a> Iterator for MultiBufferBytes<'a> {
1358    type Item = &'a [u8];
1359
1360    fn next(&mut self) -> Option<Self::Item> {
1361        self.chunks.next().map(|chunk| chunk.text.as_bytes())
1362    }
1363}
1364
1365impl<'a> io::Read for MultiBufferBytes<'a> {
1366    fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
1367        todo!()
1368    }
1369}
1370
1371impl ToOffset for Point {
1372    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
1373        snapshot.point_to_offset(*self)
1374    }
1375}
1376
1377impl ToOffset for PointUtf16 {
1378    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
1379        snapshot.point_utf16_to_offset(*self)
1380    }
1381}
1382
1383impl ToOffset for usize {
1384    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
1385        assert!(*self <= snapshot.len(), "offset is out of range");
1386        *self
1387    }
1388}
1389
1390impl ToPoint for usize {
1391    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
1392        snapshot.offset_to_point(*self)
1393    }
1394}
1395
1396impl ToPoint for Point {
1397    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
1398        *self
1399    }
1400}
1401
1402#[cfg(test)]
1403mod tests {
1404    use super::*;
1405    use gpui::MutableAppContext;
1406    use language::Buffer;
1407    use rand::prelude::*;
1408    use std::env;
1409    use text::{Point, RandomCharIter};
1410    use util::test::sample_text;
1411
1412    #[gpui::test]
1413    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
1414        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
1415        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
1416        assert_eq!(
1417            multibuffer.read(cx).snapshot(cx).text(),
1418            buffer.read(cx).text()
1419        );
1420
1421        buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX", cx));
1422        assert_eq!(
1423            multibuffer.read(cx).snapshot(cx).text(),
1424            buffer.read(cx).text()
1425        );
1426    }
1427
1428    #[gpui::test]
1429    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
1430        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
1431        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
1432
1433        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
1434
1435        let subscription = multibuffer.update(cx, |multibuffer, cx| {
1436            let subscription = multibuffer.subscribe();
1437            multibuffer.push_excerpt(
1438                ExcerptProperties {
1439                    buffer: &buffer_1,
1440                    range: Point::new(1, 2)..Point::new(2, 5),
1441                    header_height: 2,
1442                },
1443                cx,
1444            );
1445            assert_eq!(
1446                subscription.consume().into_inner(),
1447                [Edit {
1448                    old: 0..0,
1449                    new: 0..13
1450                }]
1451            );
1452
1453            multibuffer.push_excerpt(
1454                ExcerptProperties {
1455                    buffer: &buffer_1,
1456                    range: Point::new(3, 3)..Point::new(4, 4),
1457                    header_height: 1,
1458                },
1459                cx,
1460            );
1461            multibuffer.push_excerpt(
1462                ExcerptProperties {
1463                    buffer: &buffer_2,
1464                    range: Point::new(3, 1)..Point::new(3, 3),
1465                    header_height: 3,
1466                },
1467                cx,
1468            );
1469            assert_eq!(
1470                subscription.consume().into_inner(),
1471                [Edit {
1472                    old: 13..13,
1473                    new: 13..29
1474                }]
1475            );
1476
1477            subscription
1478        });
1479
1480        assert_eq!(
1481            multibuffer.read(cx).snapshot(cx).text(),
1482            concat!(
1483                "\n",      // Preserve newlines
1484                "\n",      //
1485                "bbbb\n",  //
1486                "ccccc\n", //
1487                "\n",      //
1488                "ddd\n",   //
1489                "eeee\n",  //
1490                "\n",      //
1491                "\n",      //
1492                "\n",      //
1493                "jj\n"     //
1494            )
1495        );
1496
1497        buffer_1.update(cx, |buffer, cx| {
1498            buffer.edit(
1499                [
1500                    Point::new(0, 0)..Point::new(0, 0),
1501                    Point::new(2, 1)..Point::new(2, 3),
1502                ],
1503                "\n",
1504                cx,
1505            );
1506        });
1507
1508        assert_eq!(
1509            multibuffer.read(cx).snapshot(cx).text(),
1510            concat!(
1511                "\n",     // Preserve newlines
1512                "\n",     //
1513                "bbbb\n", //
1514                "c\n",    //
1515                "cc\n",   //
1516                "\n",     //
1517                "ddd\n",  //
1518                "eeee\n", //
1519                "\n",     //
1520                "\n",     //
1521                "\n",     //
1522                "jj\n"    //
1523            )
1524        );
1525
1526        assert_eq!(
1527            subscription.consume().into_inner(),
1528            [Edit {
1529                old: 8..10,
1530                new: 8..9
1531            }]
1532        );
1533    }
1534
1535    #[gpui::test(iterations = 100)]
1536    fn test_random_excerpts(cx: &mut MutableAppContext, mut rng: StdRng) {
1537        let operations = env::var("OPERATIONS")
1538            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1539            .unwrap_or(10);
1540
1541        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
1542        let list = cx.add_model(|_| MultiBuffer::new(0));
1543        let mut excerpt_ids = Vec::new();
1544        let mut expected_excerpts = Vec::new();
1545        let mut old_versions = Vec::new();
1546
1547        for _ in 0..operations {
1548            match rng.gen_range(0..100) {
1549                0..=19 if !buffers.is_empty() => {
1550                    let buffer = buffers.choose(&mut rng).unwrap();
1551                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 1, cx));
1552                }
1553                _ => {
1554                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
1555                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
1556                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
1557                        buffers.last().unwrap()
1558                    } else {
1559                        buffers.choose(&mut rng).unwrap()
1560                    };
1561
1562                    let buffer = buffer_handle.read(cx);
1563                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
1564                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1565                    let header_height = rng.gen_range(0..=5);
1566                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
1567                    log::info!(
1568                        "Pushing excerpt wih header {}, buffer {}: {:?}[{:?}] = {:?}",
1569                        header_height,
1570                        buffer_handle.id(),
1571                        buffer.text(),
1572                        start_ix..end_ix,
1573                        &buffer.text()[start_ix..end_ix]
1574                    );
1575
1576                    let excerpt_id = list.update(cx, |list, cx| {
1577                        list.push_excerpt(
1578                            ExcerptProperties {
1579                                buffer: &buffer_handle,
1580                                range: start_ix..end_ix,
1581                                header_height,
1582                            },
1583                            cx,
1584                        )
1585                    });
1586                    excerpt_ids.push(excerpt_id);
1587                    expected_excerpts.push((buffer_handle.clone(), anchor_range, header_height));
1588                }
1589            }
1590
1591            if rng.gen_bool(0.3) {
1592                list.update(cx, |list, cx| {
1593                    old_versions.push((list.snapshot(cx), list.subscribe()));
1594                })
1595            }
1596
1597            let snapshot = list.read(cx).snapshot(cx);
1598
1599            let mut excerpt_starts = Vec::new();
1600            let mut expected_text = String::new();
1601            for (buffer, range, header_height) in &expected_excerpts {
1602                let buffer = buffer.read(cx);
1603                let buffer_range = range.to_offset(buffer);
1604
1605                for _ in 0..*header_height {
1606                    expected_text.push('\n');
1607                }
1608
1609                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
1610                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
1611                expected_text.push('\n');
1612            }
1613
1614            assert_eq!(snapshot.text(), expected_text);
1615
1616            let mut excerpt_starts = excerpt_starts.into_iter();
1617            for (buffer, range, _) in &expected_excerpts {
1618                let buffer_id = buffer.id();
1619                let buffer = buffer.read(cx);
1620                let buffer_range = range.to_offset(buffer);
1621                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
1622                let buffer_start_point_utf16 =
1623                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
1624
1625                let excerpt_start = excerpt_starts.next().unwrap();
1626                let mut offset = excerpt_start.bytes;
1627                let mut buffer_offset = buffer_range.start;
1628                let mut point = excerpt_start.lines;
1629                let mut buffer_point = buffer_start_point;
1630                let mut point_utf16 = excerpt_start.lines_utf16;
1631                let mut buffer_point_utf16 = buffer_start_point_utf16;
1632                for byte in buffer.bytes_in_range(buffer_range.clone()).flatten() {
1633                    let left_offset = snapshot.clip_offset(offset, Bias::Left);
1634                    let right_offset = snapshot.clip_offset(offset, Bias::Right);
1635                    let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
1636                    let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
1637                    assert_eq!(
1638                        left_offset,
1639                        excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
1640                        "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
1641                        offset,
1642                        buffer_id,
1643                        buffer_offset,
1644                    );
1645                    assert_eq!(
1646                        right_offset,
1647                        excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
1648                        "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
1649                        offset,
1650                        buffer_id,
1651                        buffer_offset,
1652                    );
1653
1654                    let left_point = snapshot.clip_point(point, Bias::Left);
1655                    let right_point = snapshot.clip_point(point, Bias::Right);
1656                    let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
1657                    let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
1658                    assert_eq!(
1659                        left_point,
1660                        excerpt_start.lines + (buffer_left_point - buffer_start_point),
1661                        "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
1662                        point,
1663                        buffer_id,
1664                        buffer_point,
1665                    );
1666                    assert_eq!(
1667                        right_point,
1668                        excerpt_start.lines + (buffer_right_point - buffer_start_point),
1669                        "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
1670                        point,
1671                        buffer_id,
1672                        buffer_point,
1673                    );
1674
1675                    let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
1676                    let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
1677                    let buffer_left_point_utf16 =
1678                        buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
1679                    let buffer_right_point_utf16 =
1680                        buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
1681                    assert_eq!(
1682                        left_point_utf16,
1683                        excerpt_start.lines_utf16
1684                            + (buffer_left_point_utf16 - buffer_start_point_utf16),
1685                        "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
1686                        point_utf16,
1687                        buffer_id,
1688                        buffer_point_utf16,
1689                    );
1690                    assert_eq!(
1691                        right_point_utf16,
1692                        excerpt_start.lines_utf16
1693                            + (buffer_right_point_utf16 - buffer_start_point_utf16),
1694                        "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
1695                        point_utf16,
1696                        buffer_id,
1697                        buffer_point_utf16,
1698                    );
1699
1700                    assert_eq!(
1701                        snapshot.point_to_offset(left_point),
1702                        left_offset,
1703                        "point_to_offset({:?})",
1704                        left_point,
1705                    );
1706                    assert_eq!(
1707                        snapshot.offset_to_point(left_offset),
1708                        left_point,
1709                        "offset_to_point({:?})",
1710                        left_offset,
1711                    );
1712
1713                    offset += 1;
1714                    buffer_offset += 1;
1715                    if *byte == b'\n' {
1716                        point += Point::new(1, 0);
1717                        point_utf16 += PointUtf16::new(1, 0);
1718                        buffer_point += Point::new(1, 0);
1719                        buffer_point_utf16 += PointUtf16::new(1, 0);
1720                    } else {
1721                        point += Point::new(0, 1);
1722                        point_utf16 += PointUtf16::new(0, 1);
1723                        buffer_point += Point::new(0, 1);
1724                        buffer_point_utf16 += PointUtf16::new(0, 1);
1725                    }
1726                }
1727            }
1728
1729            for (row, line) in expected_text.split('\n').enumerate() {
1730                assert_eq!(
1731                    snapshot.line_len(row as u32),
1732                    line.len() as u32,
1733                    "line_len({}).",
1734                    row
1735                );
1736            }
1737
1738            for _ in 0..10 {
1739                let end_ix = snapshot.clip_offset(rng.gen_range(0..=snapshot.len()), Bias::Right);
1740                let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
1741
1742                assert_eq!(
1743                    snapshot
1744                        .text_for_range(start_ix..end_ix)
1745                        .collect::<String>(),
1746                    &expected_text[start_ix..end_ix],
1747                    "incorrect text for range {:?}",
1748                    start_ix..end_ix
1749                );
1750
1751                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
1752                assert_eq!(
1753                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
1754                    expected_summary,
1755                    "incorrect summary for range {:?}",
1756                    start_ix..end_ix
1757                );
1758            }
1759        }
1760
1761        let snapshot = list.read(cx).snapshot(cx);
1762        for (old_snapshot, subscription) in old_versions {
1763            let edits = subscription.consume().into_inner();
1764
1765            log::info!(
1766                "applying edits since old text: {:?}: {:?}",
1767                old_snapshot.text(),
1768                edits,
1769            );
1770
1771            let mut text = old_snapshot.text();
1772            for edit in edits {
1773                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
1774                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
1775            }
1776            assert_eq!(text.to_string(), snapshot.text());
1777        }
1778    }
1779}