multi_buffer.rs

   1mod anchor;
   2
   3pub use anchor::{Anchor, AnchorRangeExt};
   4use anyhow::Result;
   5use clock::ReplicaId;
   6use collections::{HashMap, HashSet};
   7use gpui::{AppContext, ElementBox, Entity, ModelContext, ModelHandle, 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, fmt, io,
  15    iter::{self, FromIterator},
  16    ops::{Range, Sub},
  17    str,
  18    sync::Arc,
  19    time::{Duration, Instant, SystemTime},
  20};
  21use sum_tree::{Bias, Cursor, SumTree};
  22use text::{
  23    locator::Locator,
  24    rope::TextDimension,
  25    subscription::{Subscription, Topic},
  26    AnchorRangeExt as _, Edit, Point, PointUtf16, TextSummary,
  27};
  28use theme::SyntaxTheme;
  29use util::post_inc;
  30
  31const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
  32
  33pub type ExcerptId = Locator;
  34
  35pub struct MultiBuffer {
  36    snapshot: RefCell<MultiBufferSnapshot>,
  37    buffers: HashMap<usize, BufferState>,
  38    subscriptions: Topic,
  39    singleton: bool,
  40    replica_id: ReplicaId,
  41    history: History,
  42}
  43
  44struct History {
  45    next_transaction_id: usize,
  46    undo_stack: Vec<Transaction>,
  47    redo_stack: Vec<Transaction>,
  48    transaction_depth: usize,
  49    group_interval: Duration,
  50}
  51
  52struct Transaction {
  53    id: usize,
  54    buffer_transactions: HashSet<(usize, text::TransactionId)>,
  55    first_edit_at: Instant,
  56    last_edit_at: Instant,
  57}
  58
  59pub trait ToOffset: 'static + fmt::Debug {
  60    fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize;
  61}
  62
  63pub trait ToPoint: 'static + fmt::Debug {
  64    fn to_point(&self, snapshot: &MultiBufferSnapshot) -> Point;
  65}
  66
  67pub trait FromAnchor: 'static {
  68    fn from_anchor(anchor: &Anchor, snapshot: &MultiBufferSnapshot) -> Self;
  69}
  70
  71#[derive(Debug)]
  72struct BufferState {
  73    buffer: ModelHandle<Buffer>,
  74    last_version: clock::Global,
  75    last_parse_count: usize,
  76    last_diagnostics_update_count: usize,
  77    excerpts: Vec<ExcerptId>,
  78}
  79
  80#[derive(Clone, Default)]
  81pub struct MultiBufferSnapshot {
  82    excerpts: SumTree<Excerpt>,
  83    parse_count: usize,
  84    diagnostics_update_count: usize,
  85    is_dirty: bool,
  86    has_conflict: bool,
  87}
  88
  89pub type RenderHeaderFn = Arc<dyn 'static + Send + Sync + Fn(&AppContext) -> ElementBox>;
  90
  91pub struct ExcerptProperties<'a, T> {
  92    pub buffer: &'a ModelHandle<Buffer>,
  93    pub range: Range<T>,
  94    pub header_height: u8,
  95    pub render_header: Option<RenderHeaderFn>,
  96}
  97
  98#[derive(Clone)]
  99struct Excerpt {
 100    id: ExcerptId,
 101    buffer_id: usize,
 102    buffer: BufferSnapshot,
 103    range: Range<text::Anchor>,
 104    render_header: Option<RenderHeaderFn>,
 105    text_summary: TextSummary,
 106    header_height: u8,
 107    has_trailing_newline: bool,
 108}
 109
 110#[derive(Clone, Debug, Default)]
 111struct ExcerptSummary {
 112    excerpt_id: ExcerptId,
 113    text: TextSummary,
 114}
 115
 116pub struct MultiBufferRows<'a> {
 117    header_height: u32,
 118    buffer_row_range: Range<u32>,
 119    excerpts: Cursor<'a, Excerpt, Point>,
 120}
 121
 122pub struct MultiBufferChunks<'a> {
 123    range: Range<usize>,
 124    excerpts: Cursor<'a, Excerpt, usize>,
 125    excerpt_chunks: Option<ExcerptChunks<'a>>,
 126    theme: Option<&'a SyntaxTheme>,
 127}
 128
 129pub struct MultiBufferBytes<'a> {
 130    range: Range<usize>,
 131    excerpts: Cursor<'a, Excerpt, usize>,
 132    excerpt_bytes: Option<ExcerptBytes<'a>>,
 133    chunk: &'a [u8],
 134}
 135
 136struct ExcerptChunks<'a> {
 137    header_height: usize,
 138    content_chunks: BufferChunks<'a>,
 139    footer_height: usize,
 140}
 141
 142struct ExcerptBytes<'a> {
 143    header_height: usize,
 144    content_bytes: language::rope::Bytes<'a>,
 145    footer_height: usize,
 146}
 147
 148impl MultiBuffer {
 149    pub fn new(replica_id: ReplicaId) -> Self {
 150        Self {
 151            snapshot: Default::default(),
 152            buffers: Default::default(),
 153            subscriptions: Default::default(),
 154            singleton: false,
 155            replica_id,
 156            history: History {
 157                next_transaction_id: Default::default(),
 158                undo_stack: Default::default(),
 159                redo_stack: Default::default(),
 160                transaction_depth: 0,
 161                group_interval: Duration::from_millis(300),
 162            },
 163        }
 164    }
 165
 166    pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
 167        let mut this = Self::new(buffer.read(cx).replica_id());
 168        this.singleton = true;
 169        this.push_excerpt(
 170            ExcerptProperties {
 171                buffer: &buffer,
 172                range: text::Anchor::min()..text::Anchor::max(),
 173                header_height: 0,
 174                render_header: None,
 175            },
 176            cx,
 177        );
 178        this
 179    }
 180
 181    #[cfg(any(test, feature = "test-support"))]
 182    pub fn build_simple(text: &str, cx: &mut gpui::MutableAppContext) -> ModelHandle<Self> {
 183        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 184        cx.add_model(|cx| Self::singleton(buffer, cx))
 185    }
 186
 187    #[cfg(any(test, feature = "test-support"))]
 188    pub fn build_random(
 189        mut rng: &mut impl rand::Rng,
 190        cx: &mut gpui::MutableAppContext,
 191    ) -> ModelHandle<Self> {
 192        use rand::prelude::*;
 193        use std::env;
 194        use text::RandomCharIter;
 195
 196        let max_excerpts = env::var("MAX_EXCERPTS")
 197            .map(|i| i.parse().expect("invalid `MAX_EXCERPTS` variable"))
 198            .unwrap_or(5);
 199        let excerpts = rng.gen_range(1..=max_excerpts);
 200
 201        cx.add_model(|cx| {
 202            let mut multibuffer = MultiBuffer::new(0);
 203            let mut buffers = Vec::new();
 204            for _ in 0..excerpts {
 205                let buffer_handle = if rng.gen() || buffers.is_empty() {
 206                    let text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
 207                    buffers.push(cx.add_model(|cx| Buffer::new(0, text, cx)));
 208                    let buffer = buffers.last().unwrap();
 209                    log::info!(
 210                        "Creating new buffer {} with text: {:?}",
 211                        buffer.id(),
 212                        buffer.read(cx).text()
 213                    );
 214                    buffers.last().unwrap()
 215                } else {
 216                    buffers.choose(rng).unwrap()
 217                };
 218
 219                let buffer = buffer_handle.read(cx);
 220                let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
 221                let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
 222                let header_height = rng.gen_range(0..=5);
 223                log::info!(
 224                    "Inserting excerpt from buffer {} with header height {} and range {:?}: {:?}",
 225                    buffer_handle.id(),
 226                    header_height,
 227                    start_ix..end_ix,
 228                    &buffer.text()[start_ix..end_ix]
 229                );
 230
 231                multibuffer.push_excerpt(
 232                    ExcerptProperties {
 233                        buffer: buffer_handle,
 234                        range: start_ix..end_ix,
 235                        header_height,
 236                        render_header: None,
 237                    },
 238                    cx,
 239                );
 240            }
 241            multibuffer
 242        })
 243    }
 244
 245    pub fn replica_id(&self) -> ReplicaId {
 246        self.replica_id
 247    }
 248
 249    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
 250        self.sync(cx);
 251        self.snapshot.borrow().clone()
 252    }
 253
 254    pub fn read(&self, cx: &AppContext) -> Ref<MultiBufferSnapshot> {
 255        self.sync(cx);
 256        self.snapshot.borrow()
 257    }
 258
 259    pub fn as_singleton(&self) -> Option<&ModelHandle<Buffer>> {
 260        if self.singleton {
 261            return Some(&self.buffers.values().next().unwrap().buffer);
 262        } else {
 263            None
 264        }
 265    }
 266
 267    pub fn subscribe(&mut self) -> Subscription {
 268        self.subscriptions.subscribe()
 269    }
 270
 271    pub fn edit<I, S, T>(&mut self, ranges: I, new_text: T, cx: &mut ModelContext<Self>)
 272    where
 273        I: IntoIterator<Item = Range<S>>,
 274        S: ToOffset,
 275        T: Into<String>,
 276    {
 277        self.edit_internal(ranges, new_text, false, cx)
 278    }
 279
 280    pub fn edit_with_autoindent<I, S, T>(
 281        &mut self,
 282        ranges: I,
 283        new_text: T,
 284        cx: &mut ModelContext<Self>,
 285    ) where
 286        I: IntoIterator<Item = Range<S>>,
 287        S: ToOffset,
 288        T: Into<String>,
 289    {
 290        self.edit_internal(ranges, new_text, true, cx)
 291    }
 292
 293    pub fn edit_internal<I, S, T>(
 294        &mut self,
 295        ranges_iter: I,
 296        new_text: T,
 297        autoindent: bool,
 298        cx: &mut ModelContext<Self>,
 299    ) where
 300        I: IntoIterator<Item = Range<S>>,
 301        S: ToOffset,
 302        T: Into<String>,
 303    {
 304        if let Some(buffer) = self.as_singleton() {
 305            let snapshot = self.read(cx);
 306            let ranges = ranges_iter
 307                .into_iter()
 308                .map(|range| range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot));
 309            return buffer.update(cx, |buffer, cx| {
 310                if autoindent {
 311                    buffer.edit_with_autoindent(ranges, new_text, cx)
 312                } else {
 313                    buffer.edit(ranges, new_text, cx)
 314                }
 315            });
 316        }
 317
 318        let snapshot = self.read(cx);
 319        let mut buffer_edits: HashMap<usize, Vec<(Range<usize>, bool)>> = Default::default();
 320        let mut cursor = snapshot.excerpts.cursor::<usize>();
 321        for range in ranges_iter {
 322            let start = range.start.to_offset(&snapshot);
 323            let end = range.end.to_offset(&snapshot);
 324            cursor.seek(&start, Bias::Right, &());
 325            if cursor.item().is_none() && start == *cursor.start() {
 326                cursor.prev(&());
 327            }
 328            let start_excerpt = cursor.item().expect("start offset out of bounds");
 329            let start_overshoot =
 330                (start - cursor.start()).saturating_sub(start_excerpt.header_height as usize);
 331            let buffer_start =
 332                start_excerpt.range.start.to_offset(&start_excerpt.buffer) + start_overshoot;
 333
 334            cursor.seek(&end, Bias::Right, &());
 335            if cursor.item().is_none() && end == *cursor.start() {
 336                cursor.prev(&());
 337            }
 338            let end_excerpt = cursor.item().expect("end offset out of bounds");
 339            let end_overshoot =
 340                (end - cursor.start()).saturating_sub(end_excerpt.header_height as usize);
 341            let buffer_end = end_excerpt.range.start.to_offset(&end_excerpt.buffer) + end_overshoot;
 342
 343            if start_excerpt.id == end_excerpt.id {
 344                buffer_edits
 345                    .entry(start_excerpt.buffer_id)
 346                    .or_insert(Vec::new())
 347                    .push((buffer_start..buffer_end, true));
 348            } else {
 349                let start_excerpt_range =
 350                    buffer_start..start_excerpt.range.end.to_offset(&start_excerpt.buffer);
 351                let end_excerpt_range =
 352                    end_excerpt.range.start.to_offset(&end_excerpt.buffer)..buffer_end;
 353                buffer_edits
 354                    .entry(start_excerpt.buffer_id)
 355                    .or_insert(Vec::new())
 356                    .push((start_excerpt_range, true));
 357                buffer_edits
 358                    .entry(end_excerpt.buffer_id)
 359                    .or_insert(Vec::new())
 360                    .push((end_excerpt_range, false));
 361
 362                cursor.seek(&start, Bias::Right, &());
 363                cursor.next(&());
 364                while let Some(excerpt) = cursor.item() {
 365                    if excerpt.id == end_excerpt.id {
 366                        break;
 367                    }
 368                    buffer_edits
 369                        .entry(excerpt.buffer_id)
 370                        .or_insert(Vec::new())
 371                        .push((excerpt.range.to_offset(&excerpt.buffer), false));
 372                    cursor.next(&());
 373                }
 374            }
 375        }
 376
 377        let new_text = new_text.into();
 378        for (buffer_id, mut edits) in buffer_edits {
 379            edits.sort_unstable_by_key(|(range, _)| range.start);
 380            self.buffers[&buffer_id].buffer.update(cx, |buffer, cx| {
 381                let mut edits = edits.into_iter().peekable();
 382                let mut insertions = Vec::new();
 383                let mut deletions = Vec::new();
 384                while let Some((mut range, mut is_insertion)) = edits.next() {
 385                    while let Some((next_range, next_is_insertion)) = edits.peek() {
 386                        if range.end >= next_range.start {
 387                            range.end = cmp::max(next_range.end, range.end);
 388                            is_insertion |= *next_is_insertion;
 389                            edits.next();
 390                        } else {
 391                            break;
 392                        }
 393                    }
 394
 395                    if is_insertion {
 396                        insertions.push(
 397                            buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 398                        );
 399                    } else if !range.is_empty() {
 400                        deletions.push(
 401                            buffer.anchor_before(range.start)..buffer.anchor_before(range.end),
 402                        );
 403                    }
 404                }
 405
 406                if autoindent {
 407                    buffer.edit_with_autoindent(deletions, "", cx);
 408                    buffer.edit_with_autoindent(insertions, new_text.clone(), cx);
 409                } else {
 410                    buffer.edit(deletions, "", cx);
 411                    buffer.edit(insertions, new_text.clone(), cx);
 412                }
 413            })
 414        }
 415    }
 416
 417    pub fn start_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 418        self.start_transaction_at(Instant::now(), cx)
 419    }
 420
 421    pub(crate) fn start_transaction_at(
 422        &mut self,
 423        now: Instant,
 424        cx: &mut ModelContext<Self>,
 425    ) -> Option<TransactionId> {
 426        if let Some(buffer) = self.as_singleton() {
 427            return buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 428        }
 429
 430        for BufferState { buffer, .. } in self.buffers.values() {
 431            buffer.update(cx, |buffer, _| buffer.start_transaction_at(now));
 432        }
 433        self.history.start_transaction(now)
 434    }
 435
 436    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 437        self.end_transaction_at(Instant::now(), cx)
 438    }
 439
 440    pub(crate) fn end_transaction_at(
 441        &mut self,
 442        now: Instant,
 443        cx: &mut ModelContext<Self>,
 444    ) -> Option<TransactionId> {
 445        if let Some(buffer) = self.as_singleton() {
 446            return buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx));
 447        }
 448
 449        let mut buffer_transactions = HashSet::default();
 450        for BufferState { buffer, .. } in self.buffers.values() {
 451            if let Some(transaction_id) =
 452                buffer.update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 453            {
 454                buffer_transactions.insert((buffer.id(), transaction_id));
 455            }
 456        }
 457
 458        if self.history.end_transaction(now, buffer_transactions) {
 459            let transaction_id = self.history.group().unwrap();
 460            Some(transaction_id)
 461        } else {
 462            None
 463        }
 464    }
 465
 466    pub fn set_active_selections(
 467        &mut self,
 468        selections: &[Selection<Anchor>],
 469        cx: &mut ModelContext<Self>,
 470    ) {
 471        let mut selections_by_buffer: HashMap<usize, Vec<Selection<text::Anchor>>> =
 472            Default::default();
 473        let snapshot = self.read(cx);
 474        let mut cursor = snapshot.excerpts.cursor::<Option<&ExcerptId>>();
 475        for selection in selections {
 476            cursor.seek(&Some(&selection.start.excerpt_id), Bias::Left, &());
 477            while let Some(excerpt) = cursor.item() {
 478                if excerpt.id > selection.end.excerpt_id {
 479                    break;
 480                }
 481
 482                let mut start = excerpt.range.start.clone();
 483                let mut end = excerpt.range.end.clone();
 484                if excerpt.id == selection.start.excerpt_id {
 485                    start = selection.start.text_anchor.clone();
 486                }
 487                if excerpt.id == selection.end.excerpt_id {
 488                    end = selection.end.text_anchor.clone();
 489                }
 490                selections_by_buffer
 491                    .entry(excerpt.buffer_id)
 492                    .or_default()
 493                    .push(Selection {
 494                        id: selection.id,
 495                        start,
 496                        end,
 497                        reversed: selection.reversed,
 498                        goal: selection.goal,
 499                    });
 500
 501                cursor.next(&());
 502            }
 503        }
 504
 505        for (buffer_id, mut selections) in selections_by_buffer {
 506            self.buffers[&buffer_id].buffer.update(cx, |buffer, cx| {
 507                selections.sort_unstable_by(|a, b| a.start.cmp(&b.start, buffer).unwrap());
 508                let mut selections = selections.into_iter().peekable();
 509                let merged_selections = Arc::from_iter(iter::from_fn(|| {
 510                    let mut selection = selections.next()?;
 511                    while let Some(next_selection) = selections.peek() {
 512                        if selection
 513                            .end
 514                            .cmp(&next_selection.start, buffer)
 515                            .unwrap()
 516                            .is_ge()
 517                        {
 518                            let next_selection = selections.next().unwrap();
 519                            if next_selection
 520                                .end
 521                                .cmp(&selection.end, buffer)
 522                                .unwrap()
 523                                .is_ge()
 524                            {
 525                                selection.end = next_selection.end;
 526                            }
 527                        } else {
 528                            break;
 529                        }
 530                    }
 531                    Some(selection)
 532                }));
 533                buffer.set_active_selections(merged_selections, cx);
 534            });
 535        }
 536    }
 537
 538    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
 539        for buffer in self.buffers.values() {
 540            buffer
 541                .buffer
 542                .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 543        }
 544    }
 545
 546    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 547        if let Some(buffer) = self.as_singleton() {
 548            return buffer.update(cx, |buffer, cx| buffer.undo(cx));
 549        }
 550
 551        while let Some(transaction) = self.history.pop_undo() {
 552            let mut undone = false;
 553            for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
 554                if let Some(BufferState { buffer, .. }) = self.buffers.get(&buffer_id) {
 555                    undone |= buffer.update(cx, |buf, cx| {
 556                        buf.undo_transaction(*buffer_transaction_id, cx)
 557                    });
 558                }
 559            }
 560
 561            if undone {
 562                return Some(transaction.id);
 563            }
 564        }
 565
 566        None
 567    }
 568
 569    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
 570        if let Some(buffer) = self.as_singleton() {
 571            return buffer.update(cx, |buffer, cx| buffer.redo(cx));
 572        }
 573
 574        while let Some(transaction) = self.history.pop_redo() {
 575            let mut redone = false;
 576            for (buffer_id, buffer_transaction_id) in &transaction.buffer_transactions {
 577                if let Some(BufferState { buffer, .. }) = self.buffers.get(&buffer_id) {
 578                    redone |= buffer.update(cx, |buf, cx| {
 579                        buf.redo_transaction(*buffer_transaction_id, cx)
 580                    });
 581                }
 582            }
 583
 584            if redone {
 585                return Some(transaction.id);
 586            }
 587        }
 588
 589        None
 590    }
 591
 592    pub fn push_excerpt<O>(
 593        &mut self,
 594        props: ExcerptProperties<O>,
 595        cx: &mut ModelContext<Self>,
 596    ) -> ExcerptId
 597    where
 598        O: text::ToOffset,
 599    {
 600        assert_eq!(self.history.transaction_depth, 0);
 601        self.sync(cx);
 602
 603        let buffer = props.buffer.clone();
 604        cx.observe(&buffer, |_, _, cx| cx.notify()).detach();
 605        cx.subscribe(&buffer, Self::on_buffer_event).detach();
 606
 607        let buffer_snapshot = buffer.read(cx).snapshot();
 608        let range = buffer_snapshot.anchor_before(&props.range.start)
 609            ..buffer_snapshot.anchor_after(&props.range.end);
 610        let last_version = buffer_snapshot.version().clone();
 611        let last_parse_count = buffer_snapshot.parse_count();
 612        let last_diagnostics_update_count = buffer_snapshot.diagnostics_update_count();
 613
 614        let mut snapshot = self.snapshot.borrow_mut();
 615        let mut prev_id = None;
 616        let edit_start = snapshot.excerpts.summary().text.bytes;
 617        snapshot.excerpts.update_last(
 618            |excerpt| {
 619                excerpt.has_trailing_newline = true;
 620                prev_id = Some(excerpt.id.clone());
 621            },
 622            &(),
 623        );
 624
 625        let id = ExcerptId::between(&prev_id.unwrap_or(ExcerptId::min()), &ExcerptId::max());
 626        let excerpt = Excerpt::new(
 627            id.clone(),
 628            buffer.id(),
 629            buffer_snapshot,
 630            range,
 631            props.header_height,
 632            props.render_header,
 633            false,
 634        );
 635        snapshot.excerpts.push(excerpt, &());
 636        self.buffers
 637            .entry(props.buffer.id())
 638            .or_insert_with(|| BufferState {
 639                buffer,
 640                last_version,
 641                last_parse_count,
 642                last_diagnostics_update_count,
 643                excerpts: Default::default(),
 644            })
 645            .excerpts
 646            .push(id.clone());
 647        self.subscriptions.publish_mut([Edit {
 648            old: edit_start..edit_start,
 649            new: edit_start..snapshot.excerpts.summary().text.bytes,
 650        }]);
 651
 652        cx.notify();
 653
 654        id
 655    }
 656
 657    fn on_buffer_event(
 658        &mut self,
 659        _: ModelHandle<Buffer>,
 660        event: &Event,
 661        cx: &mut ModelContext<Self>,
 662    ) {
 663        cx.emit(event.clone());
 664    }
 665
 666    pub fn save(
 667        &mut self,
 668        cx: &mut ModelContext<Self>,
 669    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 670        self.as_singleton()
 671            .unwrap()
 672            .update(cx, |buffer, cx| buffer.save(cx))
 673    }
 674
 675    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 676        self.buffers
 677            .values()
 678            .next()
 679            .and_then(|state| state.buffer.read(cx).language())
 680    }
 681
 682    pub fn file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn File> {
 683        self.as_singleton().unwrap().read(cx).file()
 684    }
 685
 686    #[cfg(test)]
 687    pub fn is_parsing(&self, cx: &AppContext) -> bool {
 688        self.as_singleton().unwrap().read(cx).is_parsing()
 689    }
 690
 691    fn sync(&self, cx: &AppContext) {
 692        let mut snapshot = self.snapshot.borrow_mut();
 693        let mut excerpts_to_edit = Vec::new();
 694        let mut reparsed = false;
 695        let mut diagnostics_updated = false;
 696        let mut is_dirty = false;
 697        let mut has_conflict = false;
 698        for buffer_state in self.buffers.values() {
 699            let buffer = buffer_state.buffer.read(cx);
 700            let buffer_edited = buffer.version().gt(&buffer_state.last_version);
 701            let buffer_reparsed = buffer.parse_count() > buffer_state.last_parse_count;
 702            let buffer_diagnostics_updated =
 703                buffer.diagnostics_update_count() > buffer_state.last_diagnostics_update_count;
 704            if buffer_edited || buffer_reparsed || buffer_diagnostics_updated {
 705                excerpts_to_edit.extend(
 706                    buffer_state
 707                        .excerpts
 708                        .iter()
 709                        .map(|excerpt_id| (excerpt_id, buffer_state, buffer_edited)),
 710                );
 711            }
 712
 713            reparsed |= buffer_reparsed;
 714            diagnostics_updated |= buffer_diagnostics_updated;
 715            is_dirty |= buffer.is_dirty();
 716            has_conflict |= buffer.has_conflict();
 717        }
 718        if reparsed {
 719            snapshot.parse_count += 1;
 720        }
 721        if diagnostics_updated {
 722            snapshot.diagnostics_update_count += 1;
 723        }
 724        snapshot.is_dirty = is_dirty;
 725        snapshot.has_conflict = has_conflict;
 726
 727        excerpts_to_edit.sort_unstable_by_key(|(excerpt_id, _, _)| *excerpt_id);
 728
 729        let mut edits = Vec::new();
 730        let mut new_excerpts = SumTree::new();
 731        let mut cursor = snapshot.excerpts.cursor::<(Option<&ExcerptId>, usize)>();
 732
 733        for (id, buffer_state, buffer_edited) in excerpts_to_edit {
 734            new_excerpts.push_tree(cursor.slice(&Some(id), Bias::Left, &()), &());
 735            let old_excerpt = cursor.item().unwrap();
 736            let buffer = buffer_state.buffer.read(cx);
 737
 738            let mut new_excerpt;
 739            if buffer_edited {
 740                edits.extend(
 741                    buffer
 742                        .edits_since_in_range::<usize>(
 743                            old_excerpt.buffer.version(),
 744                            old_excerpt.range.clone(),
 745                        )
 746                        .map(|mut edit| {
 747                            let excerpt_old_start =
 748                                cursor.start().1 + old_excerpt.header_height as usize;
 749                            let excerpt_new_start = new_excerpts.summary().text.bytes
 750                                + old_excerpt.header_height as usize;
 751                            edit.old.start += excerpt_old_start;
 752                            edit.old.end += excerpt_old_start;
 753                            edit.new.start += excerpt_new_start;
 754                            edit.new.end += excerpt_new_start;
 755                            edit
 756                        }),
 757                );
 758
 759                new_excerpt = Excerpt::new(
 760                    id.clone(),
 761                    buffer_state.buffer.id(),
 762                    buffer.snapshot(),
 763                    old_excerpt.range.clone(),
 764                    old_excerpt.header_height,
 765                    old_excerpt.render_header.clone(),
 766                    old_excerpt.has_trailing_newline,
 767                );
 768            } else {
 769                new_excerpt = old_excerpt.clone();
 770                new_excerpt.buffer = buffer.snapshot();
 771            }
 772
 773            new_excerpts.push(new_excerpt, &());
 774            cursor.next(&());
 775        }
 776        new_excerpts.push_tree(cursor.suffix(&()), &());
 777
 778        drop(cursor);
 779        snapshot.excerpts = new_excerpts;
 780
 781        self.subscriptions.publish(edits);
 782    }
 783}
 784
 785#[cfg(any(test, feature = "test-support"))]
 786impl MultiBuffer {
 787    pub fn randomly_edit(
 788        &mut self,
 789        rng: &mut impl rand::Rng,
 790        count: usize,
 791        cx: &mut ModelContext<Self>,
 792    ) {
 793        use text::RandomCharIter;
 794
 795        let snapshot = self.read(cx);
 796        let mut old_ranges: Vec<Range<usize>> = Vec::new();
 797        for _ in 0..count {
 798            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
 799            if last_end > snapshot.len() {
 800                break;
 801            }
 802            let end_ix = snapshot.clip_offset(rng.gen_range(0..=last_end), Bias::Right);
 803            let start_ix = snapshot.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
 804            old_ranges.push(start_ix..end_ix);
 805        }
 806        let new_text_len = rng.gen_range(0..10);
 807        let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
 808        log::info!("mutating multi-buffer at {:?}: {:?}", old_ranges, new_text);
 809        drop(snapshot);
 810
 811        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
 812    }
 813}
 814
 815impl Entity for MultiBuffer {
 816    type Event = language::Event;
 817}
 818
 819impl MultiBufferSnapshot {
 820    pub fn text(&self) -> String {
 821        self.chunks(0..self.len(), None)
 822            .map(|chunk| chunk.text)
 823            .collect()
 824    }
 825
 826    pub fn excerpt_headers_in_range<'a>(
 827        &'a self,
 828        range: Range<u32>,
 829    ) -> impl 'a + Iterator<Item = (Range<u32>, RenderHeaderFn)> {
 830        let mut cursor = self.excerpts.cursor::<Point>();
 831        cursor.seek(&Point::new(range.start, 0), Bias::Right, &());
 832
 833        if let Some(excerpt) = cursor.item() {
 834            if range.start >= cursor.start().row + excerpt.header_height as u32 {
 835                cursor.next(&());
 836            }
 837        }
 838
 839        iter::from_fn(move || {
 840            while let Some(excerpt) = cursor.item() {
 841                if cursor.start().row >= range.end {
 842                    break;
 843                }
 844
 845                if let Some(render) = excerpt.render_header.clone() {
 846                    let start = cursor.start().row;
 847                    let end = start + excerpt.header_height as u32;
 848                    cursor.next(&());
 849                    return Some((start..end, render));
 850                } else {
 851                    cursor.next(&());
 852                }
 853            }
 854            None
 855        })
 856    }
 857
 858    pub fn reversed_chars_at<'a, T: ToOffset>(
 859        &'a self,
 860        position: T,
 861    ) -> impl Iterator<Item = char> + 'a {
 862        let mut offset = position.to_offset(self);
 863        let mut cursor = self.excerpts.cursor::<usize>();
 864        cursor.seek(&offset, Bias::Left, &());
 865        let mut excerpt_chunks = cursor.item().map(|excerpt| {
 866            let start_after_header = cursor.start() + excerpt.header_height as usize;
 867            let end_before_footer = cursor.start() + excerpt.text_summary.bytes;
 868
 869            let start = excerpt.range.start.to_offset(&excerpt.buffer);
 870            let end =
 871                start + (cmp::min(offset, end_before_footer).saturating_sub(start_after_header));
 872            excerpt.buffer.reversed_chunks_in_range(start..end)
 873        });
 874        iter::from_fn(move || {
 875            if offset == *cursor.start() {
 876                cursor.prev(&());
 877                let excerpt = cursor.item()?;
 878                excerpt_chunks = Some(
 879                    excerpt
 880                        .buffer
 881                        .reversed_chunks_in_range(excerpt.range.clone()),
 882                );
 883            }
 884
 885            let excerpt = cursor.item().unwrap();
 886            if offset <= cursor.start() + excerpt.header_height as usize {
 887                let header_height = offset - cursor.start();
 888                offset -= header_height;
 889                Some(unsafe { str::from_utf8_unchecked(&NEWLINES[..header_height]) })
 890            } else if offset == cursor.end(&()) && excerpt.has_trailing_newline {
 891                offset -= 1;
 892                Some("\n")
 893            } else {
 894                let chunk = excerpt_chunks.as_mut().unwrap().next().unwrap();
 895                offset -= chunk.len();
 896                Some(chunk)
 897            }
 898        })
 899        .flat_map(|c| c.chars().rev())
 900    }
 901
 902    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
 903        let offset = position.to_offset(self);
 904        self.text_for_range(offset..self.len())
 905            .flat_map(|chunk| chunk.chars())
 906    }
 907
 908    pub fn text_for_range<'a, T: ToOffset>(
 909        &'a self,
 910        range: Range<T>,
 911    ) -> impl Iterator<Item = &'a str> {
 912        self.chunks(range, None).map(|chunk| chunk.text)
 913    }
 914
 915    pub fn is_line_blank(&self, row: u32) -> bool {
 916        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
 917            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
 918    }
 919
 920    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
 921    where
 922        T: ToOffset,
 923    {
 924        let position = position.to_offset(self);
 925        position == self.clip_offset(position, Bias::Left)
 926            && self
 927                .bytes_in_range(position..self.len())
 928                .flatten()
 929                .copied()
 930                .take(needle.len())
 931                .eq(needle.bytes())
 932    }
 933
 934    fn as_singleton(&self) -> Option<&BufferSnapshot> {
 935        let mut excerpts = self.excerpts.iter();
 936        let buffer = excerpts.next().map(|excerpt| &excerpt.buffer);
 937        if excerpts.next().is_none() {
 938            buffer
 939        } else {
 940            None
 941        }
 942    }
 943
 944    pub fn len(&self) -> usize {
 945        self.excerpts.summary().text.bytes
 946    }
 947
 948    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
 949        let mut cursor = self.excerpts.cursor::<usize>();
 950        cursor.seek(&offset, Bias::Right, &());
 951        if let Some(excerpt) = cursor.item() {
 952            let header_end = *cursor.start() + excerpt.header_height as usize;
 953            if offset < header_end {
 954                if bias == Bias::Left {
 955                    cursor.prev(&());
 956                    if let Some(excerpt) = cursor.item() {
 957                        return *cursor.start() + excerpt.text_summary.bytes;
 958                    }
 959                }
 960                header_end
 961            } else {
 962                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
 963                let buffer_offset = excerpt
 964                    .buffer
 965                    .clip_offset(excerpt_start + (offset - header_end), bias);
 966                let offset_in_excerpt = if buffer_offset > excerpt_start {
 967                    buffer_offset - excerpt_start
 968                } else {
 969                    0
 970                };
 971                header_end + offset_in_excerpt
 972            }
 973        } else {
 974            self.excerpts.summary().text.bytes
 975        }
 976    }
 977
 978    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
 979        let mut cursor = self.excerpts.cursor::<Point>();
 980        cursor.seek(&point, Bias::Right, &());
 981        if let Some(excerpt) = cursor.item() {
 982            let header_end = *cursor.start() + Point::new(excerpt.header_height as u32, 0);
 983            if point < header_end {
 984                if bias == Bias::Left {
 985                    cursor.prev(&());
 986                    if let Some(excerpt) = cursor.item() {
 987                        return *cursor.start() + excerpt.text_summary.lines;
 988                    }
 989                }
 990                header_end
 991            } else {
 992                let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
 993                let buffer_point = excerpt
 994                    .buffer
 995                    .clip_point(excerpt_start + (point - header_end), bias);
 996                let point_in_excerpt = if buffer_point > excerpt_start {
 997                    buffer_point - excerpt_start
 998                } else {
 999                    Point::zero()
1000                };
1001                header_end + point_in_excerpt
1002            }
1003        } else {
1004            self.excerpts.summary().text.lines
1005        }
1006    }
1007
1008    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1009        let mut cursor = self.excerpts.cursor::<PointUtf16>();
1010        cursor.seek(&point, Bias::Right, &());
1011        if let Some(excerpt) = cursor.item() {
1012            let header_end = *cursor.start() + PointUtf16::new(excerpt.header_height as u32, 0);
1013            if point < header_end {
1014                if bias == Bias::Left {
1015                    cursor.prev(&());
1016                    if let Some(excerpt) = cursor.item() {
1017                        return *cursor.start() + excerpt.text_summary.lines_utf16;
1018                    }
1019                }
1020                header_end
1021            } else {
1022                let excerpt_start = excerpt
1023                    .buffer
1024                    .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1025                let buffer_point = excerpt
1026                    .buffer
1027                    .clip_point_utf16(excerpt_start + (point - header_end), bias);
1028                let point_in_excerpt = if buffer_point > excerpt_start {
1029                    buffer_point - excerpt_start
1030                } else {
1031                    PointUtf16::new(0, 0)
1032                };
1033                header_end + point_in_excerpt
1034            }
1035        } else {
1036            self.excerpts.summary().text.lines_utf16
1037        }
1038    }
1039
1040    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> MultiBufferBytes<'a> {
1041        let range = range.start.to_offset(self)..range.end.to_offset(self);
1042        let mut excerpts = self.excerpts.cursor::<usize>();
1043        excerpts.seek(&range.start, Bias::Right, &());
1044
1045        let mut chunk = &[][..];
1046        let excerpt_bytes = if let Some(excerpt) = excerpts.item() {
1047            let mut excerpt_bytes = excerpt
1048                .bytes_in_range(range.start - excerpts.start()..range.end - excerpts.start());
1049            chunk = excerpt_bytes.next().unwrap_or(&[][..]);
1050            Some(excerpt_bytes)
1051        } else {
1052            None
1053        };
1054
1055        MultiBufferBytes {
1056            range,
1057            excerpts,
1058            excerpt_bytes,
1059            chunk,
1060        }
1061    }
1062
1063    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> MultiBufferRows<'a> {
1064        let mut result = MultiBufferRows {
1065            header_height: 0,
1066            buffer_row_range: 0..0,
1067            excerpts: self.excerpts.cursor(),
1068        };
1069        result.seek(start_row);
1070        result
1071    }
1072
1073    pub fn chunks<'a, T: ToOffset>(
1074        &'a self,
1075        range: Range<T>,
1076        theme: Option<&'a SyntaxTheme>,
1077    ) -> MultiBufferChunks<'a> {
1078        let range = range.start.to_offset(self)..range.end.to_offset(self);
1079        let mut chunks = MultiBufferChunks {
1080            range: range.clone(),
1081            excerpts: self.excerpts.cursor(),
1082            excerpt_chunks: None,
1083            theme,
1084        };
1085        chunks.seek(range.start);
1086        chunks
1087    }
1088
1089    pub fn offset_to_point(&self, offset: usize) -> Point {
1090        let mut cursor = self.excerpts.cursor::<(usize, Point)>();
1091        cursor.seek(&offset, Bias::Right, &());
1092        if let Some(excerpt) = cursor.item() {
1093            let (start_offset, start_point) = cursor.start();
1094            let overshoot = offset - start_offset;
1095            let header_height = excerpt.header_height as usize;
1096            if overshoot < header_height {
1097                *start_point + Point::new(overshoot as u32, 0)
1098            } else {
1099                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1100                let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1101                let buffer_point = excerpt
1102                    .buffer
1103                    .offset_to_point(excerpt_start_offset + (overshoot - header_height));
1104                *start_point
1105                    + Point::new(header_height as u32, 0)
1106                    + (buffer_point - excerpt_start_point)
1107            }
1108        } else {
1109            self.excerpts.summary().text.lines
1110        }
1111    }
1112
1113    pub fn point_to_offset(&self, point: Point) -> usize {
1114        let mut cursor = self.excerpts.cursor::<(Point, usize)>();
1115        cursor.seek(&point, Bias::Right, &());
1116        if let Some(excerpt) = cursor.item() {
1117            let (start_point, start_offset) = cursor.start();
1118            let overshoot = point - start_point;
1119            let header_height = Point::new(excerpt.header_height as u32, 0);
1120            if overshoot < header_height {
1121                start_offset + overshoot.row as usize
1122            } else {
1123                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1124                let excerpt_start_point = excerpt.range.start.to_point(&excerpt.buffer);
1125                let buffer_offset = excerpt
1126                    .buffer
1127                    .point_to_offset(excerpt_start_point + (overshoot - header_height));
1128                *start_offset + excerpt.header_height as usize + buffer_offset
1129                    - excerpt_start_offset
1130            }
1131        } else {
1132            self.excerpts.summary().text.bytes
1133        }
1134    }
1135
1136    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1137        let mut cursor = self.excerpts.cursor::<(PointUtf16, usize)>();
1138        cursor.seek(&point, Bias::Right, &());
1139        if let Some(excerpt) = cursor.item() {
1140            let (start_point, start_offset) = cursor.start();
1141            let overshoot = point - start_point;
1142            let header_height = PointUtf16::new(excerpt.header_height as u32, 0);
1143            if overshoot < header_height {
1144                start_offset + overshoot.row as usize
1145            } else {
1146                let excerpt_start_offset = excerpt.range.start.to_offset(&excerpt.buffer);
1147                let excerpt_start_point = excerpt
1148                    .buffer
1149                    .offset_to_point_utf16(excerpt.range.start.to_offset(&excerpt.buffer));
1150                let buffer_offset = excerpt
1151                    .buffer
1152                    .point_utf16_to_offset(excerpt_start_point + (overshoot - header_height));
1153                *start_offset
1154                    + excerpt.header_height as usize
1155                    + (buffer_offset - excerpt_start_offset)
1156            }
1157        } else {
1158            self.excerpts.summary().text.bytes
1159        }
1160    }
1161
1162    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1163        if let Some((buffer, range)) = self.buffer_line_for_row(row) {
1164            buffer
1165                .indent_column_for_line(range.start.row)
1166                .min(range.end.column)
1167                .saturating_sub(range.start.column)
1168        } else {
1169            0
1170        }
1171    }
1172
1173    pub fn line_len(&self, row: u32) -> u32 {
1174        if let Some((_, range)) = self.buffer_line_for_row(row) {
1175            range.end.column - range.start.column
1176        } else {
1177            0
1178        }
1179    }
1180
1181    fn buffer_line_for_row(&self, row: u32) -> Option<(&BufferSnapshot, Range<Point>)> {
1182        let mut cursor = self.excerpts.cursor::<Point>();
1183        cursor.seek(&Point::new(row, 0), Bias::Right, &());
1184        if let Some(excerpt) = cursor.item() {
1185            let overshoot = row - cursor.start().row;
1186            let header_height = excerpt.header_height as u32;
1187            if overshoot >= header_height {
1188                let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer);
1189                let excerpt_end = excerpt.range.end.to_point(&excerpt.buffer);
1190                let buffer_row = excerpt_start.row + overshoot - header_height;
1191                let line_start = Point::new(buffer_row, 0);
1192                let line_end = Point::new(buffer_row, excerpt.buffer.line_len(buffer_row));
1193                return Some((
1194                    &excerpt.buffer,
1195                    line_start.max(excerpt_start)..line_end.min(excerpt_end),
1196                ));
1197            }
1198        }
1199        None
1200    }
1201
1202    pub fn max_point(&self) -> Point {
1203        self.text_summary().lines
1204    }
1205
1206    pub fn text_summary(&self) -> TextSummary {
1207        self.excerpts.summary().text
1208    }
1209
1210    pub fn text_summary_for_range<'a, D, O>(&'a self, range: Range<O>) -> D
1211    where
1212        D: TextDimension,
1213        O: ToOffset,
1214    {
1215        let mut summary = D::default();
1216        let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1217        let mut cursor = self.excerpts.cursor::<usize>();
1218        cursor.seek(&range.start, Bias::Right, &());
1219        if let Some(excerpt) = cursor.item() {
1220            let start_after_header = cursor.start() + excerpt.header_height as usize;
1221            if range.start < start_after_header {
1222                let header_len = cmp::min(range.end, start_after_header) - range.start;
1223                summary.add_assign(&D::from_text_summary(&TextSummary {
1224                    bytes: header_len,
1225                    lines: Point::new(header_len as u32, 0),
1226                    lines_utf16: PointUtf16::new(header_len as u32, 0),
1227                    first_line_chars: 0,
1228                    last_line_chars: 0,
1229                    longest_row: 0,
1230                    longest_row_chars: 0,
1231                }));
1232                range.start = start_after_header;
1233                range.end = cmp::max(range.start, range.end);
1234            }
1235
1236            let mut end_before_newline = cursor.end(&());
1237            if excerpt.has_trailing_newline {
1238                end_before_newline -= 1;
1239            }
1240
1241            let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1242            let start_in_excerpt = excerpt_start + (range.start - start_after_header);
1243            let end_in_excerpt =
1244                excerpt_start + (cmp::min(end_before_newline, range.end) - start_after_header);
1245            summary.add_assign(
1246                &excerpt
1247                    .buffer
1248                    .text_summary_for_range(start_in_excerpt..end_in_excerpt),
1249            );
1250
1251            if range.end > end_before_newline {
1252                summary.add_assign(&D::from_text_summary(&TextSummary {
1253                    bytes: 1,
1254                    lines: Point::new(1 as u32, 0),
1255                    lines_utf16: PointUtf16::new(1 as u32, 0),
1256                    first_line_chars: 0,
1257                    last_line_chars: 0,
1258                    longest_row: 0,
1259                    longest_row_chars: 0,
1260                }));
1261            }
1262
1263            cursor.next(&());
1264        }
1265
1266        if range.end > *cursor.start() {
1267            summary.add_assign(&D::from_text_summary(&cursor.summary::<_, TextSummary>(
1268                &range.end,
1269                Bias::Right,
1270                &(),
1271            )));
1272            if let Some(excerpt) = cursor.item() {
1273                let start_after_header = cursor.start() + excerpt.header_height as usize;
1274                let header_len =
1275                    cmp::min(range.end - cursor.start(), excerpt.header_height as usize);
1276                summary.add_assign(&D::from_text_summary(&TextSummary {
1277                    bytes: header_len,
1278                    lines: Point::new(header_len as u32, 0),
1279                    lines_utf16: PointUtf16::new(header_len as u32, 0),
1280                    first_line_chars: 0,
1281                    last_line_chars: 0,
1282                    longest_row: 0,
1283                    longest_row_chars: 0,
1284                }));
1285                range.end = cmp::max(start_after_header, range.end);
1286
1287                let excerpt_start = excerpt.range.start.to_offset(&excerpt.buffer);
1288                let end_in_excerpt = excerpt_start + (range.end - start_after_header);
1289                summary.add_assign(
1290                    &excerpt
1291                        .buffer
1292                        .text_summary_for_range(excerpt_start..end_in_excerpt),
1293                );
1294                cursor.next(&());
1295            }
1296        }
1297
1298        summary
1299    }
1300
1301    pub fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
1302    where
1303        D: TextDimension + Ord + Sub<D, Output = D>,
1304    {
1305        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1306        cursor.seek(&Some(&anchor.excerpt_id), Bias::Left, &());
1307        if cursor.item().is_none() {
1308            cursor.next(&());
1309        }
1310
1311        let mut position = D::from_text_summary(&cursor.start().text);
1312        if let Some(excerpt) = cursor.item() {
1313            position.add_summary(&excerpt.header_summary(), &());
1314            if excerpt.id == anchor.excerpt_id {
1315                let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1316                let buffer_position = anchor.text_anchor.summary::<D>(&excerpt.buffer);
1317                if buffer_position > excerpt_buffer_start {
1318                    position.add_assign(&(buffer_position - excerpt_buffer_start));
1319                }
1320            }
1321        }
1322        position
1323    }
1324
1325    pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
1326    where
1327        D: TextDimension + Ord + Sub<D, Output = D>,
1328        I: 'a + IntoIterator<Item = &'a Anchor>,
1329    {
1330        let mut anchors = anchors.into_iter().peekable();
1331        let mut cursor = self.excerpts.cursor::<ExcerptSummary>();
1332        let mut summaries = Vec::new();
1333        while let Some(anchor) = anchors.peek() {
1334            let excerpt_id = &anchor.excerpt_id;
1335            let excerpt_anchors = iter::from_fn(|| {
1336                let anchor = anchors.peek()?;
1337                if anchor.excerpt_id == *excerpt_id {
1338                    Some(&anchors.next().unwrap().text_anchor)
1339                } else {
1340                    None
1341                }
1342            });
1343
1344            cursor.seek_forward(&Some(excerpt_id), Bias::Left, &());
1345            if cursor.item().is_none() {
1346                cursor.next(&());
1347            }
1348
1349            let mut position = D::from_text_summary(&cursor.start().text);
1350            if let Some(excerpt) = cursor.item() {
1351                position.add_summary(&excerpt.header_summary(), &());
1352                if excerpt.id == *excerpt_id {
1353                    let excerpt_buffer_start = excerpt.range.start.summary::<D>(&excerpt.buffer);
1354                    summaries.extend(
1355                        excerpt
1356                            .buffer
1357                            .summaries_for_anchors::<D, _>(excerpt_anchors)
1358                            .map(move |summary| {
1359                                let mut position = position.clone();
1360                                let excerpt_buffer_start = excerpt_buffer_start.clone();
1361                                if summary > excerpt_buffer_start {
1362                                    position.add_assign(&(summary - excerpt_buffer_start));
1363                                }
1364                                position
1365                            }),
1366                    );
1367                    continue;
1368                }
1369            }
1370
1371            summaries.extend(excerpt_anchors.map(|_| position.clone()));
1372        }
1373
1374        summaries
1375    }
1376
1377    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1378        self.anchor_at(position, Bias::Left)
1379    }
1380
1381    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1382        self.anchor_at(position, Bias::Right)
1383    }
1384
1385    pub fn anchor_at<T: ToOffset>(&self, position: T, mut bias: Bias) -> Anchor {
1386        let offset = position.to_offset(self);
1387        let mut cursor = self.excerpts.cursor::<(usize, Option<&ExcerptId>)>();
1388        cursor.seek(&offset, Bias::Right, &());
1389        if cursor.item().is_none() && offset == cursor.start().0 && bias == Bias::Left {
1390            cursor.prev(&());
1391        }
1392        if let Some(excerpt) = cursor.item() {
1393            let start_after_header = cursor.start().0 + excerpt.header_height as usize;
1394            let mut overshoot = offset.saturating_sub(start_after_header);
1395            if excerpt.has_trailing_newline && offset == cursor.end(&()).0 {
1396                overshoot -= 1;
1397                bias = Bias::Right;
1398            }
1399
1400            let buffer_start = excerpt.range.start.to_offset(&excerpt.buffer);
1401            let text_anchor =
1402                excerpt.clip_anchor(excerpt.buffer.anchor_at(buffer_start + overshoot, bias));
1403            Anchor {
1404                excerpt_id: excerpt.id.clone(),
1405                text_anchor,
1406            }
1407        } else if offset == 0 && bias == Bias::Left {
1408            Anchor::min()
1409        } else {
1410            Anchor::max()
1411        }
1412    }
1413
1414    pub fn anchor_in_excerpt(&self, excerpt_id: ExcerptId, text_anchor: text::Anchor) -> Anchor {
1415        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1416        cursor.seek(&Some(&excerpt_id), Bias::Left, &());
1417        if let Some(excerpt) = cursor.item() {
1418            if excerpt.id == excerpt_id {
1419                let text_anchor = excerpt.clip_anchor(text_anchor);
1420                drop(cursor);
1421                return Anchor {
1422                    excerpt_id,
1423                    text_anchor,
1424                };
1425            }
1426        }
1427        panic!("excerpt not found");
1428    }
1429
1430    pub fn parse_count(&self) -> usize {
1431        self.parse_count
1432    }
1433
1434    pub fn enclosing_bracket_ranges<T: ToOffset>(
1435        &self,
1436        range: Range<T>,
1437    ) -> Option<(Range<usize>, Range<usize>)> {
1438        let range = range.start.to_offset(self)..range.end.to_offset(self);
1439
1440        let mut cursor = self.excerpts.cursor::<usize>();
1441        cursor.seek(&range.start, Bias::Right, &());
1442        let start_excerpt = cursor.item();
1443
1444        cursor.seek(&range.end, Bias::Right, &());
1445        let end_excerpt = cursor.item();
1446
1447        start_excerpt
1448            .zip(end_excerpt)
1449            .and_then(|(start_excerpt, end_excerpt)| {
1450                if start_excerpt.id != end_excerpt.id {
1451                    return None;
1452                }
1453
1454                let excerpt_buffer_start =
1455                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1456                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes
1457                    - start_excerpt.header_height as usize;
1458
1459                let start_after_header = cursor.start() + start_excerpt.header_height as usize;
1460                let start_in_buffer =
1461                    excerpt_buffer_start + range.start.saturating_sub(start_after_header);
1462                let end_in_buffer =
1463                    excerpt_buffer_start + range.end.saturating_sub(start_after_header);
1464                let (mut start_bracket_range, mut end_bracket_range) = start_excerpt
1465                    .buffer
1466                    .enclosing_bracket_ranges(start_in_buffer..end_in_buffer)?;
1467
1468                if start_bracket_range.start >= excerpt_buffer_start
1469                    && end_bracket_range.end < excerpt_buffer_end
1470                {
1471                    start_bracket_range.start =
1472                        start_after_header + (start_bracket_range.start - excerpt_buffer_start);
1473                    start_bracket_range.end =
1474                        start_after_header + (start_bracket_range.end - excerpt_buffer_start);
1475                    end_bracket_range.start =
1476                        start_after_header + (end_bracket_range.start - excerpt_buffer_start);
1477                    end_bracket_range.end =
1478                        start_after_header + (end_bracket_range.end - excerpt_buffer_start);
1479                    Some((start_bracket_range, end_bracket_range))
1480                } else {
1481                    None
1482                }
1483            })
1484    }
1485
1486    pub fn diagnostics_update_count(&self) -> usize {
1487        self.diagnostics_update_count
1488    }
1489
1490    pub fn language(&self) -> Option<&Arc<Language>> {
1491        self.excerpts
1492            .iter()
1493            .next()
1494            .and_then(|excerpt| excerpt.buffer.language())
1495    }
1496
1497    pub fn is_dirty(&self) -> bool {
1498        self.is_dirty
1499    }
1500
1501    pub fn has_conflict(&self) -> bool {
1502        self.has_conflict
1503    }
1504
1505    pub fn diagnostic_group<'a, O>(
1506        &'a self,
1507        group_id: usize,
1508    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1509    where
1510        O: text::FromAnchor + 'a,
1511    {
1512        self.as_singleton().unwrap().diagnostic_group(group_id)
1513    }
1514
1515    pub fn diagnostics_in_range<'a, T, O>(
1516        &'a self,
1517        range: Range<T>,
1518    ) -> impl Iterator<Item = DiagnosticEntry<O>> + 'a
1519    where
1520        T: 'a + ToOffset,
1521        O: 'a + text::FromAnchor,
1522    {
1523        let range = range.start.to_offset(self)..range.end.to_offset(self);
1524        self.as_singleton().unwrap().diagnostics_in_range(range)
1525    }
1526
1527    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1528        let range = range.start.to_offset(self)..range.end.to_offset(self);
1529
1530        let mut cursor = self.excerpts.cursor::<usize>();
1531        cursor.seek(&range.start, Bias::Right, &());
1532        let start_excerpt = cursor.item();
1533
1534        cursor.seek(&range.end, Bias::Right, &());
1535        let end_excerpt = cursor.item();
1536
1537        start_excerpt
1538            .zip(end_excerpt)
1539            .and_then(|(start_excerpt, end_excerpt)| {
1540                if start_excerpt.id != end_excerpt.id {
1541                    return None;
1542                }
1543
1544                let excerpt_buffer_start =
1545                    start_excerpt.range.start.to_offset(&start_excerpt.buffer);
1546                let excerpt_buffer_end = excerpt_buffer_start + start_excerpt.text_summary.bytes
1547                    - start_excerpt.header_height as usize;
1548
1549                let start_after_header = cursor.start() + start_excerpt.header_height as usize;
1550                let start_in_buffer =
1551                    excerpt_buffer_start + range.start.saturating_sub(start_after_header);
1552                let end_in_buffer =
1553                    excerpt_buffer_start + range.end.saturating_sub(start_after_header);
1554                let mut ancestor_buffer_range = start_excerpt
1555                    .buffer
1556                    .range_for_syntax_ancestor(start_in_buffer..end_in_buffer)?;
1557                ancestor_buffer_range.start =
1558                    cmp::max(ancestor_buffer_range.start, excerpt_buffer_start);
1559                ancestor_buffer_range.end = cmp::min(ancestor_buffer_range.end, excerpt_buffer_end);
1560
1561                let start =
1562                    start_after_header + (ancestor_buffer_range.start - excerpt_buffer_start);
1563                let end = start_after_header + (ancestor_buffer_range.end - excerpt_buffer_start);
1564                Some(start..end)
1565            })
1566    }
1567
1568    fn buffer_snapshot_for_excerpt<'a>(
1569        &'a self,
1570        excerpt_id: &'a ExcerptId,
1571    ) -> Option<&'a BufferSnapshot> {
1572        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1573        cursor.seek(&Some(excerpt_id), Bias::Left, &());
1574        if let Some(excerpt) = cursor.item() {
1575            if excerpt.id == *excerpt_id {
1576                return Some(&excerpt.buffer);
1577            }
1578        }
1579        None
1580    }
1581
1582    pub fn remote_selections_in_range<'a>(
1583        &'a self,
1584        range: &'a Range<Anchor>,
1585    ) -> impl 'a + Iterator<Item = (ReplicaId, Selection<Anchor>)> {
1586        let mut cursor = self.excerpts.cursor::<Option<&ExcerptId>>();
1587        cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &());
1588        cursor
1589            .take_while(move |excerpt| excerpt.id <= range.end.excerpt_id)
1590            .flat_map(move |excerpt| {
1591                let mut query_range = excerpt.range.start.clone()..excerpt.range.end.clone();
1592                if excerpt.id == range.start.excerpt_id {
1593                    query_range.start = range.start.text_anchor.clone();
1594                }
1595                if excerpt.id == range.end.excerpt_id {
1596                    query_range.end = range.end.text_anchor.clone();
1597                }
1598
1599                excerpt
1600                    .buffer
1601                    .remote_selections_in_range(query_range)
1602                    .flat_map(move |(replica_id, selections)| {
1603                        selections.map(move |selection| {
1604                            let mut start = Anchor {
1605                                excerpt_id: excerpt.id.clone(),
1606                                text_anchor: selection.start.clone(),
1607                            };
1608                            let mut end = Anchor {
1609                                excerpt_id: excerpt.id.clone(),
1610                                text_anchor: selection.end.clone(),
1611                            };
1612                            if range.start.cmp(&start, self).unwrap().is_gt() {
1613                                start = range.start.clone();
1614                            }
1615                            if range.end.cmp(&end, self).unwrap().is_lt() {
1616                                end = range.end.clone();
1617                            }
1618
1619                            (
1620                                replica_id,
1621                                Selection {
1622                                    id: selection.id,
1623                                    start,
1624                                    end,
1625                                    reversed: selection.reversed,
1626                                    goal: selection.goal,
1627                                },
1628                            )
1629                        })
1630                    })
1631            })
1632    }
1633}
1634
1635impl History {
1636    fn start_transaction(&mut self, now: Instant) -> Option<TransactionId> {
1637        self.transaction_depth += 1;
1638        if self.transaction_depth == 1 {
1639            let id = post_inc(&mut self.next_transaction_id);
1640            self.undo_stack.push(Transaction {
1641                id,
1642                buffer_transactions: Default::default(),
1643                first_edit_at: now,
1644                last_edit_at: now,
1645            });
1646            Some(id)
1647        } else {
1648            None
1649        }
1650    }
1651
1652    fn end_transaction(
1653        &mut self,
1654        now: Instant,
1655        buffer_transactions: HashSet<(usize, TransactionId)>,
1656    ) -> bool {
1657        assert_ne!(self.transaction_depth, 0);
1658        self.transaction_depth -= 1;
1659        if self.transaction_depth == 0 {
1660            if buffer_transactions.is_empty() {
1661                self.undo_stack.pop();
1662                false
1663            } else {
1664                let transaction = self.undo_stack.last_mut().unwrap();
1665                transaction.last_edit_at = now;
1666                transaction.buffer_transactions.extend(buffer_transactions);
1667                true
1668            }
1669        } else {
1670            false
1671        }
1672    }
1673
1674    fn pop_undo(&mut self) -> Option<&Transaction> {
1675        assert_eq!(self.transaction_depth, 0);
1676        if let Some(transaction) = self.undo_stack.pop() {
1677            self.redo_stack.push(transaction);
1678            self.redo_stack.last()
1679        } else {
1680            None
1681        }
1682    }
1683
1684    fn pop_redo(&mut self) -> Option<&Transaction> {
1685        assert_eq!(self.transaction_depth, 0);
1686        if let Some(transaction) = self.redo_stack.pop() {
1687            self.undo_stack.push(transaction);
1688            self.undo_stack.last()
1689        } else {
1690            None
1691        }
1692    }
1693
1694    fn group(&mut self) -> Option<TransactionId> {
1695        let mut new_len = self.undo_stack.len();
1696        let mut transactions = self.undo_stack.iter_mut();
1697
1698        if let Some(mut transaction) = transactions.next_back() {
1699            while let Some(prev_transaction) = transactions.next_back() {
1700                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
1701                {
1702                    transaction = prev_transaction;
1703                    new_len -= 1;
1704                } else {
1705                    break;
1706                }
1707            }
1708        }
1709
1710        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
1711        if let Some(last_transaction) = transactions_to_keep.last_mut() {
1712            if let Some(transaction) = transactions_to_merge.last() {
1713                last_transaction.last_edit_at = transaction.last_edit_at;
1714            }
1715        }
1716
1717        self.undo_stack.truncate(new_len);
1718        self.undo_stack.last().map(|t| t.id)
1719    }
1720}
1721
1722impl Excerpt {
1723    fn new(
1724        id: ExcerptId,
1725        buffer_id: usize,
1726        buffer: BufferSnapshot,
1727        range: Range<text::Anchor>,
1728        header_height: u8,
1729        render_header: Option<RenderHeaderFn>,
1730        has_trailing_newline: bool,
1731    ) -> Self {
1732        let mut text_summary =
1733            buffer.text_summary_for_range::<TextSummary, _>(range.to_offset(&buffer));
1734        if header_height > 0 {
1735            text_summary.first_line_chars = 0;
1736            text_summary.lines.row += header_height as u32;
1737            text_summary.lines_utf16.row += header_height as u32;
1738            text_summary.bytes += header_height as usize;
1739            text_summary.longest_row += header_height as u32;
1740        }
1741        Excerpt {
1742            id,
1743            buffer_id,
1744            buffer,
1745            range,
1746            text_summary,
1747            header_height,
1748            render_header,
1749            has_trailing_newline,
1750        }
1751    }
1752
1753    fn header_summary(&self) -> TextSummary {
1754        TextSummary {
1755            bytes: self.header_height as usize,
1756            lines: Point::new(self.header_height as u32, 0),
1757            lines_utf16: PointUtf16::new(self.header_height as u32, 0),
1758            first_line_chars: 0,
1759            last_line_chars: 0,
1760            longest_row: 0,
1761            longest_row_chars: 0,
1762        }
1763    }
1764
1765    fn chunks_in_range<'a>(
1766        &'a self,
1767        range: Range<usize>,
1768        theme: Option<&'a SyntaxTheme>,
1769    ) -> ExcerptChunks<'a> {
1770        let content_start = self.range.start.to_offset(&self.buffer);
1771        let chunks_start = content_start + range.start.saturating_sub(self.header_height as usize);
1772        let chunks_end = content_start
1773            + cmp::min(range.end, self.text_summary.bytes)
1774                .saturating_sub(self.header_height as usize);
1775
1776        let header_height = cmp::min(
1777            (self.header_height as usize).saturating_sub(range.start),
1778            range.len(),
1779        );
1780
1781        let footer_height = if self.has_trailing_newline
1782            && range.start <= self.text_summary.bytes
1783            && range.end > self.text_summary.bytes
1784        {
1785            1
1786        } else {
1787            0
1788        };
1789
1790        let content_chunks = self.buffer.chunks(chunks_start..chunks_end, theme);
1791
1792        ExcerptChunks {
1793            header_height,
1794            content_chunks,
1795            footer_height,
1796        }
1797    }
1798
1799    fn bytes_in_range(&self, range: Range<usize>) -> ExcerptBytes {
1800        let content_start = self.range.start.to_offset(&self.buffer);
1801        let bytes_start = content_start + range.start.saturating_sub(self.header_height as usize);
1802        let bytes_end = content_start
1803            + cmp::min(range.end, self.text_summary.bytes)
1804                .saturating_sub(self.header_height as usize);
1805
1806        let header_height = cmp::min(
1807            (self.header_height as usize).saturating_sub(range.start),
1808            range.len(),
1809        );
1810
1811        let footer_height = if self.has_trailing_newline
1812            && range.start <= self.text_summary.bytes
1813            && range.end > self.text_summary.bytes
1814        {
1815            1
1816        } else {
1817            0
1818        };
1819
1820        let content_bytes = self.buffer.bytes_in_range(bytes_start..bytes_end);
1821
1822        ExcerptBytes {
1823            header_height,
1824            content_bytes,
1825            footer_height,
1826        }
1827    }
1828
1829    fn clip_anchor(&self, text_anchor: text::Anchor) -> text::Anchor {
1830        if text_anchor
1831            .cmp(&self.range.start, &self.buffer)
1832            .unwrap()
1833            .is_lt()
1834        {
1835            self.range.start.clone()
1836        } else if text_anchor
1837            .cmp(&self.range.end, &self.buffer)
1838            .unwrap()
1839            .is_gt()
1840        {
1841            self.range.end.clone()
1842        } else {
1843            text_anchor
1844        }
1845    }
1846}
1847
1848impl fmt::Debug for Excerpt {
1849    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1850        f.debug_struct("Excerpt")
1851            .field("id", &self.id)
1852            .field("buffer_id", &self.buffer_id)
1853            .field("range", &self.range)
1854            .field("text_summary", &self.text_summary)
1855            .field("header_height", &self.header_height)
1856            .field("has_trailing_newline", &self.has_trailing_newline)
1857            .finish()
1858    }
1859}
1860
1861impl sum_tree::Item for Excerpt {
1862    type Summary = ExcerptSummary;
1863
1864    fn summary(&self) -> Self::Summary {
1865        let mut text = self.text_summary.clone();
1866        if self.has_trailing_newline {
1867            text += TextSummary::from("\n");
1868        }
1869        ExcerptSummary {
1870            excerpt_id: self.id.clone(),
1871            text,
1872        }
1873    }
1874}
1875
1876impl sum_tree::Summary for ExcerptSummary {
1877    type Context = ();
1878
1879    fn add_summary(&mut self, summary: &Self, _: &()) {
1880        debug_assert!(summary.excerpt_id > self.excerpt_id);
1881        self.excerpt_id = summary.excerpt_id.clone();
1882        self.text.add_summary(&summary.text, &());
1883    }
1884}
1885
1886impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for TextSummary {
1887    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1888        *self += &summary.text;
1889    }
1890}
1891
1892impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for usize {
1893    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1894        *self += summary.text.bytes;
1895    }
1896}
1897
1898impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for usize {
1899    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1900        Ord::cmp(self, &cursor_location.text.bytes)
1901    }
1902}
1903
1904impl<'a> sum_tree::SeekTarget<'a, ExcerptSummary, ExcerptSummary> for Option<&'a ExcerptId> {
1905    fn cmp(&self, cursor_location: &ExcerptSummary, _: &()) -> cmp::Ordering {
1906        Ord::cmp(self, &Some(&cursor_location.excerpt_id))
1907    }
1908}
1909
1910impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Point {
1911    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1912        *self += summary.text.lines;
1913    }
1914}
1915
1916impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for PointUtf16 {
1917    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1918        *self += summary.text.lines_utf16
1919    }
1920}
1921
1922impl<'a> sum_tree::Dimension<'a, ExcerptSummary> for Option<&'a ExcerptId> {
1923    fn add_summary(&mut self, summary: &'a ExcerptSummary, _: &()) {
1924        *self = Some(&summary.excerpt_id);
1925    }
1926}
1927
1928impl<'a> MultiBufferRows<'a> {
1929    pub fn seek(&mut self, row: u32) {
1930        self.header_height = 0;
1931        self.buffer_row_range = 0..0;
1932
1933        self.excerpts
1934            .seek_forward(&Point::new(row, 0), Bias::Right, &());
1935        if self.excerpts.item().is_none() {
1936            self.excerpts.prev(&());
1937
1938            if self.excerpts.item().is_none() && row == 0 {
1939                self.buffer_row_range = 0..1;
1940                return;
1941            }
1942        }
1943
1944        if let Some(excerpt) = self.excerpts.item() {
1945            let overshoot = row - self.excerpts.start().row;
1946            let excerpt_start = excerpt.range.start.to_point(&excerpt.buffer).row;
1947            let excerpt_header_height = excerpt.header_height as u32;
1948
1949            self.header_height = excerpt_header_height.saturating_sub(overshoot);
1950            self.buffer_row_range.start =
1951                excerpt_start + overshoot.saturating_sub(excerpt_header_height);
1952            self.buffer_row_range.end =
1953                excerpt_start + excerpt.text_summary.lines.row + 1 - excerpt_header_height;
1954        }
1955    }
1956}
1957
1958impl<'a> Iterator for MultiBufferRows<'a> {
1959    type Item = Option<u32>;
1960
1961    fn next(&mut self) -> Option<Self::Item> {
1962        loop {
1963            if self.header_height > 0 {
1964                self.header_height -= 1;
1965                return Some(None);
1966            }
1967            if !self.buffer_row_range.is_empty() {
1968                let row = Some(self.buffer_row_range.start);
1969                self.buffer_row_range.start += 1;
1970                return Some(row);
1971            }
1972            self.excerpts.item()?;
1973            self.excerpts.next(&());
1974            let excerpt = self.excerpts.item()?;
1975            self.header_height = excerpt.header_height as u32;
1976            self.buffer_row_range.start = excerpt.range.start.to_point(&excerpt.buffer).row;
1977            self.buffer_row_range.end =
1978                self.buffer_row_range.start + excerpt.text_summary.lines.row + 1
1979                    - self.header_height;
1980        }
1981    }
1982}
1983
1984impl<'a> MultiBufferChunks<'a> {
1985    pub fn offset(&self) -> usize {
1986        self.range.start
1987    }
1988
1989    pub fn seek(&mut self, offset: usize) {
1990        self.range.start = offset;
1991        self.excerpts.seek(&offset, Bias::Right, &());
1992        if let Some(excerpt) = self.excerpts.item() {
1993            self.excerpt_chunks = Some(excerpt.chunks_in_range(
1994                self.range.start - self.excerpts.start()..self.range.end - self.excerpts.start(),
1995                self.theme,
1996            ));
1997        } else {
1998            self.excerpt_chunks = None;
1999        }
2000    }
2001}
2002
2003impl<'a> Iterator for MultiBufferChunks<'a> {
2004    type Item = Chunk<'a>;
2005
2006    fn next(&mut self) -> Option<Self::Item> {
2007        if self.range.is_empty() {
2008            None
2009        } else if let Some(chunk) = self.excerpt_chunks.as_mut()?.next() {
2010            self.range.start += chunk.text.len();
2011            Some(chunk)
2012        } else {
2013            self.excerpts.next(&());
2014            let excerpt = self.excerpts.item()?;
2015            self.excerpt_chunks = Some(
2016                excerpt.chunks_in_range(0..self.range.end - self.excerpts.start(), self.theme),
2017            );
2018            self.next()
2019        }
2020    }
2021}
2022
2023impl<'a> MultiBufferBytes<'a> {
2024    fn consume(&mut self, len: usize) {
2025        self.range.start += len;
2026        self.chunk = &self.chunk[len..];
2027
2028        if !self.range.is_empty() && self.chunk.is_empty() {
2029            if let Some(chunk) = self.excerpt_bytes.as_mut().and_then(|bytes| bytes.next()) {
2030                self.chunk = chunk;
2031            } else {
2032                self.excerpts.next(&());
2033                if let Some(excerpt) = self.excerpts.item() {
2034                    let mut excerpt_bytes =
2035                        excerpt.bytes_in_range(0..self.range.end - self.excerpts.start());
2036                    self.chunk = excerpt_bytes.next().unwrap();
2037                    self.excerpt_bytes = Some(excerpt_bytes);
2038                }
2039            }
2040        }
2041    }
2042}
2043
2044impl<'a> Iterator for MultiBufferBytes<'a> {
2045    type Item = &'a [u8];
2046
2047    fn next(&mut self) -> Option<Self::Item> {
2048        let chunk = self.chunk;
2049        if chunk.is_empty() {
2050            None
2051        } else {
2052            self.consume(chunk.len());
2053            Some(chunk)
2054        }
2055    }
2056}
2057
2058impl<'a> io::Read for MultiBufferBytes<'a> {
2059    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
2060        let len = cmp::min(buf.len(), self.chunk.len());
2061        buf[..len].copy_from_slice(&self.chunk[..len]);
2062        if len > 0 {
2063            self.consume(len);
2064        }
2065        Ok(len)
2066    }
2067}
2068
2069impl<'a> Iterator for ExcerptBytes<'a> {
2070    type Item = &'a [u8];
2071
2072    fn next(&mut self) -> Option<Self::Item> {
2073        if self.header_height > 0 {
2074            let result = &NEWLINES[..self.header_height];
2075            self.header_height = 0;
2076            return Some(result);
2077        }
2078
2079        if let Some(chunk) = self.content_bytes.next() {
2080            if !chunk.is_empty() {
2081                return Some(chunk);
2082            }
2083        }
2084
2085        if self.footer_height > 0 {
2086            let result = &NEWLINES[..self.footer_height];
2087            self.footer_height = 0;
2088            return Some(result);
2089        }
2090
2091        None
2092    }
2093}
2094
2095impl<'a> Iterator for ExcerptChunks<'a> {
2096    type Item = Chunk<'a>;
2097
2098    fn next(&mut self) -> Option<Self::Item> {
2099        if self.header_height > 0 {
2100            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.header_height]) };
2101            self.header_height = 0;
2102            return Some(Chunk {
2103                text,
2104                ..Default::default()
2105            });
2106        }
2107
2108        if let Some(chunk) = self.content_chunks.next() {
2109            return Some(chunk);
2110        }
2111
2112        if self.footer_height > 0 {
2113            let text = unsafe { str::from_utf8_unchecked(&NEWLINES[..self.footer_height]) };
2114            self.footer_height = 0;
2115            return Some(Chunk {
2116                text,
2117                ..Default::default()
2118            });
2119        }
2120
2121        None
2122    }
2123}
2124
2125impl ToOffset for Point {
2126    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2127        snapshot.point_to_offset(*self)
2128    }
2129}
2130
2131impl ToOffset for PointUtf16 {
2132    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2133        snapshot.point_utf16_to_offset(*self)
2134    }
2135}
2136
2137impl ToOffset for usize {
2138    fn to_offset<'a>(&self, snapshot: &MultiBufferSnapshot) -> usize {
2139        assert!(*self <= snapshot.len(), "offset is out of range");
2140        *self
2141    }
2142}
2143
2144impl ToPoint for usize {
2145    fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
2146        snapshot.offset_to_point(*self)
2147    }
2148}
2149
2150impl ToPoint for Point {
2151    fn to_point<'a>(&self, _: &MultiBufferSnapshot) -> Point {
2152        *self
2153    }
2154}
2155
2156#[cfg(test)]
2157mod tests {
2158    use super::*;
2159    use gpui::{elements::Empty, Element, MutableAppContext};
2160    use language::{Buffer, Rope};
2161    use rand::prelude::*;
2162    use std::env;
2163    use text::{Point, RandomCharIter};
2164    use util::test::sample_text;
2165
2166    #[gpui::test]
2167    fn test_singleton_multibuffer(cx: &mut MutableAppContext) {
2168        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2169        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2170
2171        let snapshot = multibuffer.read(cx).snapshot(cx);
2172        assert_eq!(snapshot.text(), buffer.read(cx).text());
2173
2174        assert_eq!(
2175            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2176            (0..buffer.read(cx).row_count())
2177                .map(Some)
2178                .collect::<Vec<_>>()
2179        );
2180
2181        buffer.update(cx, |buffer, cx| buffer.edit([1..3], "XXX\n", cx));
2182        let snapshot = multibuffer.read(cx).snapshot(cx);
2183
2184        assert_eq!(snapshot.text(), buffer.read(cx).text());
2185        assert_eq!(
2186            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2187            (0..buffer.read(cx).row_count())
2188                .map(Some)
2189                .collect::<Vec<_>>()
2190        );
2191    }
2192
2193    #[gpui::test]
2194    fn test_excerpt_buffer(cx: &mut MutableAppContext) {
2195        let buffer_1 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'a'), cx));
2196        let buffer_2 = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6, 'g'), cx));
2197        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2198
2199        let subscription = multibuffer.update(cx, |multibuffer, cx| {
2200            let subscription = multibuffer.subscribe();
2201            multibuffer.push_excerpt(
2202                ExcerptProperties {
2203                    buffer: &buffer_1,
2204                    range: Point::new(1, 2)..Point::new(2, 5),
2205                    header_height: 2,
2206                    render_header: Some(Arc::new(|_| Empty::new().named("header 1"))),
2207                },
2208                cx,
2209            );
2210            assert_eq!(
2211                subscription.consume().into_inner(),
2212                [Edit {
2213                    old: 0..0,
2214                    new: 0..12
2215                }]
2216            );
2217
2218            multibuffer.push_excerpt(
2219                ExcerptProperties {
2220                    buffer: &buffer_1,
2221                    range: Point::new(3, 3)..Point::new(4, 4),
2222                    header_height: 1,
2223                    render_header: Some(Arc::new(|_| Empty::new().named("header 2"))),
2224                },
2225                cx,
2226            );
2227            multibuffer.push_excerpt(
2228                ExcerptProperties {
2229                    buffer: &buffer_2,
2230                    range: Point::new(3, 1)..Point::new(3, 3),
2231                    header_height: 3,
2232                    render_header: Some(Arc::new(|_| Empty::new().named("header 3"))),
2233                },
2234                cx,
2235            );
2236            assert_eq!(
2237                subscription.consume().into_inner(),
2238                [Edit {
2239                    old: 12..12,
2240                    new: 12..28
2241                }]
2242            );
2243
2244            subscription
2245        });
2246
2247        let snapshot = multibuffer.read(cx).snapshot(cx);
2248        assert_eq!(
2249            snapshot.text(),
2250            concat!(
2251                "\n",      // Preserve newlines
2252                "\n",      //
2253                "bbbb\n",  //
2254                "ccccc\n", //
2255                "\n",      //
2256                "ddd\n",   //
2257                "eeee\n",  //
2258                "\n",      //
2259                "\n",      //
2260                "\n",      //
2261                "jj"       //
2262            )
2263        );
2264        assert_eq!(
2265            snapshot.buffer_rows(0).collect::<Vec<_>>(),
2266            &[
2267                None,
2268                None,
2269                Some(1),
2270                Some(2),
2271                None,
2272                Some(3),
2273                Some(4),
2274                None,
2275                None,
2276                None,
2277                Some(3)
2278            ]
2279        );
2280        assert_eq!(
2281            snapshot.buffer_rows(2).collect::<Vec<_>>(),
2282            &[
2283                Some(1),
2284                Some(2),
2285                None,
2286                Some(3),
2287                Some(4),
2288                None,
2289                None,
2290                None,
2291                Some(3)
2292            ]
2293        );
2294        assert_eq!(snapshot.buffer_rows(10).collect::<Vec<_>>(), &[Some(3)]);
2295        assert_eq!(snapshot.buffer_rows(11).collect::<Vec<_>>(), &[]);
2296        assert_eq!(snapshot.buffer_rows(12).collect::<Vec<_>>(), &[]);
2297
2298        {
2299            let snapshot = multibuffer.read(cx).read(cx);
2300            assert_eq!(
2301                snapshot
2302                    .excerpt_headers_in_range(0..snapshot.max_point().row + 1)
2303                    .map(|(rows, render)| (rows, render(cx).name().unwrap().to_string()))
2304                    .collect::<Vec<_>>(),
2305                &[
2306                    (0..2, "header 1".into()),
2307                    (4..5, "header 2".into()),
2308                    (7..10, "header 3".into())
2309                ]
2310            );
2311
2312            assert_eq!(
2313                snapshot
2314                    .excerpt_headers_in_range(1..5)
2315                    .map(|(rows, render)| (rows, render(cx).name().unwrap().to_string()))
2316                    .collect::<Vec<_>>(),
2317                &[(0..2, "header 1".into()), (4..5, "header 2".into())]
2318            );
2319
2320            assert_eq!(
2321                snapshot
2322                    .excerpt_headers_in_range(2..8)
2323                    .map(|(rows, render)| (rows, render(cx).name().unwrap().to_string()))
2324                    .collect::<Vec<_>>(),
2325                &[(4..5, "header 2".into()), (7..10, "header 3".into())]
2326            );
2327        }
2328
2329        buffer_1.update(cx, |buffer, cx| {
2330            buffer.edit(
2331                [
2332                    Point::new(0, 0)..Point::new(0, 0),
2333                    Point::new(2, 1)..Point::new(2, 3),
2334                ],
2335                "\n",
2336                cx,
2337            );
2338        });
2339
2340        assert_eq!(
2341            multibuffer.read(cx).snapshot(cx).text(),
2342            concat!(
2343                "\n",     // Preserve newlines
2344                "\n",     //
2345                "bbbb\n", //
2346                "c\n",    //
2347                "cc\n",   //
2348                "\n",     //
2349                "ddd\n",  //
2350                "eeee\n", //
2351                "\n",     //
2352                "\n",     //
2353                "\n",     //
2354                "jj"      //
2355            )
2356        );
2357
2358        assert_eq!(
2359            subscription.consume().into_inner(),
2360            [Edit {
2361                old: 8..10,
2362                new: 8..9
2363            }]
2364        );
2365
2366        let multibuffer = multibuffer.read(cx).snapshot(cx);
2367        assert_eq!(
2368            multibuffer.clip_point(Point::new(0, 0), Bias::Left),
2369            Point::new(2, 0)
2370        );
2371        assert_eq!(
2372            multibuffer.clip_point(Point::new(0, 0), Bias::Right),
2373            Point::new(2, 0)
2374        );
2375        assert_eq!(
2376            multibuffer.clip_point(Point::new(1, 0), Bias::Left),
2377            Point::new(2, 0)
2378        );
2379        assert_eq!(
2380            multibuffer.clip_point(Point::new(1, 0), Bias::Right),
2381            Point::new(2, 0)
2382        );
2383        assert_eq!(
2384            multibuffer.clip_point(Point::new(8, 0), Bias::Left),
2385            Point::new(7, 4)
2386        );
2387        assert_eq!(
2388            multibuffer.clip_point(Point::new(8, 0), Bias::Right),
2389            Point::new(11, 0)
2390        );
2391        assert_eq!(
2392            multibuffer.clip_point(Point::new(9, 0), Bias::Left),
2393            Point::new(7, 4)
2394        );
2395        assert_eq!(
2396            multibuffer.clip_point(Point::new(9, 0), Bias::Right),
2397            Point::new(11, 0)
2398        );
2399    }
2400
2401    #[gpui::test]
2402    fn test_empty_excerpt_buffer(cx: &mut MutableAppContext) {
2403        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2404
2405        let snapshot = multibuffer.read(cx).snapshot(cx);
2406        assert_eq!(snapshot.text(), "");
2407        assert_eq!(snapshot.buffer_rows(0).collect::<Vec<_>>(), &[Some(0)]);
2408        assert_eq!(snapshot.buffer_rows(1).collect::<Vec<_>>(), &[]);
2409    }
2410
2411    #[gpui::test]
2412    fn test_singleton_multibuffer_anchors(cx: &mut MutableAppContext) {
2413        let buffer = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2414        let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
2415        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2416        buffer.update(cx, |buffer, cx| {
2417            buffer.edit([0..0], "X", cx);
2418            buffer.edit([5..5], "Y", cx);
2419        });
2420        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2421
2422        assert_eq!(old_snapshot.text(), "abcd");
2423        assert_eq!(new_snapshot.text(), "XabcdY");
2424
2425        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
2426        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
2427        assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
2428        assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
2429    }
2430
2431    #[gpui::test]
2432    fn test_multibuffer_anchors(cx: &mut MutableAppContext) {
2433        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "abcd", cx));
2434        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "efghi", cx));
2435        let multibuffer = cx.add_model(|cx| {
2436            let mut multibuffer = MultiBuffer::new(0);
2437            multibuffer.push_excerpt(
2438                ExcerptProperties {
2439                    buffer: &buffer_1,
2440                    range: 0..4,
2441                    header_height: 1,
2442                    render_header: None,
2443                },
2444                cx,
2445            );
2446            multibuffer.push_excerpt(
2447                ExcerptProperties {
2448                    buffer: &buffer_2,
2449                    range: 0..5,
2450                    header_height: 1,
2451                    render_header: None,
2452                },
2453                cx,
2454            );
2455            multibuffer
2456        });
2457        let old_snapshot = multibuffer.read(cx).snapshot(cx);
2458
2459        assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 1);
2460        assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 1);
2461        assert_eq!(Anchor::min().to_offset(&old_snapshot), 1);
2462        assert_eq!(Anchor::min().to_offset(&old_snapshot), 1);
2463        assert_eq!(Anchor::max().to_offset(&old_snapshot), 12);
2464        assert_eq!(Anchor::max().to_offset(&old_snapshot), 12);
2465
2466        buffer_1.update(cx, |buffer, cx| {
2467            buffer.edit([0..0], "W", cx);
2468            buffer.edit([5..5], "X", cx);
2469        });
2470        buffer_2.update(cx, |buffer, cx| {
2471            buffer.edit([0..0], "Y", cx);
2472            buffer.edit([6..0], "Z", cx);
2473        });
2474        let new_snapshot = multibuffer.read(cx).snapshot(cx);
2475
2476        assert_eq!(old_snapshot.text(), "\nabcd\n\nefghi");
2477        assert_eq!(new_snapshot.text(), "\nWabcdX\n\nYefghiZ");
2478
2479        assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 1);
2480        assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 2);
2481        assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 1);
2482        assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
2483        assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
2484        assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
2485        assert_eq!(old_snapshot.anchor_before(7).to_offset(&new_snapshot), 9);
2486        assert_eq!(old_snapshot.anchor_after(7).to_offset(&new_snapshot), 10);
2487        assert_eq!(old_snapshot.anchor_before(12).to_offset(&new_snapshot), 15);
2488        assert_eq!(old_snapshot.anchor_after(12).to_offset(&new_snapshot), 16);
2489    }
2490
2491    #[gpui::test(iterations = 100)]
2492    fn test_random_excerpts(cx: &mut MutableAppContext, mut rng: StdRng) {
2493        let operations = env::var("OPERATIONS")
2494            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2495            .unwrap_or(10);
2496
2497        let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
2498        let list = cx.add_model(|_| MultiBuffer::new(0));
2499        let mut excerpt_ids = Vec::new();
2500        let mut expected_excerpts = Vec::new();
2501        let mut old_versions = Vec::new();
2502
2503        for _ in 0..operations {
2504            match rng.gen_range(0..100) {
2505                0..=19 if !buffers.is_empty() => {
2506                    let buffer = buffers.choose(&mut rng).unwrap();
2507                    buffer.update(cx, |buf, cx| buf.randomly_edit(&mut rng, 5, cx));
2508                }
2509                _ => {
2510                    let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2511                        let base_text = RandomCharIter::new(&mut rng).take(10).collect::<String>();
2512                        buffers.push(cx.add_model(|cx| Buffer::new(0, base_text, cx)));
2513                        buffers.last().unwrap()
2514                    } else {
2515                        buffers.choose(&mut rng).unwrap()
2516                    };
2517
2518                    let buffer = buffer_handle.read(cx);
2519                    let end_ix = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Right);
2520                    let start_ix = buffer.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2521                    let header_height = rng.gen_range(0..=5);
2522                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2523                    log::info!(
2524                        "Pushing excerpt wih header {}, buffer {}: {:?}[{:?}] = {:?}",
2525                        header_height,
2526                        buffer_handle.id(),
2527                        buffer.text(),
2528                        start_ix..end_ix,
2529                        &buffer.text()[start_ix..end_ix]
2530                    );
2531
2532                    let excerpt_id = list.update(cx, |list, cx| {
2533                        list.push_excerpt(
2534                            ExcerptProperties {
2535                                buffer: &buffer_handle,
2536                                range: start_ix..end_ix,
2537                                header_height,
2538                                render_header: None,
2539                            },
2540                            cx,
2541                        )
2542                    });
2543                    excerpt_ids.push(excerpt_id);
2544                    expected_excerpts.push((buffer_handle.clone(), anchor_range, header_height));
2545                }
2546            }
2547
2548            if rng.gen_bool(0.3) {
2549                list.update(cx, |list, cx| {
2550                    old_versions.push((list.snapshot(cx), list.subscribe()));
2551                })
2552            }
2553
2554            let snapshot = list.read(cx).snapshot(cx);
2555
2556            let mut excerpt_starts = Vec::new();
2557            let mut expected_text = String::new();
2558            let mut expected_buffer_rows = Vec::new();
2559            for (buffer, range, header_height) in &expected_excerpts {
2560                let buffer = buffer.read(cx);
2561                let buffer_range = range.to_offset(buffer);
2562
2563                for _ in 0..*header_height {
2564                    expected_text.push('\n');
2565                    expected_buffer_rows.push(None);
2566                }
2567
2568                excerpt_starts.push(TextSummary::from(expected_text.as_str()));
2569                expected_text.extend(buffer.text_for_range(buffer_range.clone()));
2570                expected_text.push('\n');
2571
2572                let buffer_row_range = buffer.offset_to_point(buffer_range.start).row
2573                    ..=buffer.offset_to_point(buffer_range.end).row;
2574                for row in buffer_row_range {
2575                    expected_buffer_rows.push(Some(row));
2576                }
2577            }
2578            // Remove final trailing newline.
2579            if !expected_excerpts.is_empty() {
2580                expected_text.pop();
2581            }
2582
2583            assert_eq!(snapshot.text(), expected_text);
2584            log::info!("MultiBuffer text: {:?}", expected_text);
2585
2586            assert_eq!(
2587                snapshot.buffer_rows(0).collect::<Vec<_>>(),
2588                expected_buffer_rows,
2589            );
2590
2591            for _ in 0..5 {
2592                let start_row = rng.gen_range(0..=expected_buffer_rows.len());
2593                assert_eq!(
2594                    snapshot.buffer_rows(start_row as u32).collect::<Vec<_>>(),
2595                    &expected_buffer_rows[start_row..],
2596                    "buffer_rows({})",
2597                    start_row
2598                );
2599            }
2600
2601            let mut excerpt_starts = excerpt_starts.into_iter();
2602            for (buffer, range, _) in &expected_excerpts {
2603                let buffer_id = buffer.id();
2604                let buffer = buffer.read(cx);
2605                let buffer_range = range.to_offset(buffer);
2606                let buffer_start_point = buffer.offset_to_point(buffer_range.start);
2607                let buffer_start_point_utf16 =
2608                    buffer.text_summary_for_range::<PointUtf16, _>(0..buffer_range.start);
2609
2610                let excerpt_start = excerpt_starts.next().unwrap();
2611                let mut offset = excerpt_start.bytes;
2612                let mut buffer_offset = buffer_range.start;
2613                let mut point = excerpt_start.lines;
2614                let mut buffer_point = buffer_start_point;
2615                let mut point_utf16 = excerpt_start.lines_utf16;
2616                let mut buffer_point_utf16 = buffer_start_point_utf16;
2617                for ch in buffer
2618                    .snapshot()
2619                    .chunks(buffer_range.clone(), None)
2620                    .flat_map(|c| c.text.chars())
2621                {
2622                    for _ in 0..ch.len_utf8() {
2623                        let left_offset = snapshot.clip_offset(offset, Bias::Left);
2624                        let right_offset = snapshot.clip_offset(offset, Bias::Right);
2625                        let buffer_left_offset = buffer.clip_offset(buffer_offset, Bias::Left);
2626                        let buffer_right_offset = buffer.clip_offset(buffer_offset, Bias::Right);
2627                        assert_eq!(
2628                            left_offset,
2629                            excerpt_start.bytes + (buffer_left_offset - buffer_range.start),
2630                            "clip_offset({:?}, Left). buffer: {:?}, buffer offset: {:?}",
2631                            offset,
2632                            buffer_id,
2633                            buffer_offset,
2634                        );
2635                        assert_eq!(
2636                            right_offset,
2637                            excerpt_start.bytes + (buffer_right_offset - buffer_range.start),
2638                            "clip_offset({:?}, Right). buffer: {:?}, buffer offset: {:?}",
2639                            offset,
2640                            buffer_id,
2641                            buffer_offset,
2642                        );
2643
2644                        let left_point = snapshot.clip_point(point, Bias::Left);
2645                        let right_point = snapshot.clip_point(point, Bias::Right);
2646                        let buffer_left_point = buffer.clip_point(buffer_point, Bias::Left);
2647                        let buffer_right_point = buffer.clip_point(buffer_point, Bias::Right);
2648                        assert_eq!(
2649                            left_point,
2650                            excerpt_start.lines + (buffer_left_point - buffer_start_point),
2651                            "clip_point({:?}, Left). buffer: {:?}, buffer point: {:?}",
2652                            point,
2653                            buffer_id,
2654                            buffer_point,
2655                        );
2656                        assert_eq!(
2657                            right_point,
2658                            excerpt_start.lines + (buffer_right_point - buffer_start_point),
2659                            "clip_point({:?}, Right). buffer: {:?}, buffer point: {:?}",
2660                            point,
2661                            buffer_id,
2662                            buffer_point,
2663                        );
2664
2665                        assert_eq!(
2666                            snapshot.point_to_offset(left_point),
2667                            left_offset,
2668                            "point_to_offset({:?})",
2669                            left_point,
2670                        );
2671                        assert_eq!(
2672                            snapshot.offset_to_point(left_offset),
2673                            left_point,
2674                            "offset_to_point({:?})",
2675                            left_offset,
2676                        );
2677
2678                        offset += 1;
2679                        buffer_offset += 1;
2680                        if ch == '\n' {
2681                            point += Point::new(1, 0);
2682                            buffer_point += Point::new(1, 0);
2683                        } else {
2684                            point += Point::new(0, 1);
2685                            buffer_point += Point::new(0, 1);
2686                        }
2687                    }
2688
2689                    for _ in 0..ch.len_utf16() {
2690                        let left_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Left);
2691                        let right_point_utf16 = snapshot.clip_point_utf16(point_utf16, Bias::Right);
2692                        let buffer_left_point_utf16 =
2693                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Left);
2694                        let buffer_right_point_utf16 =
2695                            buffer.clip_point_utf16(buffer_point_utf16, Bias::Right);
2696                        assert_eq!(
2697                            left_point_utf16,
2698                            excerpt_start.lines_utf16
2699                                + (buffer_left_point_utf16 - buffer_start_point_utf16),
2700                            "clip_point_utf16({:?}, Left). buffer: {:?}, buffer point_utf16: {:?}",
2701                            point_utf16,
2702                            buffer_id,
2703                            buffer_point_utf16,
2704                        );
2705                        assert_eq!(
2706                            right_point_utf16,
2707                            excerpt_start.lines_utf16
2708                                + (buffer_right_point_utf16 - buffer_start_point_utf16),
2709                            "clip_point_utf16({:?}, Right). buffer: {:?}, buffer point_utf16: {:?}",
2710                            point_utf16,
2711                            buffer_id,
2712                            buffer_point_utf16,
2713                        );
2714
2715                        if ch == '\n' {
2716                            point_utf16 += PointUtf16::new(1, 0);
2717                            buffer_point_utf16 += PointUtf16::new(1, 0);
2718                        } else {
2719                            point_utf16 += PointUtf16::new(0, 1);
2720                            buffer_point_utf16 += PointUtf16::new(0, 1);
2721                        }
2722                    }
2723                }
2724            }
2725
2726            for (row, line) in expected_text.split('\n').enumerate() {
2727                assert_eq!(
2728                    snapshot.line_len(row as u32),
2729                    line.len() as u32,
2730                    "line_len({}).",
2731                    row
2732                );
2733            }
2734
2735            let text_rope = Rope::from(expected_text.as_str());
2736            for _ in 0..10 {
2737                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2738                let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2739
2740                assert_eq!(
2741                    snapshot
2742                        .text_for_range(start_ix..end_ix)
2743                        .collect::<String>(),
2744                    &expected_text[start_ix..end_ix],
2745                    "incorrect text for range {:?}",
2746                    start_ix..end_ix
2747                );
2748
2749                let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2750                assert_eq!(
2751                    snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2752                    expected_summary,
2753                    "incorrect summary for range {:?}",
2754                    start_ix..end_ix
2755                );
2756            }
2757
2758            for _ in 0..10 {
2759                let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2760                assert_eq!(
2761                    snapshot.reversed_chars_at(end_ix).collect::<String>(),
2762                    expected_text[..end_ix].chars().rev().collect::<String>(),
2763                );
2764            }
2765
2766            for _ in 0..10 {
2767                let end_ix = rng.gen_range(0..=text_rope.len());
2768                let start_ix = rng.gen_range(0..=end_ix);
2769                assert_eq!(
2770                    snapshot
2771                        .bytes_in_range(start_ix..end_ix)
2772                        .flatten()
2773                        .copied()
2774                        .collect::<Vec<_>>(),
2775                    expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2776                    "bytes_in_range({:?})",
2777                    start_ix..end_ix,
2778                );
2779            }
2780        }
2781
2782        let snapshot = list.read(cx).snapshot(cx);
2783        for (old_snapshot, subscription) in old_versions {
2784            let edits = subscription.consume().into_inner();
2785
2786            log::info!(
2787                "applying subscription edits to old text: {:?}: {:?}",
2788                old_snapshot.text(),
2789                edits,
2790            );
2791
2792            let mut text = old_snapshot.text();
2793            for edit in edits {
2794                let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2795                text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2796            }
2797            assert_eq!(text.to_string(), snapshot.text());
2798        }
2799    }
2800
2801    #[gpui::test]
2802    fn test_history(cx: &mut MutableAppContext) {
2803        let buffer_1 = cx.add_model(|cx| Buffer::new(0, "1234", cx));
2804        let buffer_2 = cx.add_model(|cx| Buffer::new(0, "5678", cx));
2805        let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
2806        let group_interval = multibuffer.read(cx).history.group_interval;
2807        multibuffer.update(cx, |multibuffer, cx| {
2808            multibuffer.push_excerpt(
2809                ExcerptProperties {
2810                    buffer: &buffer_1,
2811                    range: 0..buffer_1.read(cx).len(),
2812                    header_height: 0,
2813                    render_header: None,
2814                },
2815                cx,
2816            );
2817            multibuffer.push_excerpt(
2818                ExcerptProperties {
2819                    buffer: &buffer_2,
2820                    range: 0..buffer_2.read(cx).len(),
2821                    header_height: 0,
2822                    render_header: None,
2823                },
2824                cx,
2825            );
2826        });
2827
2828        let mut now = Instant::now();
2829
2830        multibuffer.update(cx, |multibuffer, cx| {
2831            multibuffer.start_transaction_at(now, cx);
2832            multibuffer.edit(
2833                [
2834                    Point::new(0, 0)..Point::new(0, 0),
2835                    Point::new(1, 0)..Point::new(1, 0),
2836                ],
2837                "A",
2838                cx,
2839            );
2840            multibuffer.edit(
2841                [
2842                    Point::new(0, 1)..Point::new(0, 1),
2843                    Point::new(1, 1)..Point::new(1, 1),
2844                ],
2845                "B",
2846                cx,
2847            );
2848            multibuffer.end_transaction_at(now, cx);
2849            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2850
2851            now += 2 * group_interval;
2852            multibuffer.start_transaction_at(now, cx);
2853            multibuffer.edit([2..2], "C", cx);
2854            multibuffer.end_transaction_at(now, cx);
2855            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2856
2857            multibuffer.undo(cx);
2858            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2859
2860            multibuffer.undo(cx);
2861            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2862
2863            multibuffer.redo(cx);
2864            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2865
2866            multibuffer.redo(cx);
2867            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2868
2869            buffer_1.update(cx, |buffer_1, cx| buffer_1.undo(cx));
2870            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2871
2872            multibuffer.undo(cx);
2873            assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2874
2875            multibuffer.redo(cx);
2876            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2877
2878            multibuffer.redo(cx);
2879            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2880
2881            multibuffer.undo(cx);
2882            assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2883
2884            buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
2885            assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2886
2887            multibuffer.undo(cx);
2888            assert_eq!(multibuffer.read(cx).text(), "C1234\n5678");
2889        });
2890    }
2891}