buffer.rs

   1mod anchor;
   2mod operation_queue;
   3mod point;
   4pub mod rope;
   5mod selection;
   6
   7use crate::{
   8    language::{Language, Tree},
   9    settings::{HighlightId, HighlightMap},
  10    time::{self, ReplicaId},
  11    util::Bias,
  12    worktree::{File, Worktree},
  13};
  14pub use anchor::*;
  15use anyhow::{anyhow, Result};
  16use gpui::{
  17    sum_tree::{self, FilterCursor, SumTree},
  18    AppContext, Entity, ModelContext, ModelHandle, Task,
  19};
  20use lazy_static::lazy_static;
  21use operation_queue::OperationQueue;
  22use parking_lot::Mutex;
  23pub use point::*;
  24pub use rope::{Chunks, Rope, TextSummary};
  25use seahash::SeaHasher;
  26pub use selection::*;
  27use similar::{ChangeTag, TextDiff};
  28use std::{
  29    cell::RefCell,
  30    cmp,
  31    convert::{TryFrom, TryInto},
  32    hash::BuildHasher,
  33    iter::Iterator,
  34    ops::{Deref, DerefMut, Range},
  35    path::Path,
  36    str,
  37    sync::Arc,
  38    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  39};
  40use tree_sitter::{InputEdit, Parser, QueryCursor};
  41use zrpc::proto;
  42
  43#[derive(Clone, Default)]
  44struct DeterministicState;
  45
  46impl BuildHasher for DeterministicState {
  47    type Hasher = SeaHasher;
  48
  49    fn build_hasher(&self) -> Self::Hasher {
  50        SeaHasher::new()
  51    }
  52}
  53
  54#[cfg(test)]
  55type HashMap<K, V> = std::collections::HashMap<K, V, DeterministicState>;
  56
  57#[cfg(test)]
  58type HashSet<T> = std::collections::HashSet<T, DeterministicState>;
  59
  60#[cfg(not(test))]
  61type HashMap<K, V> = std::collections::HashMap<K, V>;
  62
  63#[cfg(not(test))]
  64type HashSet<T> = std::collections::HashSet<T>;
  65
  66thread_local! {
  67    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  68}
  69
  70lazy_static! {
  71    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  72}
  73
  74struct QueryCursorHandle(Option<QueryCursor>);
  75
  76impl QueryCursorHandle {
  77    fn new() -> Self {
  78        QueryCursorHandle(Some(
  79            QUERY_CURSORS
  80                .lock()
  81                .pop()
  82                .unwrap_or_else(|| QueryCursor::new()),
  83        ))
  84    }
  85}
  86
  87impl Deref for QueryCursorHandle {
  88    type Target = QueryCursor;
  89
  90    fn deref(&self) -> &Self::Target {
  91        self.0.as_ref().unwrap()
  92    }
  93}
  94
  95impl DerefMut for QueryCursorHandle {
  96    fn deref_mut(&mut self) -> &mut Self::Target {
  97        self.0.as_mut().unwrap()
  98    }
  99}
 100
 101impl Drop for QueryCursorHandle {
 102    fn drop(&mut self) {
 103        let mut cursor = self.0.take().unwrap();
 104        cursor.set_byte_range(0..usize::MAX);
 105        cursor.set_point_range(Point::zero().into()..Point::MAX.into());
 106        QUERY_CURSORS.lock().push(cursor)
 107    }
 108}
 109
 110pub struct Buffer {
 111    fragments: SumTree<Fragment>,
 112    visible_text: Rope,
 113    deleted_text: Rope,
 114    pub version: time::Global,
 115    saved_version: time::Global,
 116    saved_mtime: SystemTime,
 117    last_edit: time::Local,
 118    undo_map: UndoMap,
 119    history: History,
 120    file: Option<File>,
 121    language: Option<Arc<Language>>,
 122    sync_parse_timeout: Duration,
 123    syntax_tree: Mutex<Option<SyntaxTree>>,
 124    parsing_in_background: bool,
 125    parse_count: usize,
 126    selections: HashMap<SelectionSetId, SelectionSet>,
 127    deferred_ops: OperationQueue,
 128    deferred_replicas: HashSet<ReplicaId>,
 129    replica_id: ReplicaId,
 130    remote_id: u64,
 131    local_clock: time::Local,
 132    lamport_clock: time::Lamport,
 133    #[cfg(test)]
 134    operations: Vec<Operation>,
 135}
 136
 137#[derive(Clone, Debug, Eq, PartialEq)]
 138pub struct SelectionSet {
 139    pub selections: Arc<[Selection]>,
 140    pub active: bool,
 141}
 142
 143#[derive(Clone)]
 144struct SyntaxTree {
 145    tree: Tree,
 146    dirty: bool,
 147    version: time::Global,
 148}
 149
 150#[derive(Clone, Debug)]
 151struct Transaction {
 152    start: time::Global,
 153    end: time::Global,
 154    buffer_was_dirty: bool,
 155    edits: Vec<time::Local>,
 156    ranges: Vec<Range<usize>>,
 157    selections_before: Option<(SelectionSetId, Arc<[Selection]>)>,
 158    selections_after: Option<(SelectionSetId, Arc<[Selection]>)>,
 159    first_edit_at: Instant,
 160    last_edit_at: Instant,
 161}
 162
 163impl Transaction {
 164    fn push_edit(&mut self, edit: &EditOperation) {
 165        self.edits.push(edit.timestamp.local());
 166        self.end.observe(edit.timestamp.local());
 167
 168        let mut other_ranges = edit.ranges.iter().peekable();
 169        let mut new_ranges: Vec<Range<usize>> = Vec::new();
 170        let insertion_len = edit.new_text.as_ref().map_or(0, |t| t.len());
 171        let mut delta = 0;
 172
 173        for mut self_range in self.ranges.iter().cloned() {
 174            self_range.start += delta;
 175            self_range.end += delta;
 176
 177            while let Some(other_range) = other_ranges.peek() {
 178                let mut other_range = (*other_range).clone();
 179                other_range.start += delta;
 180                other_range.end += delta;
 181
 182                if other_range.start <= self_range.end {
 183                    other_ranges.next().unwrap();
 184                    delta += insertion_len;
 185
 186                    if other_range.end < self_range.start {
 187                        new_ranges.push(other_range.start..other_range.end + insertion_len);
 188                        self_range.start += insertion_len;
 189                        self_range.end += insertion_len;
 190                    } else {
 191                        self_range.start = cmp::min(self_range.start, other_range.start);
 192                        self_range.end = cmp::max(self_range.end, other_range.end) + insertion_len;
 193                    }
 194                } else {
 195                    break;
 196                }
 197            }
 198
 199            new_ranges.push(self_range);
 200        }
 201
 202        for other_range in other_ranges {
 203            new_ranges.push(other_range.start + delta..other_range.end + delta + insertion_len);
 204            delta += insertion_len;
 205        }
 206
 207        self.ranges = new_ranges;
 208    }
 209}
 210
 211#[derive(Clone)]
 212pub struct History {
 213    // TODO: Turn this into a String or Rope, maybe.
 214    pub base_text: Arc<str>,
 215    ops: HashMap<time::Local, EditOperation>,
 216    undo_stack: Vec<Transaction>,
 217    redo_stack: Vec<Transaction>,
 218    transaction_depth: usize,
 219    group_interval: Duration,
 220}
 221
 222impl History {
 223    pub fn new(base_text: Arc<str>) -> Self {
 224        Self {
 225            base_text,
 226            ops: Default::default(),
 227            undo_stack: Vec::new(),
 228            redo_stack: Vec::new(),
 229            transaction_depth: 0,
 230            group_interval: Duration::from_millis(300),
 231        }
 232    }
 233
 234    fn push(&mut self, op: EditOperation) {
 235        self.ops.insert(op.timestamp.local(), op);
 236    }
 237
 238    fn start_transaction(
 239        &mut self,
 240        start: time::Global,
 241        buffer_was_dirty: bool,
 242        selections: Option<(SelectionSetId, Arc<[Selection]>)>,
 243        now: Instant,
 244    ) {
 245        self.transaction_depth += 1;
 246        if self.transaction_depth == 1 {
 247            self.undo_stack.push(Transaction {
 248                start: start.clone(),
 249                end: start,
 250                buffer_was_dirty,
 251                edits: Vec::new(),
 252                ranges: Vec::new(),
 253                selections_before: selections,
 254                selections_after: None,
 255                first_edit_at: now,
 256                last_edit_at: now,
 257            });
 258        }
 259    }
 260
 261    fn end_transaction(
 262        &mut self,
 263        selections: Option<(SelectionSetId, Arc<[Selection]>)>,
 264        now: Instant,
 265    ) -> Option<&Transaction> {
 266        assert_ne!(self.transaction_depth, 0);
 267        self.transaction_depth -= 1;
 268        if self.transaction_depth == 0 {
 269            let transaction = self.undo_stack.last_mut().unwrap();
 270            transaction.selections_after = selections;
 271            transaction.last_edit_at = now;
 272            Some(transaction)
 273        } else {
 274            None
 275        }
 276    }
 277
 278    fn group(&mut self) {
 279        let mut new_len = self.undo_stack.len();
 280        let mut transactions = self.undo_stack.iter_mut();
 281
 282        if let Some(mut transaction) = transactions.next_back() {
 283            while let Some(prev_transaction) = transactions.next_back() {
 284                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
 285                    && transaction.start == prev_transaction.end
 286                {
 287                    transaction = prev_transaction;
 288                    new_len -= 1;
 289                } else {
 290                    break;
 291                }
 292            }
 293        }
 294
 295        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
 296        if let Some(last_transaction) = transactions_to_keep.last_mut() {
 297            for transaction in &*transactions_to_merge {
 298                for edit_id in &transaction.edits {
 299                    last_transaction.push_edit(&self.ops[edit_id]);
 300                }
 301            }
 302
 303            if let Some(transaction) = transactions_to_merge.last_mut() {
 304                last_transaction.last_edit_at = transaction.last_edit_at;
 305                last_transaction.selections_after = transaction.selections_after.take();
 306                last_transaction.end = transaction.end.clone();
 307            }
 308        }
 309
 310        self.undo_stack.truncate(new_len);
 311    }
 312
 313    fn push_undo(&mut self, edit_id: time::Local) {
 314        assert_ne!(self.transaction_depth, 0);
 315        let last_transaction = self.undo_stack.last_mut().unwrap();
 316        last_transaction.push_edit(&self.ops[&edit_id]);
 317    }
 318
 319    fn pop_undo(&mut self) -> Option<&Transaction> {
 320        assert_eq!(self.transaction_depth, 0);
 321        if let Some(transaction) = self.undo_stack.pop() {
 322            self.redo_stack.push(transaction);
 323            self.redo_stack.last()
 324        } else {
 325            None
 326        }
 327    }
 328
 329    fn pop_redo(&mut self) -> Option<&Transaction> {
 330        assert_eq!(self.transaction_depth, 0);
 331        if let Some(transaction) = self.redo_stack.pop() {
 332            self.undo_stack.push(transaction);
 333            self.undo_stack.last()
 334        } else {
 335            None
 336        }
 337    }
 338}
 339
 340#[derive(Clone, Default, Debug)]
 341struct UndoMap(HashMap<time::Local, Vec<(time::Local, u32)>>);
 342
 343impl UndoMap {
 344    fn insert(&mut self, undo: &UndoOperation) {
 345        for (edit_id, count) in &undo.counts {
 346            self.0.entry(*edit_id).or_default().push((undo.id, *count));
 347        }
 348    }
 349
 350    fn is_undone(&self, edit_id: time::Local) -> bool {
 351        self.undo_count(edit_id) % 2 == 1
 352    }
 353
 354    fn was_undone(&self, edit_id: time::Local, version: &time::Global) -> bool {
 355        let undo_count = self
 356            .0
 357            .get(&edit_id)
 358            .unwrap_or(&Vec::new())
 359            .iter()
 360            .filter(|(undo_id, _)| version.observed(*undo_id))
 361            .map(|(_, undo_count)| *undo_count)
 362            .max()
 363            .unwrap_or(0);
 364        undo_count % 2 == 1
 365    }
 366
 367    fn undo_count(&self, edit_id: time::Local) -> u32 {
 368        self.0
 369            .get(&edit_id)
 370            .unwrap_or(&Vec::new())
 371            .iter()
 372            .map(|(_, undo_count)| *undo_count)
 373            .max()
 374            .unwrap_or(0)
 375    }
 376}
 377
 378struct Edits<'a, F: Fn(&FragmentSummary) -> bool> {
 379    visible_text: &'a Rope,
 380    deleted_text: &'a Rope,
 381    cursor: Option<FilterCursor<'a, F, Fragment, FragmentTextSummary>>,
 382    undos: &'a UndoMap,
 383    since: time::Global,
 384    old_offset: usize,
 385    new_offset: usize,
 386    old_point: Point,
 387    new_point: Point,
 388}
 389
 390#[derive(Clone, Debug, Default, Eq, PartialEq)]
 391pub struct Edit {
 392    pub old_bytes: Range<usize>,
 393    pub new_bytes: Range<usize>,
 394    pub old_lines: Range<Point>,
 395}
 396
 397impl Edit {
 398    pub fn delta(&self) -> isize {
 399        self.inserted_bytes() as isize - self.deleted_bytes() as isize
 400    }
 401
 402    pub fn deleted_bytes(&self) -> usize {
 403        self.old_bytes.end - self.old_bytes.start
 404    }
 405
 406    pub fn inserted_bytes(&self) -> usize {
 407        self.new_bytes.end - self.new_bytes.start
 408    }
 409
 410    pub fn deleted_lines(&self) -> Point {
 411        self.old_lines.end - self.old_lines.start
 412    }
 413}
 414
 415struct Diff {
 416    base_version: time::Global,
 417    new_text: Arc<str>,
 418    changes: Vec<(ChangeTag, usize)>,
 419}
 420
 421#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 422struct InsertionTimestamp {
 423    replica_id: ReplicaId,
 424    local: time::Seq,
 425    lamport: time::Seq,
 426}
 427
 428impl InsertionTimestamp {
 429    fn local(&self) -> time::Local {
 430        time::Local {
 431            replica_id: self.replica_id,
 432            value: self.local,
 433        }
 434    }
 435
 436    fn lamport(&self) -> time::Lamport {
 437        time::Lamport {
 438            replica_id: self.replica_id,
 439            value: self.lamport,
 440        }
 441    }
 442}
 443
 444#[derive(Eq, PartialEq, Clone, Debug)]
 445struct Fragment {
 446    timestamp: InsertionTimestamp,
 447    len: usize,
 448    visible: bool,
 449    deletions: HashSet<time::Local>,
 450    max_undos: time::Global,
 451}
 452
 453#[derive(Eq, PartialEq, Clone, Debug)]
 454pub struct FragmentSummary {
 455    text: FragmentTextSummary,
 456    max_version: time::Global,
 457    min_insertion_version: time::Global,
 458    max_insertion_version: time::Global,
 459}
 460
 461#[derive(Copy, Default, Clone, Debug, PartialEq, Eq)]
 462struct FragmentTextSummary {
 463    visible: usize,
 464    deleted: usize,
 465}
 466
 467impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FragmentTextSummary {
 468    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<time::Global>) {
 469        self.visible += summary.text.visible;
 470        self.deleted += summary.text.deleted;
 471    }
 472}
 473
 474#[derive(Clone, Debug, Eq, PartialEq)]
 475pub enum Operation {
 476    Edit(EditOperation),
 477    Undo {
 478        undo: UndoOperation,
 479        lamport_timestamp: time::Lamport,
 480    },
 481    UpdateSelections {
 482        set_id: SelectionSetId,
 483        selections: Option<Arc<[Selection]>>,
 484        lamport_timestamp: time::Lamport,
 485    },
 486    SetActiveSelections {
 487        set_id: Option<SelectionSetId>,
 488        lamport_timestamp: time::Lamport,
 489    },
 490    #[cfg(test)]
 491    Test(time::Lamport),
 492}
 493
 494#[derive(Clone, Debug, Eq, PartialEq)]
 495pub struct EditOperation {
 496    timestamp: InsertionTimestamp,
 497    version: time::Global,
 498    ranges: Vec<Range<usize>>,
 499    new_text: Option<String>,
 500}
 501
 502#[derive(Clone, Debug, Eq, PartialEq)]
 503pub struct UndoOperation {
 504    id: time::Local,
 505    counts: HashMap<time::Local, u32>,
 506    ranges: Vec<Range<usize>>,
 507    version: time::Global,
 508}
 509
 510impl Buffer {
 511    pub fn new<T: Into<Arc<str>>>(
 512        replica_id: ReplicaId,
 513        base_text: T,
 514        cx: &mut ModelContext<Self>,
 515    ) -> Self {
 516        Self::build(
 517            replica_id,
 518            History::new(base_text.into()),
 519            None,
 520            cx.model_id() as u64,
 521            None,
 522            cx,
 523        )
 524    }
 525
 526    pub fn from_history(
 527        replica_id: ReplicaId,
 528        history: History,
 529        file: Option<File>,
 530        language: Option<Arc<Language>>,
 531        cx: &mut ModelContext<Self>,
 532    ) -> Self {
 533        Self::build(
 534            replica_id,
 535            history,
 536            file,
 537            cx.model_id() as u64,
 538            language,
 539            cx,
 540        )
 541    }
 542
 543    fn build(
 544        replica_id: ReplicaId,
 545        history: History,
 546        file: Option<File>,
 547        remote_id: u64,
 548        language: Option<Arc<Language>>,
 549        cx: &mut ModelContext<Self>,
 550    ) -> Self {
 551        let saved_mtime;
 552        if let Some(file) = file.as_ref() {
 553            saved_mtime = file.mtime;
 554        } else {
 555            saved_mtime = UNIX_EPOCH;
 556        }
 557
 558        let mut fragments = SumTree::new();
 559
 560        let visible_text = Rope::from(history.base_text.as_ref());
 561        if visible_text.len() > 0 {
 562            fragments.push(
 563                Fragment {
 564                    timestamp: Default::default(),
 565                    len: visible_text.len(),
 566                    visible: true,
 567                    deletions: Default::default(),
 568                    max_undos: Default::default(),
 569                },
 570                &None,
 571            );
 572        }
 573
 574        let mut result = Self {
 575            visible_text,
 576            deleted_text: Rope::new(),
 577            fragments,
 578            version: time::Global::new(),
 579            saved_version: time::Global::new(),
 580            last_edit: time::Local::default(),
 581            undo_map: Default::default(),
 582            history,
 583            file,
 584            syntax_tree: Mutex::new(None),
 585            parsing_in_background: false,
 586            parse_count: 0,
 587            sync_parse_timeout: Duration::from_millis(1),
 588            language,
 589            saved_mtime,
 590            selections: HashMap::default(),
 591            deferred_ops: OperationQueue::new(),
 592            deferred_replicas: HashSet::default(),
 593            replica_id,
 594            remote_id,
 595            local_clock: time::Local::new(replica_id),
 596            lamport_clock: time::Lamport::new(replica_id),
 597
 598            #[cfg(test)]
 599            operations: Default::default(),
 600        };
 601        result.reparse(cx);
 602        result
 603    }
 604
 605    pub fn replica_id(&self) -> ReplicaId {
 606        self.local_clock.replica_id
 607    }
 608
 609    pub fn snapshot(&self) -> Snapshot {
 610        Snapshot {
 611            visible_text: self.visible_text.clone(),
 612            fragments: self.fragments.clone(),
 613            version: self.version.clone(),
 614            tree: self.syntax_tree(),
 615            is_parsing: self.parsing_in_background,
 616            language: self.language.clone(),
 617            query_cursor: QueryCursorHandle::new(),
 618        }
 619    }
 620
 621    pub fn from_proto(
 622        replica_id: ReplicaId,
 623        message: proto::Buffer,
 624        file: Option<File>,
 625        language: Option<Arc<Language>>,
 626        cx: &mut ModelContext<Self>,
 627    ) -> Result<Self> {
 628        let mut buffer = Buffer::build(
 629            replica_id,
 630            History::new(message.content.into()),
 631            file,
 632            message.id,
 633            language,
 634            cx,
 635        );
 636        let ops = message
 637            .history
 638            .into_iter()
 639            .map(|op| Operation::Edit(op.into()));
 640        buffer.apply_ops(ops, cx)?;
 641        buffer.selections = message
 642            .selections
 643            .into_iter()
 644            .map(|set| {
 645                let set_id = time::Lamport {
 646                    replica_id: set.replica_id as ReplicaId,
 647                    value: set.local_timestamp,
 648                };
 649                let selections: Vec<Selection> = set
 650                    .selections
 651                    .into_iter()
 652                    .map(TryFrom::try_from)
 653                    .collect::<Result<_, _>>()?;
 654                let set = SelectionSet {
 655                    selections: Arc::from(selections),
 656                    active: set.is_active,
 657                };
 658                Result::<_, anyhow::Error>::Ok((set_id, set))
 659            })
 660            .collect::<Result<_, _>>()?;
 661        Ok(buffer)
 662    }
 663
 664    pub fn to_proto(&self, cx: &mut ModelContext<Self>) -> proto::Buffer {
 665        let ops = self.history.ops.values().map(Into::into).collect();
 666        proto::Buffer {
 667            id: cx.model_id() as u64,
 668            content: self.history.base_text.to_string(),
 669            history: ops,
 670            selections: self
 671                .selections
 672                .iter()
 673                .map(|(set_id, set)| proto::SelectionSetSnapshot {
 674                    replica_id: set_id.replica_id as u32,
 675                    local_timestamp: set_id.value,
 676                    selections: set.selections.iter().map(Into::into).collect(),
 677                    is_active: set.active,
 678                })
 679                .collect(),
 680        }
 681    }
 682
 683    pub fn file(&self) -> Option<&File> {
 684        self.file.as_ref()
 685    }
 686
 687    pub fn file_mut(&mut self) -> Option<&mut File> {
 688        self.file.as_mut()
 689    }
 690
 691    pub fn save(
 692        &mut self,
 693        cx: &mut ModelContext<Self>,
 694    ) -> Result<Task<Result<(time::Global, SystemTime)>>> {
 695        let file = self
 696            .file
 697            .as_ref()
 698            .ok_or_else(|| anyhow!("buffer has no file"))?;
 699        let text = self.visible_text.clone();
 700        let version = self.version.clone();
 701        let save = file.save(self.remote_id, text, version, cx.as_mut());
 702        Ok(cx.spawn(|this, mut cx| async move {
 703            let (version, mtime) = save.await?;
 704            this.update(&mut cx, |this, cx| {
 705                this.did_save(version.clone(), mtime, cx);
 706            });
 707            Ok((version, mtime))
 708        }))
 709    }
 710
 711    pub fn save_as(
 712        &mut self,
 713        worktree: &ModelHandle<Worktree>,
 714        path: impl Into<Arc<Path>>,
 715        cx: &mut ModelContext<Self>,
 716    ) -> Task<Result<()>> {
 717        let handle = cx.handle();
 718        let text = self.visible_text.clone();
 719        let version = self.version.clone();
 720        let save_as = worktree.update(cx, |worktree, cx| {
 721            worktree
 722                .as_local_mut()
 723                .unwrap()
 724                .save_buffer_as(handle, path, text, cx)
 725        });
 726
 727        cx.spawn(|this, mut cx| async move {
 728            save_as.await.map(|new_file| {
 729                this.update(&mut cx, |this, cx| {
 730                    let mtime = new_file.mtime;
 731                    this.file = Some(new_file);
 732                    this.did_save(version, mtime, cx);
 733                });
 734            })
 735        })
 736    }
 737
 738    pub fn did_save(
 739        &mut self,
 740        version: time::Global,
 741        mtime: SystemTime,
 742        cx: &mut ModelContext<Self>,
 743    ) {
 744        self.saved_mtime = mtime;
 745        self.saved_version = version;
 746        cx.emit(Event::Saved);
 747    }
 748
 749    pub fn file_updated(
 750        &mut self,
 751        path: Arc<Path>,
 752        mtime: SystemTime,
 753        new_text: Option<String>,
 754        cx: &mut ModelContext<Self>,
 755    ) {
 756        let file = self.file.as_mut().unwrap();
 757        let mut changed = false;
 758        if path != file.path {
 759            file.path = path;
 760            changed = true;
 761        }
 762
 763        if mtime != file.mtime {
 764            file.mtime = mtime;
 765            changed = true;
 766            if let Some(new_text) = new_text {
 767                if self.version == self.saved_version {
 768                    cx.spawn(|this, mut cx| async move {
 769                        let diff = this
 770                            .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
 771                            .await;
 772                        this.update(&mut cx, |this, cx| {
 773                            if this.apply_diff(diff, cx) {
 774                                this.saved_version = this.version.clone();
 775                                this.saved_mtime = mtime;
 776                                cx.emit(Event::Reloaded);
 777                            }
 778                        });
 779                    })
 780                    .detach();
 781                }
 782            }
 783        }
 784
 785        if changed {
 786            cx.emit(Event::FileHandleChanged);
 787        }
 788    }
 789
 790    pub fn file_deleted(&mut self, cx: &mut ModelContext<Self>) {
 791        if self.version == self.saved_version {
 792            cx.emit(Event::Dirtied);
 793        }
 794        cx.emit(Event::FileHandleChanged);
 795    }
 796
 797    pub fn parse_count(&self) -> usize {
 798        self.parse_count
 799    }
 800
 801    pub fn syntax_tree(&self) -> Option<Tree> {
 802        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 803            let mut delta = 0_isize;
 804            for edit in self.edits_since(syntax_tree.version.clone()) {
 805                let start_offset = (edit.old_bytes.start as isize + delta) as usize;
 806                let start_point = self.visible_text.to_point(start_offset);
 807                syntax_tree.tree.edit(&InputEdit {
 808                    start_byte: start_offset,
 809                    old_end_byte: start_offset + edit.deleted_bytes(),
 810                    new_end_byte: start_offset + edit.inserted_bytes(),
 811                    start_position: start_point.into(),
 812                    old_end_position: (start_point + edit.deleted_lines()).into(),
 813                    new_end_position: self
 814                        .visible_text
 815                        .to_point(start_offset + edit.inserted_bytes())
 816                        .into(),
 817                });
 818                delta += edit.inserted_bytes() as isize - edit.deleted_bytes() as isize;
 819                syntax_tree.dirty = true;
 820            }
 821            syntax_tree.version = self.version();
 822            Some(syntax_tree.tree.clone())
 823        } else {
 824            None
 825        }
 826    }
 827
 828    #[cfg(test)]
 829    pub fn is_parsing(&self) -> bool {
 830        self.parsing_in_background
 831    }
 832
 833    #[cfg(test)]
 834    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 835        self.sync_parse_timeout = timeout;
 836    }
 837
 838    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 839        if self.parsing_in_background {
 840            return false;
 841        }
 842
 843        if let Some(language) = self.language.clone() {
 844            // The parse tree is out of date, so grab the syntax tree to synchronously
 845            // splice all the edits that have happened since the last parse.
 846            let old_tree = self.syntax_tree();
 847            let parsed_text = self.visible_text.clone();
 848            let parsed_version = self.version();
 849            let parse_task = cx.background().spawn({
 850                let language = language.clone();
 851                async move { Self::parse_text(&parsed_text, old_tree, &language) }
 852            });
 853
 854            match cx
 855                .background()
 856                .block_with_timeout(self.sync_parse_timeout, parse_task)
 857            {
 858                Ok(new_tree) => {
 859                    *self.syntax_tree.lock() = Some(SyntaxTree {
 860                        tree: new_tree,
 861                        dirty: false,
 862                        version: parsed_version,
 863                    });
 864                    self.parse_count += 1;
 865                    cx.emit(Event::Reparsed);
 866                    cx.notify();
 867                    return true;
 868                }
 869                Err(parse_task) => {
 870                    self.parsing_in_background = true;
 871                    cx.spawn(move |this, mut cx| async move {
 872                        let new_tree = parse_task.await;
 873                        this.update(&mut cx, move |this, cx| {
 874                            let parse_again = this.version > parsed_version;
 875                            *this.syntax_tree.lock() = Some(SyntaxTree {
 876                                tree: new_tree,
 877                                dirty: false,
 878                                version: parsed_version,
 879                            });
 880                            this.parse_count += 1;
 881                            this.parsing_in_background = false;
 882
 883                            if parse_again && this.reparse(cx) {
 884                                return;
 885                            }
 886
 887                            cx.emit(Event::Reparsed);
 888                            cx.notify();
 889                        });
 890                    })
 891                    .detach();
 892                }
 893            }
 894        }
 895        false
 896    }
 897
 898    fn parse_text(text: &Rope, old_tree: Option<Tree>, language: &Language) -> Tree {
 899        PARSER.with(|parser| {
 900            let mut parser = parser.borrow_mut();
 901            parser
 902                .set_language(language.grammar)
 903                .expect("incompatible grammar");
 904            let mut chunks = text.chunks_in_range(0..text.len());
 905            let tree = parser
 906                .parse_with(
 907                    &mut move |offset, _| {
 908                        chunks.seek(offset);
 909                        chunks.next().unwrap_or("").as_bytes()
 910                    },
 911                    old_tree.as_ref(),
 912                )
 913                .unwrap();
 914            tree
 915        })
 916    }
 917
 918    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
 919        if let Some(tree) = self.syntax_tree() {
 920            let root = tree.root_node();
 921            let range = range.start.to_offset(self)..range.end.to_offset(self);
 922            let mut node = root.descendant_for_byte_range(range.start, range.end);
 923            while node.map_or(false, |n| n.byte_range() == range) {
 924                node = node.unwrap().parent();
 925            }
 926            node.map(|n| n.byte_range())
 927        } else {
 928            None
 929        }
 930    }
 931
 932    pub fn enclosing_bracket_ranges<T: ToOffset>(
 933        &self,
 934        range: Range<T>,
 935    ) -> Option<(Range<usize>, Range<usize>)> {
 936        let (lang, tree) = self.language.as_ref().zip(self.syntax_tree())?;
 937        let open_capture_ix = lang.brackets_query.capture_index_for_name("open")?;
 938        let close_capture_ix = lang.brackets_query.capture_index_for_name("close")?;
 939
 940        // Find bracket pairs that *inclusively* contain the given range.
 941        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
 942        let mut cursor = QueryCursorHandle::new();
 943        let matches = cursor.set_byte_range(range).matches(
 944            &lang.brackets_query,
 945            tree.root_node(),
 946            TextProvider(&self.visible_text),
 947        );
 948
 949        // Get the ranges of the innermost pair of brackets.
 950        matches
 951            .filter_map(|mat| {
 952                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
 953                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
 954                Some((open.byte_range(), close.byte_range()))
 955            })
 956            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
 957    }
 958
 959    fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
 960        // TODO: it would be nice to not allocate here.
 961        let old_text = self.text();
 962        let base_version = self.version();
 963        cx.background().spawn(async move {
 964            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
 965                .iter_all_changes()
 966                .map(|c| (c.tag(), c.value().len()))
 967                .collect::<Vec<_>>();
 968            Diff {
 969                base_version,
 970                new_text,
 971                changes,
 972            }
 973        })
 974    }
 975
 976    pub fn set_text_from_disk(&self, new_text: Arc<str>, cx: &mut ModelContext<Self>) -> Task<()> {
 977        cx.spawn(|this, mut cx| async move {
 978            let diff = this
 979                .read_with(&cx, |this, cx| this.diff(new_text, cx))
 980                .await;
 981
 982            this.update(&mut cx, |this, cx| {
 983                if this.apply_diff(diff, cx) {
 984                    this.saved_version = this.version.clone();
 985                }
 986            });
 987        })
 988    }
 989
 990    fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
 991        if self.version == diff.base_version {
 992            self.start_transaction(None).unwrap();
 993            let mut offset = 0;
 994            for (tag, len) in diff.changes {
 995                let range = offset..(offset + len);
 996                match tag {
 997                    ChangeTag::Equal => offset += len,
 998                    ChangeTag::Delete => self.edit(Some(range), "", cx),
 999                    ChangeTag::Insert => {
1000                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1001                        offset += len;
1002                    }
1003                }
1004            }
1005            self.end_transaction(None, cx).unwrap();
1006            true
1007        } else {
1008            false
1009        }
1010    }
1011
1012    pub fn is_dirty(&self) -> bool {
1013        self.version > self.saved_version
1014            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1015    }
1016
1017    pub fn has_conflict(&self) -> bool {
1018        self.version > self.saved_version
1019            && self
1020                .file
1021                .as_ref()
1022                .map_or(false, |file| file.mtime > self.saved_mtime)
1023    }
1024
1025    pub fn remote_id(&self) -> u64 {
1026        self.remote_id
1027    }
1028
1029    pub fn version(&self) -> time::Global {
1030        self.version.clone()
1031    }
1032
1033    pub fn text_summary(&self) -> TextSummary {
1034        self.visible_text.summary()
1035    }
1036
1037    pub fn len(&self) -> usize {
1038        self.content().len()
1039    }
1040
1041    pub fn line_len(&self, row: u32) -> u32 {
1042        self.content().line_len(row)
1043    }
1044
1045    pub fn max_point(&self) -> Point {
1046        self.visible_text.max_point()
1047    }
1048
1049    pub fn row_count(&self) -> u32 {
1050        self.max_point().row + 1
1051    }
1052
1053    pub fn text(&self) -> String {
1054        self.text_for_range(0..self.len()).collect()
1055    }
1056
1057    pub fn text_for_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> Chunks<'a> {
1058        let start = range.start.to_offset(self);
1059        let end = range.end.to_offset(self);
1060        self.visible_text.chunks_in_range(start..end)
1061    }
1062
1063    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
1064        self.chars_at(0)
1065    }
1066
1067    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1068        let offset = position.to_offset(self);
1069        self.visible_text.chars_at(offset)
1070    }
1071
1072    pub fn edits_since<'a>(&'a self, since: time::Global) -> impl 'a + Iterator<Item = Edit> {
1073        let since_2 = since.clone();
1074        let cursor = if since == self.version {
1075            None
1076        } else {
1077            Some(self.fragments.filter(
1078                move |summary| summary.max_version.changed_since(&since_2),
1079                &None,
1080            ))
1081        };
1082
1083        Edits {
1084            visible_text: &self.visible_text,
1085            deleted_text: &self.deleted_text,
1086            cursor,
1087            undos: &self.undo_map,
1088            since,
1089            old_offset: 0,
1090            new_offset: 0,
1091            old_point: Point::zero(),
1092            new_point: Point::zero(),
1093        }
1094    }
1095
1096    pub fn deferred_ops_len(&self) -> usize {
1097        self.deferred_ops.len()
1098    }
1099
1100    pub fn start_transaction(&mut self, set_id: Option<SelectionSetId>) -> Result<()> {
1101        self.start_transaction_at(set_id, Instant::now())
1102    }
1103
1104    fn start_transaction_at(&mut self, set_id: Option<SelectionSetId>, now: Instant) -> Result<()> {
1105        let selections = if let Some(set_id) = set_id {
1106            let set = self
1107                .selections
1108                .get(&set_id)
1109                .ok_or_else(|| anyhow!("invalid selection set {:?}", set_id))?;
1110            Some((set_id, set.selections.clone()))
1111        } else {
1112            None
1113        };
1114        self.history
1115            .start_transaction(self.version.clone(), self.is_dirty(), selections, now);
1116        Ok(())
1117    }
1118
1119    pub fn end_transaction(
1120        &mut self,
1121        set_id: Option<SelectionSetId>,
1122        cx: &mut ModelContext<Self>,
1123    ) -> Result<()> {
1124        self.end_transaction_at(set_id, Instant::now(), cx)
1125    }
1126
1127    fn end_transaction_at(
1128        &mut self,
1129        set_id: Option<SelectionSetId>,
1130        now: Instant,
1131        cx: &mut ModelContext<Self>,
1132    ) -> Result<()> {
1133        let selections = if let Some(set_id) = set_id {
1134            let set = self
1135                .selections
1136                .get(&set_id)
1137                .ok_or_else(|| anyhow!("invalid selection set {:?}", set_id))?;
1138            Some((set_id, set.selections.clone()))
1139        } else {
1140            None
1141        };
1142
1143        if let Some(transaction) = self.history.end_transaction(selections, now) {
1144            let since = transaction.start.clone();
1145            let was_dirty = transaction.buffer_was_dirty;
1146            self.history.group();
1147
1148            cx.notify();
1149            if self.edits_since(since).next().is_some() {
1150                self.did_edit(was_dirty, cx);
1151                self.reparse(cx);
1152            }
1153        }
1154
1155        Ok(())
1156    }
1157
1158    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1159    where
1160        I: IntoIterator<Item = Range<S>>,
1161        S: ToOffset,
1162        T: Into<String>,
1163    {
1164        let new_text = new_text.into();
1165        let new_text = if new_text.len() > 0 {
1166            Some(new_text)
1167        } else {
1168            None
1169        };
1170        let has_new_text = new_text.is_some();
1171
1172        // Skip invalid ranges and coalesce contiguous ones.
1173        let mut ranges: Vec<Range<usize>> = Vec::new();
1174        for range in ranges_iter {
1175            let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1176            if has_new_text || !range.is_empty() {
1177                if let Some(prev_range) = ranges.last_mut() {
1178                    if prev_range.end >= range.start {
1179                        prev_range.end = cmp::max(prev_range.end, range.end);
1180                    } else {
1181                        ranges.push(range);
1182                    }
1183                } else {
1184                    ranges.push(range);
1185                }
1186            }
1187        }
1188
1189        if !ranges.is_empty() {
1190            self.start_transaction_at(None, Instant::now()).unwrap();
1191            let timestamp = InsertionTimestamp {
1192                replica_id: self.replica_id,
1193                local: self.local_clock.tick().value,
1194                lamport: self.lamport_clock.tick().value,
1195            };
1196            let edit = self.apply_local_edit(&ranges, new_text, timestamp);
1197
1198            self.history.push(edit.clone());
1199            self.history.push_undo(edit.timestamp.local());
1200            self.last_edit = edit.timestamp.local();
1201            self.version.observe(edit.timestamp.local());
1202
1203            self.end_transaction_at(None, Instant::now(), cx).unwrap();
1204            self.send_operation(Operation::Edit(edit), cx);
1205        };
1206    }
1207
1208    fn did_edit(&self, was_dirty: bool, cx: &mut ModelContext<Self>) {
1209        cx.emit(Event::Edited);
1210        if !was_dirty {
1211            cx.emit(Event::Dirtied);
1212        }
1213    }
1214
1215    pub fn add_selection_set(
1216        &mut self,
1217        selections: impl Into<Arc<[Selection]>>,
1218        cx: &mut ModelContext<Self>,
1219    ) -> SelectionSetId {
1220        let selections = selections.into();
1221        let lamport_timestamp = self.lamport_clock.tick();
1222        self.selections.insert(
1223            lamport_timestamp,
1224            SelectionSet {
1225                selections: selections.clone(),
1226                active: false,
1227            },
1228        );
1229        cx.notify();
1230
1231        self.send_operation(
1232            Operation::UpdateSelections {
1233                set_id: lamport_timestamp,
1234                selections: Some(selections),
1235                lamport_timestamp,
1236            },
1237            cx,
1238        );
1239
1240        lamport_timestamp
1241    }
1242
1243    pub fn update_selection_set(
1244        &mut self,
1245        set_id: SelectionSetId,
1246        selections: impl Into<Arc<[Selection]>>,
1247        cx: &mut ModelContext<Self>,
1248    ) -> Result<()> {
1249        let selections = selections.into();
1250        let set = self
1251            .selections
1252            .get_mut(&set_id)
1253            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1254        set.selections = selections.clone();
1255        let lamport_timestamp = self.lamport_clock.tick();
1256        cx.notify();
1257        self.send_operation(
1258            Operation::UpdateSelections {
1259                set_id,
1260                selections: Some(selections),
1261                lamport_timestamp,
1262            },
1263            cx,
1264        );
1265        Ok(())
1266    }
1267
1268    pub fn set_active_selection_set(
1269        &mut self,
1270        set_id: Option<SelectionSetId>,
1271        cx: &mut ModelContext<Self>,
1272    ) -> Result<()> {
1273        if let Some(set_id) = set_id {
1274            assert_eq!(set_id.replica_id, self.replica_id());
1275        }
1276
1277        for (id, set) in &mut self.selections {
1278            if id.replica_id == self.local_clock.replica_id {
1279                if Some(*id) == set_id {
1280                    set.active = true;
1281                } else {
1282                    set.active = false;
1283                }
1284            }
1285        }
1286
1287        let lamport_timestamp = self.lamport_clock.tick();
1288        self.send_operation(
1289            Operation::SetActiveSelections {
1290                set_id,
1291                lamport_timestamp,
1292            },
1293            cx,
1294        );
1295        Ok(())
1296    }
1297
1298    pub fn remove_selection_set(
1299        &mut self,
1300        set_id: SelectionSetId,
1301        cx: &mut ModelContext<Self>,
1302    ) -> Result<()> {
1303        self.selections
1304            .remove(&set_id)
1305            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1306        let lamport_timestamp = self.lamport_clock.tick();
1307        cx.notify();
1308        self.send_operation(
1309            Operation::UpdateSelections {
1310                set_id,
1311                selections: None,
1312                lamport_timestamp,
1313            },
1314            cx,
1315        );
1316        Ok(())
1317    }
1318
1319    pub fn selection_set(&self, set_id: SelectionSetId) -> Result<&SelectionSet> {
1320        self.selections
1321            .get(&set_id)
1322            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))
1323    }
1324
1325    pub fn selection_sets(&self) -> impl Iterator<Item = (&SelectionSetId, &SelectionSet)> {
1326        self.selections.iter()
1327    }
1328
1329    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1330        &mut self,
1331        ops: I,
1332        cx: &mut ModelContext<Self>,
1333    ) -> Result<()> {
1334        let was_dirty = self.is_dirty();
1335        let old_version = self.version.clone();
1336
1337        let mut deferred_ops = Vec::new();
1338        for op in ops {
1339            if self.can_apply_op(&op) {
1340                self.apply_op(op)?;
1341            } else {
1342                self.deferred_replicas.insert(op.replica_id());
1343                deferred_ops.push(op);
1344            }
1345        }
1346        self.deferred_ops.insert(deferred_ops);
1347        self.flush_deferred_ops()?;
1348
1349        cx.notify();
1350        if self.edits_since(old_version).next().is_some() {
1351            self.did_edit(was_dirty, cx);
1352            self.reparse(cx);
1353        }
1354
1355        Ok(())
1356    }
1357
1358    fn apply_op(&mut self, op: Operation) -> Result<()> {
1359        match op {
1360            Operation::Edit(edit) => {
1361                if !self.version.observed(edit.timestamp.local()) {
1362                    self.apply_remote_edit(
1363                        &edit.version,
1364                        &edit.ranges,
1365                        edit.new_text.as_deref(),
1366                        edit.timestamp,
1367                    );
1368                    self.version.observe(edit.timestamp.local());
1369                    self.history.push(edit);
1370                }
1371            }
1372            Operation::Undo {
1373                undo,
1374                lamport_timestamp,
1375            } => {
1376                if !self.version.observed(undo.id) {
1377                    self.apply_undo(&undo)?;
1378                    self.version.observe(undo.id);
1379                    self.lamport_clock.observe(lamport_timestamp);
1380                }
1381            }
1382            Operation::UpdateSelections {
1383                set_id,
1384                selections,
1385                lamport_timestamp,
1386            } => {
1387                if let Some(selections) = selections {
1388                    if let Some(set) = self.selections.get_mut(&set_id) {
1389                        set.selections = selections;
1390                    } else {
1391                        self.selections.insert(
1392                            set_id,
1393                            SelectionSet {
1394                                selections,
1395                                active: false,
1396                            },
1397                        );
1398                    }
1399                } else {
1400                    self.selections.remove(&set_id);
1401                }
1402                self.lamport_clock.observe(lamport_timestamp);
1403            }
1404            Operation::SetActiveSelections {
1405                set_id,
1406                lamport_timestamp,
1407            } => {
1408                for (id, set) in &mut self.selections {
1409                    if id.replica_id == lamport_timestamp.replica_id {
1410                        if Some(*id) == set_id {
1411                            set.active = true;
1412                        } else {
1413                            set.active = false;
1414                        }
1415                    }
1416                }
1417                self.lamport_clock.observe(lamport_timestamp);
1418            }
1419            #[cfg(test)]
1420            Operation::Test(_) => {}
1421        }
1422        Ok(())
1423    }
1424
1425    fn apply_remote_edit(
1426        &mut self,
1427        version: &time::Global,
1428        ranges: &[Range<usize>],
1429        new_text: Option<&str>,
1430        timestamp: InsertionTimestamp,
1431    ) {
1432        if ranges.is_empty() {
1433            return;
1434        }
1435
1436        let cx = Some(version.clone());
1437        let mut new_ropes =
1438            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
1439        let mut old_fragments = self.fragments.cursor::<VersionedOffset, VersionedOffset>();
1440        let mut new_fragments =
1441            old_fragments.slice(&VersionedOffset::Offset(ranges[0].start), Bias::Left, &cx);
1442        new_ropes.push_tree(new_fragments.summary().text);
1443
1444        let mut fragment_start = old_fragments.sum_start().offset();
1445        for range in ranges {
1446            let fragment_end = old_fragments.sum_end(&cx).offset();
1447
1448            // If the current fragment ends before this range, then jump ahead to the first fragment
1449            // that extends past the start of this range, reusing any intervening fragments.
1450            if fragment_end < range.start {
1451                // If the current fragment has been partially consumed, then consume the rest of it
1452                // and advance to the next fragment before slicing.
1453                if fragment_start > old_fragments.sum_start().offset() {
1454                    if fragment_end > fragment_start {
1455                        let mut suffix = old_fragments.item().unwrap().clone();
1456                        suffix.len = fragment_end - fragment_start;
1457                        new_ropes.push_fragment(&suffix, suffix.visible);
1458                        new_fragments.push(suffix, &None);
1459                    }
1460                    old_fragments.next(&cx);
1461                }
1462
1463                let slice =
1464                    old_fragments.slice(&VersionedOffset::Offset(range.start), Bias::Left, &cx);
1465                new_ropes.push_tree(slice.summary().text);
1466                new_fragments.push_tree(slice, &None);
1467                fragment_start = old_fragments.sum_start().offset();
1468            }
1469
1470            // If we are at the end of a non-concurrent fragment, advance to the next one.
1471            let fragment_end = old_fragments.sum_end(&cx).offset();
1472            if fragment_end == range.start && fragment_end > fragment_start {
1473                let mut fragment = old_fragments.item().unwrap().clone();
1474                fragment.len = fragment_end - fragment_start;
1475                new_ropes.push_fragment(&fragment, fragment.visible);
1476                new_fragments.push(fragment, &None);
1477                old_fragments.next(&cx);
1478                fragment_start = old_fragments.sum_start().offset();
1479            }
1480
1481            // Skip over insertions that are concurrent to this edit, but have a lower lamport
1482            // timestamp.
1483            while let Some(fragment) = old_fragments.item() {
1484                if fragment_start == range.start
1485                    && fragment.timestamp.lamport() > timestamp.lamport()
1486                {
1487                    new_ropes.push_fragment(fragment, fragment.visible);
1488                    new_fragments.push(fragment.clone(), &None);
1489                    old_fragments.next(&cx);
1490                    debug_assert_eq!(fragment_start, range.start);
1491                } else {
1492                    break;
1493                }
1494            }
1495            debug_assert!(fragment_start <= range.start);
1496
1497            // Preserve any portion of the current fragment that precedes this range.
1498            if fragment_start < range.start {
1499                let mut prefix = old_fragments.item().unwrap().clone();
1500                prefix.len = range.start - fragment_start;
1501                fragment_start = range.start;
1502                new_ropes.push_fragment(&prefix, prefix.visible);
1503                new_fragments.push(prefix, &None);
1504            }
1505
1506            // Insert the new text before any existing fragments within the range.
1507            if let Some(new_text) = new_text {
1508                new_ropes.push_str(new_text);
1509                new_fragments.push(
1510                    Fragment {
1511                        timestamp,
1512                        len: new_text.len(),
1513                        deletions: Default::default(),
1514                        max_undos: Default::default(),
1515                        visible: true,
1516                    },
1517                    &None,
1518                );
1519            }
1520
1521            // Advance through every fragment that intersects this range, marking the intersecting
1522            // portions as deleted.
1523            while fragment_start < range.end {
1524                let fragment = old_fragments.item().unwrap();
1525                let fragment_end = old_fragments.sum_end(&cx).offset();
1526                let mut intersection = fragment.clone();
1527                let intersection_end = cmp::min(range.end, fragment_end);
1528                if fragment.was_visible(version, &self.undo_map) {
1529                    intersection.len = intersection_end - fragment_start;
1530                    intersection.deletions.insert(timestamp.local());
1531                    intersection.visible = false;
1532                }
1533                if intersection.len > 0 {
1534                    new_ropes.push_fragment(&intersection, fragment.visible);
1535                    new_fragments.push(intersection, &None);
1536                    fragment_start = intersection_end;
1537                }
1538                if fragment_end <= range.end {
1539                    old_fragments.next(&cx);
1540                }
1541            }
1542        }
1543
1544        // If the current fragment has been partially consumed, then consume the rest of it
1545        // and advance to the next fragment before slicing.
1546        if fragment_start > old_fragments.sum_start().offset() {
1547            let fragment_end = old_fragments.sum_end(&cx).offset();
1548            if fragment_end > fragment_start {
1549                let mut suffix = old_fragments.item().unwrap().clone();
1550                suffix.len = fragment_end - fragment_start;
1551                new_ropes.push_fragment(&suffix, suffix.visible);
1552                new_fragments.push(suffix, &None);
1553            }
1554            old_fragments.next(&cx);
1555        }
1556
1557        let suffix = old_fragments.suffix(&cx);
1558        new_ropes.push_tree(suffix.summary().text);
1559        new_fragments.push_tree(suffix, &None);
1560        let (visible_text, deleted_text) = new_ropes.finish();
1561        drop(old_fragments);
1562
1563        self.fragments = new_fragments;
1564        self.visible_text = visible_text;
1565        self.deleted_text = deleted_text;
1566        self.local_clock.observe(timestamp.local());
1567        self.lamport_clock.observe(timestamp.lamport());
1568    }
1569
1570    #[cfg(not(test))]
1571    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1572        if let Some(file) = &self.file {
1573            file.buffer_updated(self.remote_id, operation, cx.as_mut());
1574        }
1575    }
1576
1577    #[cfg(test)]
1578    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1579        self.operations.push(operation);
1580    }
1581
1582    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1583        self.selections
1584            .retain(|set_id, _| set_id.replica_id != replica_id);
1585        cx.notify();
1586    }
1587
1588    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
1589        let was_dirty = self.is_dirty();
1590        let old_version = self.version.clone();
1591
1592        if let Some(transaction) = self.history.pop_undo().cloned() {
1593            let selections = transaction.selections_before.clone();
1594            self.undo_or_redo(transaction, cx).unwrap();
1595            if let Some((set_id, selections)) = selections {
1596                let _ = self.update_selection_set(set_id, selections, cx);
1597            }
1598        }
1599
1600        cx.notify();
1601        if self.edits_since(old_version).next().is_some() {
1602            self.did_edit(was_dirty, cx);
1603            self.reparse(cx);
1604        }
1605    }
1606
1607    pub fn redo(&mut self, cx: &mut ModelContext<Self>) {
1608        let was_dirty = self.is_dirty();
1609        let old_version = self.version.clone();
1610
1611        if let Some(transaction) = self.history.pop_redo().cloned() {
1612            let selections = transaction.selections_after.clone();
1613            self.undo_or_redo(transaction, cx).unwrap();
1614            if let Some((set_id, selections)) = selections {
1615                let _ = self.update_selection_set(set_id, selections, cx);
1616            }
1617        }
1618
1619        cx.notify();
1620        if self.edits_since(old_version).next().is_some() {
1621            self.did_edit(was_dirty, cx);
1622            self.reparse(cx);
1623        }
1624    }
1625
1626    fn undo_or_redo(
1627        &mut self,
1628        transaction: Transaction,
1629        cx: &mut ModelContext<Self>,
1630    ) -> Result<()> {
1631        let mut counts = HashMap::default();
1632        for edit_id in transaction.edits {
1633            counts.insert(edit_id, self.undo_map.undo_count(edit_id) + 1);
1634        }
1635
1636        let undo = UndoOperation {
1637            id: self.local_clock.tick(),
1638            counts,
1639            ranges: transaction.ranges,
1640            version: transaction.start.clone(),
1641        };
1642        self.apply_undo(&undo)?;
1643        self.version.observe(undo.id);
1644
1645        let operation = Operation::Undo {
1646            undo,
1647            lamport_timestamp: self.lamport_clock.tick(),
1648        };
1649        self.send_operation(operation, cx);
1650
1651        Ok(())
1652    }
1653
1654    fn apply_undo(&mut self, undo: &UndoOperation) -> Result<()> {
1655        self.undo_map.insert(undo);
1656
1657        let mut cx = undo.version.clone();
1658        for edit_id in undo.counts.keys().copied() {
1659            cx.observe(edit_id);
1660        }
1661        let cx = Some(cx);
1662
1663        let mut old_fragments = self.fragments.cursor::<VersionedOffset, VersionedOffset>();
1664        let mut new_fragments = old_fragments.slice(
1665            &VersionedOffset::Offset(undo.ranges[0].start),
1666            Bias::Right,
1667            &cx,
1668        );
1669        let mut new_ropes =
1670            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
1671        new_ropes.push_tree(new_fragments.summary().text);
1672
1673        for range in &undo.ranges {
1674            let mut end_offset = old_fragments.sum_end(&cx).offset();
1675
1676            if end_offset < range.start {
1677                let preceding_fragments =
1678                    old_fragments.slice(&VersionedOffset::Offset(range.start), Bias::Right, &cx);
1679                new_ropes.push_tree(preceding_fragments.summary().text);
1680                new_fragments.push_tree(preceding_fragments, &None);
1681            }
1682
1683            while end_offset <= range.end {
1684                if let Some(fragment) = old_fragments.item() {
1685                    let mut fragment = fragment.clone();
1686                    let fragment_was_visible = fragment.visible;
1687
1688                    if fragment.was_visible(&undo.version, &self.undo_map)
1689                        || undo.counts.contains_key(&fragment.timestamp.local())
1690                    {
1691                        fragment.visible = fragment.is_visible(&self.undo_map);
1692                        fragment.max_undos.observe(undo.id);
1693                    }
1694                    new_ropes.push_fragment(&fragment, fragment_was_visible);
1695                    new_fragments.push(fragment, &None);
1696
1697                    old_fragments.next(&cx);
1698                    if end_offset == old_fragments.sum_end(&cx).offset() {
1699                        let unseen_fragments = old_fragments.slice(
1700                            &VersionedOffset::Offset(end_offset),
1701                            Bias::Right,
1702                            &cx,
1703                        );
1704                        new_ropes.push_tree(unseen_fragments.summary().text);
1705                        new_fragments.push_tree(unseen_fragments, &None);
1706                    }
1707                    end_offset = old_fragments.sum_end(&cx).offset();
1708                } else {
1709                    break;
1710                }
1711            }
1712        }
1713
1714        let suffix = old_fragments.suffix(&cx);
1715        new_ropes.push_tree(suffix.summary().text);
1716        new_fragments.push_tree(suffix, &None);
1717
1718        drop(old_fragments);
1719        let (visible_text, deleted_text) = new_ropes.finish();
1720        self.fragments = new_fragments;
1721        self.visible_text = visible_text;
1722        self.deleted_text = deleted_text;
1723        Ok(())
1724    }
1725
1726    fn flush_deferred_ops(&mut self) -> Result<()> {
1727        self.deferred_replicas.clear();
1728        let mut deferred_ops = Vec::new();
1729        for op in self.deferred_ops.drain().cursor().cloned() {
1730            if self.can_apply_op(&op) {
1731                self.apply_op(op)?;
1732            } else {
1733                self.deferred_replicas.insert(op.replica_id());
1734                deferred_ops.push(op);
1735            }
1736        }
1737        self.deferred_ops.insert(deferred_ops);
1738        Ok(())
1739    }
1740
1741    fn can_apply_op(&self, op: &Operation) -> bool {
1742        if self.deferred_replicas.contains(&op.replica_id()) {
1743            false
1744        } else {
1745            match op {
1746                Operation::Edit(edit) => self.version >= edit.version,
1747                Operation::Undo { undo, .. } => self.version >= undo.version,
1748                Operation::UpdateSelections { selections, .. } => {
1749                    if let Some(selections) = selections {
1750                        selections.iter().all(|selection| {
1751                            let contains_start = self.version >= selection.start.version;
1752                            let contains_end = self.version >= selection.end.version;
1753                            contains_start && contains_end
1754                        })
1755                    } else {
1756                        true
1757                    }
1758                }
1759                Operation::SetActiveSelections { set_id, .. } => {
1760                    set_id.map_or(true, |set_id| self.selections.contains_key(&set_id))
1761                }
1762                #[cfg(test)]
1763                Operation::Test(_) => true,
1764            }
1765        }
1766    }
1767
1768    fn apply_local_edit(
1769        &mut self,
1770        ranges: &[Range<usize>],
1771        new_text: Option<String>,
1772        timestamp: InsertionTimestamp,
1773    ) -> EditOperation {
1774        let mut edit = EditOperation {
1775            timestamp,
1776            version: self.version(),
1777            ranges: Vec::with_capacity(ranges.len()),
1778            new_text: None,
1779        };
1780
1781        let mut new_ropes =
1782            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
1783        let mut old_fragments = self.fragments.cursor::<usize, FragmentTextSummary>();
1784        let mut new_fragments = old_fragments.slice(&ranges[0].start, Bias::Right, &None);
1785        new_ropes.push_tree(new_fragments.summary().text);
1786
1787        let mut fragment_start = old_fragments.sum_start().visible;
1788        for range in ranges {
1789            let fragment_end = old_fragments.sum_end(&None).visible;
1790
1791            // If the current fragment ends before this range, then jump ahead to the first fragment
1792            // that extends past the start of this range, reusing any intervening fragments.
1793            if fragment_end < range.start {
1794                // If the current fragment has been partially consumed, then consume the rest of it
1795                // and advance to the next fragment before slicing.
1796                if fragment_start > old_fragments.sum_start().visible {
1797                    if fragment_end > fragment_start {
1798                        let mut suffix = old_fragments.item().unwrap().clone();
1799                        suffix.len = fragment_end - fragment_start;
1800                        new_ropes.push_fragment(&suffix, suffix.visible);
1801                        new_fragments.push(suffix, &None);
1802                    }
1803                    old_fragments.next(&None);
1804                }
1805
1806                let slice = old_fragments.slice(&range.start, Bias::Right, &None);
1807                new_ropes.push_tree(slice.summary().text);
1808                new_fragments.push_tree(slice, &None);
1809                fragment_start = old_fragments.sum_start().visible;
1810            }
1811
1812            let full_range_start = range.start + old_fragments.sum_start().deleted;
1813
1814            // Preserve any portion of the current fragment that precedes this range.
1815            if fragment_start < range.start {
1816                let mut prefix = old_fragments.item().unwrap().clone();
1817                prefix.len = range.start - fragment_start;
1818                new_ropes.push_fragment(&prefix, prefix.visible);
1819                new_fragments.push(prefix, &None);
1820                fragment_start = range.start;
1821            }
1822
1823            // Insert the new text before any existing fragments within the range.
1824            if let Some(new_text) = new_text.as_deref() {
1825                new_ropes.push_str(new_text);
1826                new_fragments.push(
1827                    Fragment {
1828                        timestamp,
1829                        len: new_text.len(),
1830                        deletions: Default::default(),
1831                        max_undos: Default::default(),
1832                        visible: true,
1833                    },
1834                    &None,
1835                );
1836            }
1837
1838            // Advance through every fragment that intersects this range, marking the intersecting
1839            // portions as deleted.
1840            while fragment_start < range.end {
1841                let fragment = old_fragments.item().unwrap();
1842                let fragment_end = old_fragments.sum_end(&None).visible;
1843                let mut intersection = fragment.clone();
1844                let intersection_end = cmp::min(range.end, fragment_end);
1845                if fragment.visible {
1846                    intersection.len = intersection_end - fragment_start;
1847                    intersection.deletions.insert(timestamp.local());
1848                    intersection.visible = false;
1849                }
1850                if intersection.len > 0 {
1851                    new_ropes.push_fragment(&intersection, fragment.visible);
1852                    new_fragments.push(intersection, &None);
1853                    fragment_start = intersection_end;
1854                }
1855                if fragment_end <= range.end {
1856                    old_fragments.next(&None);
1857                }
1858            }
1859
1860            let full_range_end = range.end + old_fragments.sum_start().deleted;
1861            edit.ranges.push(full_range_start..full_range_end);
1862        }
1863
1864        // If the current fragment has been partially consumed, then consume the rest of it
1865        // and advance to the next fragment before slicing.
1866        if fragment_start > old_fragments.sum_start().visible {
1867            let fragment_end = old_fragments.sum_end(&None).visible;
1868            if fragment_end > fragment_start {
1869                let mut suffix = old_fragments.item().unwrap().clone();
1870                suffix.len = fragment_end - fragment_start;
1871                new_ropes.push_fragment(&suffix, suffix.visible);
1872                new_fragments.push(suffix, &None);
1873            }
1874            old_fragments.next(&None);
1875        }
1876
1877        let suffix = old_fragments.suffix(&None);
1878        new_ropes.push_tree(suffix.summary().text);
1879        new_fragments.push_tree(suffix, &None);
1880        let (visible_text, deleted_text) = new_ropes.finish();
1881        drop(old_fragments);
1882
1883        self.fragments = new_fragments;
1884        self.visible_text = visible_text;
1885        self.deleted_text = deleted_text;
1886        edit.new_text = new_text;
1887        edit
1888    }
1889
1890    fn content<'a>(&'a self) -> Content<'a> {
1891        self.into()
1892    }
1893
1894    pub fn text_summary_for_range(&self, range: Range<usize>) -> TextSummary {
1895        self.content().text_summary_for_range(range)
1896    }
1897
1898    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1899        self.anchor_at(position, Bias::Left)
1900    }
1901
1902    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1903        self.anchor_at(position, Bias::Right)
1904    }
1905
1906    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1907        self.content().anchor_at(position, bias)
1908    }
1909
1910    pub fn point_for_offset(&self, offset: usize) -> Result<Point> {
1911        self.content().point_for_offset(offset)
1912    }
1913
1914    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1915        self.visible_text.clip_point(point, bias)
1916    }
1917
1918    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1919        self.visible_text.clip_offset(offset, bias)
1920    }
1921}
1922
1923impl Clone for Buffer {
1924    fn clone(&self) -> Self {
1925        Self {
1926            fragments: self.fragments.clone(),
1927            visible_text: self.visible_text.clone(),
1928            deleted_text: self.deleted_text.clone(),
1929            version: self.version.clone(),
1930            saved_version: self.saved_version.clone(),
1931            saved_mtime: self.saved_mtime,
1932            last_edit: self.last_edit.clone(),
1933            undo_map: self.undo_map.clone(),
1934            history: self.history.clone(),
1935            selections: self.selections.clone(),
1936            deferred_ops: self.deferred_ops.clone(),
1937            file: self.file.clone(),
1938            language: self.language.clone(),
1939            syntax_tree: Mutex::new(self.syntax_tree.lock().clone()),
1940            parsing_in_background: false,
1941            sync_parse_timeout: self.sync_parse_timeout,
1942            parse_count: self.parse_count,
1943            deferred_replicas: self.deferred_replicas.clone(),
1944            replica_id: self.replica_id,
1945            remote_id: self.remote_id.clone(),
1946            local_clock: self.local_clock.clone(),
1947            lamport_clock: self.lamport_clock.clone(),
1948
1949            #[cfg(test)]
1950            operations: self.operations.clone(),
1951        }
1952    }
1953}
1954
1955pub struct Snapshot {
1956    visible_text: Rope,
1957    fragments: SumTree<Fragment>,
1958    version: time::Global,
1959    tree: Option<Tree>,
1960    is_parsing: bool,
1961    language: Option<Arc<Language>>,
1962    query_cursor: QueryCursorHandle,
1963}
1964
1965impl Clone for Snapshot {
1966    fn clone(&self) -> Self {
1967        Self {
1968            visible_text: self.visible_text.clone(),
1969            fragments: self.fragments.clone(),
1970            version: self.version.clone(),
1971            tree: self.tree.clone(),
1972            is_parsing: self.is_parsing,
1973            language: self.language.clone(),
1974            query_cursor: QueryCursorHandle::new(),
1975        }
1976    }
1977}
1978
1979impl Snapshot {
1980    pub fn len(&self) -> usize {
1981        self.visible_text.len()
1982    }
1983
1984    pub fn line_len(&self, row: u32) -> u32 {
1985        self.content().line_len(row)
1986    }
1987
1988    pub fn text(&self) -> Rope {
1989        self.visible_text.clone()
1990    }
1991
1992    pub fn text_summary(&self) -> TextSummary {
1993        self.visible_text.summary()
1994    }
1995
1996    pub fn max_point(&self) -> Point {
1997        self.visible_text.max_point()
1998    }
1999
2000    pub fn text_for_range(&self, range: Range<usize>) -> Chunks {
2001        self.visible_text.chunks_in_range(range)
2002    }
2003
2004    pub fn highlighted_text_for_range(&mut self, range: Range<usize>) -> HighlightedChunks {
2005        let chunks = self.visible_text.chunks_in_range(range.clone());
2006        if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
2007            let captures = self.query_cursor.set_byte_range(range.clone()).captures(
2008                &language.highlight_query,
2009                tree.root_node(),
2010                TextProvider(&self.visible_text),
2011            );
2012
2013            HighlightedChunks {
2014                range,
2015                chunks,
2016                highlights: Some(Highlights {
2017                    captures,
2018                    next_capture: None,
2019                    stack: Default::default(),
2020                    highlight_map: language.highlight_map(),
2021                }),
2022            }
2023        } else {
2024            HighlightedChunks {
2025                range,
2026                chunks,
2027                highlights: None,
2028            }
2029        }
2030    }
2031
2032    pub fn text_summary_for_range<T>(&self, range: Range<T>) -> TextSummary
2033    where
2034        T: ToOffset,
2035    {
2036        let range = range.start.to_offset(self.content())..range.end.to_offset(self.content());
2037        self.content().text_summary_for_range(range)
2038    }
2039
2040    pub fn point_for_offset(&self, offset: usize) -> Result<Point> {
2041        self.content().point_for_offset(offset)
2042    }
2043
2044    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
2045        self.visible_text.clip_offset(offset, bias)
2046    }
2047
2048    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
2049        self.visible_text.clip_point(point, bias)
2050    }
2051
2052    pub fn to_offset(&self, point: Point) -> usize {
2053        self.visible_text.to_offset(point)
2054    }
2055
2056    pub fn to_point(&self, offset: usize) -> Point {
2057        self.visible_text.to_point(offset)
2058    }
2059
2060    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2061        self.content().anchor_at(position, Bias::Left)
2062    }
2063
2064    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2065        self.content().anchor_at(position, Bias::Right)
2066    }
2067
2068    fn content(&self) -> Content {
2069        self.into()
2070    }
2071}
2072
2073pub struct Content<'a> {
2074    visible_text: &'a Rope,
2075    fragments: &'a SumTree<Fragment>,
2076    version: &'a time::Global,
2077}
2078
2079impl<'a> From<&'a Snapshot> for Content<'a> {
2080    fn from(snapshot: &'a Snapshot) -> Self {
2081        Self {
2082            visible_text: &snapshot.visible_text,
2083            fragments: &snapshot.fragments,
2084            version: &snapshot.version,
2085        }
2086    }
2087}
2088
2089impl<'a> From<&'a Buffer> for Content<'a> {
2090    fn from(buffer: &'a Buffer) -> Self {
2091        Self {
2092            visible_text: &buffer.visible_text,
2093            fragments: &buffer.fragments,
2094            version: &buffer.version,
2095        }
2096    }
2097}
2098
2099impl<'a> From<&'a mut Buffer> for Content<'a> {
2100    fn from(buffer: &'a mut Buffer) -> Self {
2101        Self {
2102            visible_text: &buffer.visible_text,
2103            fragments: &buffer.fragments,
2104            version: &buffer.version,
2105        }
2106    }
2107}
2108
2109impl<'a> From<&'a Content<'a>> for Content<'a> {
2110    fn from(content: &'a Content) -> Self {
2111        Self {
2112            visible_text: &content.visible_text,
2113            fragments: &content.fragments,
2114            version: &content.version,
2115        }
2116    }
2117}
2118
2119impl<'a> Content<'a> {
2120    fn max_point(&self) -> Point {
2121        self.visible_text.max_point()
2122    }
2123
2124    fn len(&self) -> usize {
2125        self.fragments.extent::<usize>(&None)
2126    }
2127
2128    fn line_len(&self, row: u32) -> u32 {
2129        let row_start_offset = Point::new(row, 0).to_offset(self);
2130        let row_end_offset = if row >= self.max_point().row {
2131            self.len()
2132        } else {
2133            Point::new(row + 1, 0).to_offset(self) - 1
2134        };
2135        (row_end_offset - row_start_offset) as u32
2136    }
2137
2138    fn summary_for_anchor(&self, anchor: &Anchor) -> TextSummary {
2139        let cx = Some(anchor.version.clone());
2140        let mut cursor = self.fragments.cursor::<VersionedOffset, usize>();
2141        cursor.seek(&VersionedOffset::Offset(anchor.offset), anchor.bias, &cx);
2142        let overshoot = if cursor.item().map_or(false, |fragment| fragment.visible) {
2143            anchor.offset - cursor.seek_start().offset()
2144        } else {
2145            0
2146        };
2147        self.text_summary_for_range(0..*cursor.sum_start() + overshoot)
2148    }
2149
2150    fn text_summary_for_range(&self, range: Range<usize>) -> TextSummary {
2151        self.visible_text.cursor(range.start).summary(range.end)
2152    }
2153
2154    fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
2155        let offset = position.to_offset(self);
2156        let max_offset = self.len();
2157        assert!(offset <= max_offset, "offset is out of range");
2158        let mut cursor = self.fragments.cursor::<usize, FragmentTextSummary>();
2159        cursor.seek(&offset, bias, &None);
2160        Anchor {
2161            offset: offset + cursor.sum_start().deleted,
2162            bias,
2163            version: self.version.clone(),
2164        }
2165    }
2166
2167    fn full_offset_for_anchor(&self, anchor: &Anchor) -> usize {
2168        let cx = Some(anchor.version.clone());
2169        let mut cursor = self
2170            .fragments
2171            .cursor::<VersionedOffset, FragmentTextSummary>();
2172        cursor.seek(&VersionedOffset::Offset(anchor.offset), anchor.bias, &cx);
2173        let overshoot = if cursor.item().is_some() {
2174            anchor.offset - cursor.seek_start().offset()
2175        } else {
2176            0
2177        };
2178        let summary = cursor.sum_start();
2179        summary.visible + summary.deleted + overshoot
2180    }
2181
2182    fn point_for_offset(&self, offset: usize) -> Result<Point> {
2183        if offset <= self.len() {
2184            Ok(self.text_summary_for_range(0..offset).lines)
2185        } else {
2186            Err(anyhow!("offset out of bounds"))
2187        }
2188    }
2189}
2190
2191struct RopeBuilder<'a> {
2192    old_visible_cursor: rope::Cursor<'a>,
2193    old_deleted_cursor: rope::Cursor<'a>,
2194    new_visible: Rope,
2195    new_deleted: Rope,
2196}
2197
2198impl<'a> RopeBuilder<'a> {
2199    fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
2200        Self {
2201            old_visible_cursor,
2202            old_deleted_cursor,
2203            new_visible: Rope::new(),
2204            new_deleted: Rope::new(),
2205        }
2206    }
2207
2208    fn push_tree(&mut self, len: FragmentTextSummary) {
2209        self.push(len.visible, true, true);
2210        self.push(len.deleted, false, false);
2211    }
2212
2213    fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
2214        debug_assert!(fragment.len > 0);
2215        self.push(fragment.len, was_visible, fragment.visible)
2216    }
2217
2218    fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
2219        let text = if was_visible {
2220            self.old_visible_cursor
2221                .slice(self.old_visible_cursor.offset() + len)
2222        } else {
2223            self.old_deleted_cursor
2224                .slice(self.old_deleted_cursor.offset() + len)
2225        };
2226        if is_visible {
2227            self.new_visible.append(text);
2228        } else {
2229            self.new_deleted.append(text);
2230        }
2231    }
2232
2233    fn push_str(&mut self, text: &str) {
2234        self.new_visible.push(text);
2235    }
2236
2237    fn finish(mut self) -> (Rope, Rope) {
2238        self.new_visible.append(self.old_visible_cursor.suffix());
2239        self.new_deleted.append(self.old_deleted_cursor.suffix());
2240        (self.new_visible, self.new_deleted)
2241    }
2242}
2243
2244#[derive(Clone, Debug, Eq, PartialEq)]
2245pub enum Event {
2246    Edited,
2247    Dirtied,
2248    Saved,
2249    FileHandleChanged,
2250    Reloaded,
2251    Reparsed,
2252}
2253
2254impl Entity for Buffer {
2255    type Event = Event;
2256
2257    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
2258        if let Some(file) = self.file.as_ref() {
2259            file.buffer_removed(self.remote_id, cx);
2260        }
2261    }
2262}
2263
2264impl<'a, F: Fn(&FragmentSummary) -> bool> Iterator for Edits<'a, F> {
2265    type Item = Edit;
2266
2267    fn next(&mut self) -> Option<Self::Item> {
2268        let mut change: Option<Edit> = None;
2269        let cursor = self.cursor.as_mut()?;
2270
2271        while let Some(fragment) = cursor.item() {
2272            let bytes = cursor.start().visible - self.new_offset;
2273            let lines = self.visible_text.to_point(cursor.start().visible) - self.new_point;
2274            self.old_offset += bytes;
2275            self.old_point += &lines;
2276            self.new_offset += bytes;
2277            self.new_point += &lines;
2278
2279            if !fragment.was_visible(&self.since, &self.undos) && fragment.visible {
2280                let fragment_lines =
2281                    self.visible_text.to_point(self.new_offset + fragment.len) - self.new_point;
2282                if let Some(ref mut change) = change {
2283                    if change.new_bytes.end == self.new_offset {
2284                        change.new_bytes.end += fragment.len;
2285                    } else {
2286                        break;
2287                    }
2288                } else {
2289                    change = Some(Edit {
2290                        old_bytes: self.old_offset..self.old_offset,
2291                        new_bytes: self.new_offset..self.new_offset + fragment.len,
2292                        old_lines: self.old_point..self.old_point,
2293                    });
2294                }
2295
2296                self.new_offset += fragment.len;
2297                self.new_point += &fragment_lines;
2298            } else if fragment.was_visible(&self.since, &self.undos) && !fragment.visible {
2299                let deleted_start = cursor.start().deleted;
2300                let fragment_lines = self.deleted_text.to_point(deleted_start + fragment.len)
2301                    - self.deleted_text.to_point(deleted_start);
2302                if let Some(ref mut change) = change {
2303                    if change.new_bytes.end == self.new_offset {
2304                        change.old_bytes.end += fragment.len;
2305                        change.old_lines.end += &fragment_lines;
2306                    } else {
2307                        break;
2308                    }
2309                } else {
2310                    change = Some(Edit {
2311                        old_bytes: self.old_offset..self.old_offset + fragment.len,
2312                        new_bytes: self.new_offset..self.new_offset,
2313                        old_lines: self.old_point..self.old_point + &fragment_lines,
2314                    });
2315                }
2316
2317                self.old_offset += fragment.len;
2318                self.old_point += &fragment_lines;
2319            }
2320
2321            cursor.next(&None);
2322        }
2323
2324        change
2325    }
2326}
2327
2328struct ByteChunks<'a>(rope::Chunks<'a>);
2329
2330impl<'a> Iterator for ByteChunks<'a> {
2331    type Item = &'a [u8];
2332
2333    fn next(&mut self) -> Option<Self::Item> {
2334        self.0.next().map(str::as_bytes)
2335    }
2336}
2337
2338struct TextProvider<'a>(&'a Rope);
2339
2340impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
2341    type I = ByteChunks<'a>;
2342
2343    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
2344        ByteChunks(self.0.chunks_in_range(node.byte_range()))
2345    }
2346}
2347
2348struct Highlights<'a> {
2349    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
2350    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
2351    stack: Vec<(usize, HighlightId)>,
2352    highlight_map: HighlightMap,
2353}
2354
2355pub struct HighlightedChunks<'a> {
2356    range: Range<usize>,
2357    chunks: Chunks<'a>,
2358    highlights: Option<Highlights<'a>>,
2359}
2360
2361impl<'a> HighlightedChunks<'a> {
2362    pub fn seek(&mut self, offset: usize) {
2363        self.range.start = offset;
2364        self.chunks.seek(self.range.start);
2365        if let Some(highlights) = self.highlights.as_mut() {
2366            highlights
2367                .stack
2368                .retain(|(end_offset, _)| *end_offset > offset);
2369            if let Some((mat, capture_ix)) = &highlights.next_capture {
2370                let capture = mat.captures[*capture_ix as usize];
2371                if offset >= capture.node.start_byte() {
2372                    let next_capture_end = capture.node.end_byte();
2373                    if offset < next_capture_end {
2374                        highlights.stack.push((
2375                            next_capture_end,
2376                            highlights.highlight_map.get(capture.index),
2377                        ));
2378                    }
2379                    highlights.next_capture.take();
2380                }
2381            }
2382            highlights.captures.set_byte_range(self.range.clone());
2383        }
2384    }
2385
2386    pub fn offset(&self) -> usize {
2387        self.range.start
2388    }
2389}
2390
2391impl<'a> Iterator for HighlightedChunks<'a> {
2392    type Item = (&'a str, HighlightId);
2393
2394    fn next(&mut self) -> Option<Self::Item> {
2395        let mut next_capture_start = usize::MAX;
2396
2397        if let Some(highlights) = self.highlights.as_mut() {
2398            while let Some((parent_capture_end, _)) = highlights.stack.last() {
2399                if *parent_capture_end <= self.range.start {
2400                    highlights.stack.pop();
2401                } else {
2402                    break;
2403                }
2404            }
2405
2406            if highlights.next_capture.is_none() {
2407                highlights.next_capture = highlights.captures.next();
2408            }
2409
2410            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2411                let capture = mat.captures[*capture_ix as usize];
2412                if self.range.start < capture.node.start_byte() {
2413                    next_capture_start = capture.node.start_byte();
2414                    break;
2415                } else {
2416                    let style_id = highlights.highlight_map.get(capture.index);
2417                    highlights.stack.push((capture.node.end_byte(), style_id));
2418                    highlights.next_capture = highlights.captures.next();
2419                }
2420            }
2421        }
2422
2423        if let Some(chunk) = self.chunks.peek() {
2424            let chunk_start = self.range.start;
2425            let mut chunk_end = (self.chunks.offset() + chunk.len()).min(next_capture_start);
2426            let mut style_id = HighlightId::default();
2427            if let Some((parent_capture_end, parent_style_id)) =
2428                self.highlights.as_ref().and_then(|h| h.stack.last())
2429            {
2430                chunk_end = chunk_end.min(*parent_capture_end);
2431                style_id = *parent_style_id;
2432            }
2433
2434            let slice =
2435                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2436            self.range.start = chunk_end;
2437            if self.range.start == self.chunks.offset() + chunk.len() {
2438                self.chunks.next().unwrap();
2439            }
2440
2441            Some((slice, style_id))
2442        } else {
2443            None
2444        }
2445    }
2446}
2447
2448impl Fragment {
2449    fn is_visible(&self, undos: &UndoMap) -> bool {
2450        !undos.is_undone(self.timestamp.local())
2451            && self.deletions.iter().all(|d| undos.is_undone(*d))
2452    }
2453
2454    fn was_visible(&self, version: &time::Global, undos: &UndoMap) -> bool {
2455        (version.observed(self.timestamp.local())
2456            && !undos.was_undone(self.timestamp.local(), version))
2457            && self
2458                .deletions
2459                .iter()
2460                .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
2461    }
2462}
2463
2464impl sum_tree::Item for Fragment {
2465    type Summary = FragmentSummary;
2466
2467    fn summary(&self) -> Self::Summary {
2468        let mut max_version = time::Global::new();
2469        max_version.observe(self.timestamp.local());
2470        for deletion in &self.deletions {
2471            max_version.observe(*deletion);
2472        }
2473        max_version.join(&self.max_undos);
2474
2475        let mut min_insertion_version = time::Global::new();
2476        min_insertion_version.observe(self.timestamp.local());
2477        let max_insertion_version = min_insertion_version.clone();
2478        if self.visible {
2479            FragmentSummary {
2480                text: FragmentTextSummary {
2481                    visible: self.len,
2482                    deleted: 0,
2483                },
2484                max_version,
2485                min_insertion_version,
2486                max_insertion_version,
2487            }
2488        } else {
2489            FragmentSummary {
2490                text: FragmentTextSummary {
2491                    visible: 0,
2492                    deleted: self.len,
2493                },
2494                max_version,
2495                min_insertion_version,
2496                max_insertion_version,
2497            }
2498        }
2499    }
2500}
2501
2502impl sum_tree::Summary for FragmentSummary {
2503    type Context = Option<time::Global>;
2504
2505    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2506        self.text.visible += &other.text.visible;
2507        self.text.deleted += &other.text.deleted;
2508        self.max_version.join(&other.max_version);
2509        self.min_insertion_version
2510            .meet(&other.min_insertion_version);
2511        self.max_insertion_version
2512            .join(&other.max_insertion_version);
2513    }
2514}
2515
2516impl Default for FragmentSummary {
2517    fn default() -> Self {
2518        FragmentSummary {
2519            text: FragmentTextSummary::default(),
2520            max_version: time::Global::new(),
2521            min_insertion_version: time::Global::new(),
2522            max_insertion_version: time::Global::new(),
2523        }
2524    }
2525}
2526
2527impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2528    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<time::Global>) {
2529        *self += summary.text.visible;
2530    }
2531}
2532
2533#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2534enum VersionedOffset {
2535    Offset(usize),
2536    InvalidVersion,
2537}
2538
2539impl VersionedOffset {
2540    fn offset(&self) -> usize {
2541        if let Self::Offset(offset) = self {
2542            *offset
2543        } else {
2544            panic!("invalid version")
2545        }
2546    }
2547}
2548
2549impl Default for VersionedOffset {
2550    fn default() -> Self {
2551        Self::Offset(0)
2552    }
2553}
2554
2555impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedOffset {
2556    fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<time::Global>) {
2557        if let Self::Offset(offset) = self {
2558            let version = cx.as_ref().unwrap();
2559            if *version >= summary.max_insertion_version {
2560                *offset += summary.text.visible + summary.text.deleted;
2561            } else if !summary
2562                .min_insertion_version
2563                .iter()
2564                .all(|t| !version.observed(*t))
2565            {
2566                *self = Self::InvalidVersion;
2567            }
2568        }
2569    }
2570}
2571
2572impl<'a> sum_tree::SeekDimension<'a, FragmentSummary> for VersionedOffset {
2573    fn cmp(&self, other: &Self, _: &Option<time::Global>) -> cmp::Ordering {
2574        match (self, other) {
2575            (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2576            (Self::Offset(_), Self::InvalidVersion) => cmp::Ordering::Less,
2577            (Self::InvalidVersion, _) => unreachable!(),
2578        }
2579    }
2580}
2581
2582impl Operation {
2583    fn replica_id(&self) -> ReplicaId {
2584        self.lamport_timestamp().replica_id
2585    }
2586
2587    fn lamport_timestamp(&self) -> time::Lamport {
2588        match self {
2589            Operation::Edit(edit) => edit.timestamp.lamport(),
2590            Operation::Undo {
2591                lamport_timestamp, ..
2592            } => *lamport_timestamp,
2593            Operation::UpdateSelections {
2594                lamport_timestamp, ..
2595            } => *lamport_timestamp,
2596            Operation::SetActiveSelections {
2597                lamport_timestamp, ..
2598            } => *lamport_timestamp,
2599            #[cfg(test)]
2600            Operation::Test(lamport_timestamp) => *lamport_timestamp,
2601        }
2602    }
2603
2604    pub fn is_edit(&self) -> bool {
2605        match self {
2606            Operation::Edit { .. } => true,
2607            _ => false,
2608        }
2609    }
2610}
2611
2612impl<'a> Into<proto::Operation> for &'a Operation {
2613    fn into(self) -> proto::Operation {
2614        proto::Operation {
2615            variant: Some(match self {
2616                Operation::Edit(edit) => proto::operation::Variant::Edit(edit.into()),
2617                Operation::Undo {
2618                    undo,
2619                    lamport_timestamp,
2620                } => proto::operation::Variant::Undo(proto::operation::Undo {
2621                    replica_id: undo.id.replica_id as u32,
2622                    local_timestamp: undo.id.value,
2623                    lamport_timestamp: lamport_timestamp.value,
2624                    ranges: undo
2625                        .ranges
2626                        .iter()
2627                        .map(|r| proto::Range {
2628                            start: r.start as u64,
2629                            end: r.end as u64,
2630                        })
2631                        .collect(),
2632                    counts: undo
2633                        .counts
2634                        .iter()
2635                        .map(|(edit_id, count)| proto::operation::UndoCount {
2636                            replica_id: edit_id.replica_id as u32,
2637                            local_timestamp: edit_id.value,
2638                            count: *count,
2639                        })
2640                        .collect(),
2641                    version: From::from(&undo.version),
2642                }),
2643                Operation::UpdateSelections {
2644                    set_id,
2645                    selections,
2646                    lamport_timestamp,
2647                } => proto::operation::Variant::UpdateSelections(
2648                    proto::operation::UpdateSelections {
2649                        replica_id: set_id.replica_id as u32,
2650                        local_timestamp: set_id.value,
2651                        lamport_timestamp: lamport_timestamp.value,
2652                        set: selections.as_ref().map(|selections| proto::SelectionSet {
2653                            selections: selections.iter().map(Into::into).collect(),
2654                        }),
2655                    },
2656                ),
2657                Operation::SetActiveSelections {
2658                    set_id,
2659                    lamport_timestamp,
2660                } => proto::operation::Variant::SetActiveSelections(
2661                    proto::operation::SetActiveSelections {
2662                        replica_id: lamport_timestamp.replica_id as u32,
2663                        local_timestamp: set_id.map(|set_id| set_id.value),
2664                        lamport_timestamp: lamport_timestamp.value,
2665                    },
2666                ),
2667                #[cfg(test)]
2668                Operation::Test(_) => unimplemented!(),
2669            }),
2670        }
2671    }
2672}
2673
2674impl<'a> Into<proto::operation::Edit> for &'a EditOperation {
2675    fn into(self) -> proto::operation::Edit {
2676        let ranges = self
2677            .ranges
2678            .iter()
2679            .map(|range| proto::Range {
2680                start: range.start as u64,
2681                end: range.end as u64,
2682            })
2683            .collect();
2684        proto::operation::Edit {
2685            replica_id: self.timestamp.replica_id as u32,
2686            local_timestamp: self.timestamp.local,
2687            lamport_timestamp: self.timestamp.lamport,
2688            version: From::from(&self.version),
2689            ranges,
2690            new_text: self.new_text.clone(),
2691        }
2692    }
2693}
2694
2695impl<'a> Into<proto::Anchor> for &'a Anchor {
2696    fn into(self) -> proto::Anchor {
2697        proto::Anchor {
2698            version: (&self.version).into(),
2699            offset: self.offset as u64,
2700            bias: match self.bias {
2701                Bias::Left => proto::anchor::Bias::Left as i32,
2702                Bias::Right => proto::anchor::Bias::Right as i32,
2703            },
2704        }
2705    }
2706}
2707
2708impl<'a> Into<proto::Selection> for &'a Selection {
2709    fn into(self) -> proto::Selection {
2710        proto::Selection {
2711            id: self.id as u64,
2712            start: Some((&self.start).into()),
2713            end: Some((&self.end).into()),
2714            reversed: self.reversed,
2715        }
2716    }
2717}
2718
2719impl TryFrom<proto::Operation> for Operation {
2720    type Error = anyhow::Error;
2721
2722    fn try_from(message: proto::Operation) -> Result<Self, Self::Error> {
2723        Ok(
2724            match message
2725                .variant
2726                .ok_or_else(|| anyhow!("missing operation variant"))?
2727            {
2728                proto::operation::Variant::Edit(edit) => Operation::Edit(edit.into()),
2729                proto::operation::Variant::Undo(undo) => Operation::Undo {
2730                    lamport_timestamp: time::Lamport {
2731                        replica_id: undo.replica_id as ReplicaId,
2732                        value: undo.lamport_timestamp,
2733                    },
2734                    undo: UndoOperation {
2735                        id: time::Local {
2736                            replica_id: undo.replica_id as ReplicaId,
2737                            value: undo.local_timestamp,
2738                        },
2739                        counts: undo
2740                            .counts
2741                            .into_iter()
2742                            .map(|c| {
2743                                (
2744                                    time::Local {
2745                                        replica_id: c.replica_id as ReplicaId,
2746                                        value: c.local_timestamp,
2747                                    },
2748                                    c.count,
2749                                )
2750                            })
2751                            .collect(),
2752                        ranges: undo
2753                            .ranges
2754                            .into_iter()
2755                            .map(|r| r.start as usize..r.end as usize)
2756                            .collect(),
2757                        version: undo.version.into(),
2758                    },
2759                },
2760                proto::operation::Variant::UpdateSelections(message) => {
2761                    let selections: Option<Vec<Selection>> = if let Some(set) = message.set {
2762                        Some(
2763                            set.selections
2764                                .into_iter()
2765                                .map(TryFrom::try_from)
2766                                .collect::<Result<_, _>>()?,
2767                        )
2768                    } else {
2769                        None
2770                    };
2771                    Operation::UpdateSelections {
2772                        set_id: time::Lamport {
2773                            replica_id: message.replica_id as ReplicaId,
2774                            value: message.local_timestamp,
2775                        },
2776                        lamport_timestamp: time::Lamport {
2777                            replica_id: message.replica_id as ReplicaId,
2778                            value: message.lamport_timestamp,
2779                        },
2780                        selections: selections.map(Arc::from),
2781                    }
2782                }
2783                proto::operation::Variant::SetActiveSelections(message) => {
2784                    Operation::SetActiveSelections {
2785                        set_id: message.local_timestamp.map(|value| time::Lamport {
2786                            replica_id: message.replica_id as ReplicaId,
2787                            value,
2788                        }),
2789                        lamport_timestamp: time::Lamport {
2790                            replica_id: message.replica_id as ReplicaId,
2791                            value: message.lamport_timestamp,
2792                        },
2793                    }
2794                }
2795            },
2796        )
2797    }
2798}
2799
2800impl From<proto::operation::Edit> for EditOperation {
2801    fn from(edit: proto::operation::Edit) -> Self {
2802        let ranges = edit
2803            .ranges
2804            .into_iter()
2805            .map(|range| range.start as usize..range.end as usize)
2806            .collect();
2807        EditOperation {
2808            timestamp: InsertionTimestamp {
2809                replica_id: edit.replica_id as ReplicaId,
2810                local: edit.local_timestamp,
2811                lamport: edit.lamport_timestamp,
2812            },
2813            version: edit.version.into(),
2814            ranges,
2815            new_text: edit.new_text,
2816        }
2817    }
2818}
2819
2820impl TryFrom<proto::Anchor> for Anchor {
2821    type Error = anyhow::Error;
2822
2823    fn try_from(message: proto::Anchor) -> Result<Self, Self::Error> {
2824        let mut version = time::Global::new();
2825        for entry in message.version {
2826            version.observe(time::Local {
2827                replica_id: entry.replica_id as ReplicaId,
2828                value: entry.timestamp,
2829            });
2830        }
2831
2832        Ok(Self {
2833            offset: message.offset as usize,
2834            bias: if message.bias == proto::anchor::Bias::Left as i32 {
2835                Bias::Left
2836            } else if message.bias == proto::anchor::Bias::Right as i32 {
2837                Bias::Right
2838            } else {
2839                Err(anyhow!("invalid anchor bias {}", message.bias))?
2840            },
2841            version,
2842        })
2843    }
2844}
2845
2846impl TryFrom<proto::Selection> for Selection {
2847    type Error = anyhow::Error;
2848
2849    fn try_from(selection: proto::Selection) -> Result<Self, Self::Error> {
2850        Ok(Selection {
2851            id: selection.id as usize,
2852            start: selection
2853                .start
2854                .ok_or_else(|| anyhow!("missing selection start"))?
2855                .try_into()?,
2856            end: selection
2857                .end
2858                .ok_or_else(|| anyhow!("missing selection end"))?
2859                .try_into()?,
2860            reversed: selection.reversed,
2861            goal: SelectionGoal::None,
2862        })
2863    }
2864}
2865
2866pub trait ToOffset {
2867    fn to_offset<'a>(&self, content: impl Into<Content<'a>>) -> usize;
2868}
2869
2870impl ToOffset for Point {
2871    fn to_offset<'a>(&self, content: impl Into<Content<'a>>) -> usize {
2872        content.into().visible_text.to_offset(*self)
2873    }
2874}
2875
2876impl ToOffset for usize {
2877    fn to_offset<'a>(&self, _: impl Into<Content<'a>>) -> usize {
2878        *self
2879    }
2880}
2881
2882impl ToOffset for Anchor {
2883    fn to_offset<'a>(&self, content: impl Into<Content<'a>>) -> usize {
2884        content.into().summary_for_anchor(self).bytes
2885    }
2886}
2887
2888impl<'a> ToOffset for &'a Anchor {
2889    fn to_offset<'b>(&self, content: impl Into<Content<'b>>) -> usize {
2890        content.into().summary_for_anchor(self).bytes
2891    }
2892}
2893
2894pub trait ToPoint {
2895    fn to_point<'a>(&self, content: impl Into<Content<'a>>) -> Point;
2896}
2897
2898impl ToPoint for Anchor {
2899    fn to_point<'a>(&self, content: impl Into<Content<'a>>) -> Point {
2900        content.into().summary_for_anchor(self).lines
2901    }
2902}
2903
2904impl ToPoint for usize {
2905    fn to_point<'a>(&self, content: impl Into<Content<'a>>) -> Point {
2906        content.into().visible_text.to_point(*self)
2907    }
2908}
2909
2910#[cfg(test)]
2911mod tests {
2912    use super::*;
2913    use crate::{
2914        fs::RealFs,
2915        language::LanguageRegistry,
2916        test::temp_tree,
2917        util::RandomCharIter,
2918        worktree::{Worktree, WorktreeHandle as _},
2919    };
2920    use gpui::ModelHandle;
2921    use rand::prelude::*;
2922    use serde_json::json;
2923    use std::{
2924        cell::RefCell,
2925        cmp::Ordering,
2926        env, fs, mem,
2927        path::Path,
2928        rc::Rc,
2929        sync::atomic::{self, AtomicUsize},
2930    };
2931
2932    #[gpui::test]
2933    fn test_edit(cx: &mut gpui::MutableAppContext) {
2934        cx.add_model(|cx| {
2935            let mut buffer = Buffer::new(0, "abc", cx);
2936            assert_eq!(buffer.text(), "abc");
2937            buffer.edit(vec![3..3], "def", cx);
2938            assert_eq!(buffer.text(), "abcdef");
2939            buffer.edit(vec![0..0], "ghi", cx);
2940            assert_eq!(buffer.text(), "ghiabcdef");
2941            buffer.edit(vec![5..5], "jkl", cx);
2942            assert_eq!(buffer.text(), "ghiabjklcdef");
2943            buffer.edit(vec![6..7], "", cx);
2944            assert_eq!(buffer.text(), "ghiabjlcdef");
2945            buffer.edit(vec![4..9], "mno", cx);
2946            assert_eq!(buffer.text(), "ghiamnoef");
2947            buffer
2948        });
2949    }
2950
2951    #[gpui::test]
2952    fn test_edit_events(cx: &mut gpui::MutableAppContext) {
2953        let mut now = Instant::now();
2954        let buffer_1_events = Rc::new(RefCell::new(Vec::new()));
2955        let buffer_2_events = Rc::new(RefCell::new(Vec::new()));
2956
2957        let buffer1 = cx.add_model(|cx| Buffer::new(0, "abcdef", cx));
2958        let buffer2 = cx.add_model(|cx| Buffer::new(1, "abcdef", cx));
2959        let buffer_ops = buffer1.update(cx, |buffer, cx| {
2960            let buffer_1_events = buffer_1_events.clone();
2961            cx.subscribe(&buffer1, move |_, _, event, _| {
2962                buffer_1_events.borrow_mut().push(event.clone())
2963            })
2964            .detach();
2965            let buffer_2_events = buffer_2_events.clone();
2966            cx.subscribe(&buffer2, move |_, _, event, _| {
2967                buffer_2_events.borrow_mut().push(event.clone())
2968            })
2969            .detach();
2970
2971            // An edit emits an edited event, followed by a dirtied event,
2972            // since the buffer was previously in a clean state.
2973            buffer.edit(Some(2..4), "XYZ", cx);
2974
2975            // An empty transaction does not emit any events.
2976            buffer.start_transaction(None).unwrap();
2977            buffer.end_transaction(None, cx).unwrap();
2978
2979            // A transaction containing two edits emits one edited event.
2980            now += Duration::from_secs(1);
2981            buffer.start_transaction_at(None, now).unwrap();
2982            buffer.edit(Some(5..5), "u", cx);
2983            buffer.edit(Some(6..6), "w", cx);
2984            buffer.end_transaction_at(None, now, cx).unwrap();
2985
2986            // Undoing a transaction emits one edited event.
2987            buffer.undo(cx);
2988
2989            buffer.operations.clone()
2990        });
2991
2992        // Incorporating a set of remote ops emits a single edited event,
2993        // followed by a dirtied event.
2994        buffer2.update(cx, |buffer, cx| {
2995            buffer.apply_ops(buffer_ops, cx).unwrap();
2996        });
2997
2998        let buffer_1_events = buffer_1_events.borrow();
2999        assert_eq!(
3000            *buffer_1_events,
3001            vec![Event::Edited, Event::Dirtied, Event::Edited, Event::Edited]
3002        );
3003
3004        let buffer_2_events = buffer_2_events.borrow();
3005        assert_eq!(*buffer_2_events, vec![Event::Edited, Event::Dirtied]);
3006    }
3007
3008    #[gpui::test(iterations = 100)]
3009    fn test_random_edits(cx: &mut gpui::MutableAppContext, mut rng: StdRng) {
3010        let operations = env::var("OPERATIONS")
3011            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3012            .unwrap_or(10);
3013
3014        let reference_string_len = rng.gen_range(0..3);
3015        let mut reference_string = RandomCharIter::new(&mut rng)
3016            .take(reference_string_len)
3017            .collect::<String>();
3018        cx.add_model(|cx| {
3019            let mut buffer = Buffer::new(0, reference_string.as_str(), cx);
3020            buffer.history.group_interval = Duration::from_millis(rng.gen_range(0..=200));
3021            let mut buffer_versions = Vec::new();
3022            log::info!(
3023                "buffer text {:?}, version: {:?}",
3024                buffer.text(),
3025                buffer.version()
3026            );
3027
3028            for _i in 0..operations {
3029                let (old_ranges, new_text) = buffer.randomly_mutate(&mut rng, cx);
3030                for old_range in old_ranges.iter().rev() {
3031                    reference_string.replace_range(old_range.clone(), &new_text);
3032                }
3033                assert_eq!(buffer.text(), reference_string);
3034                log::info!(
3035                    "buffer text {:?}, version: {:?}",
3036                    buffer.text(),
3037                    buffer.version()
3038                );
3039
3040                if rng.gen_bool(0.25) {
3041                    buffer.randomly_undo_redo(&mut rng, cx);
3042                    reference_string = buffer.text();
3043                    log::info!(
3044                        "buffer text {:?}, version: {:?}",
3045                        buffer.text(),
3046                        buffer.version()
3047                    );
3048                }
3049
3050                let range = buffer.random_byte_range(0, &mut rng);
3051                assert_eq!(
3052                    buffer.text_summary_for_range(range.clone()),
3053                    TextSummary::from(&reference_string[range])
3054                );
3055
3056                if rng.gen_bool(0.3) {
3057                    buffer_versions.push(buffer.clone());
3058                }
3059            }
3060
3061            for mut old_buffer in buffer_versions {
3062                let edits = buffer
3063                    .edits_since(old_buffer.version.clone())
3064                    .collect::<Vec<_>>();
3065
3066                log::info!(
3067                    "mutating old buffer version {:?}, text: {:?}, edits since: {:?}",
3068                    old_buffer.version(),
3069                    old_buffer.text(),
3070                    edits,
3071                );
3072
3073                let mut delta = 0_isize;
3074                for edit in edits {
3075                    let old_start = (edit.old_bytes.start as isize + delta) as usize;
3076                    let new_text: String = buffer.text_for_range(edit.new_bytes.clone()).collect();
3077                    old_buffer.edit(
3078                        Some(old_start..old_start + edit.deleted_bytes()),
3079                        new_text,
3080                        cx,
3081                    );
3082                    delta += edit.delta();
3083                }
3084                assert_eq!(old_buffer.text(), buffer.text());
3085            }
3086
3087            buffer
3088        });
3089    }
3090
3091    #[gpui::test]
3092    fn test_line_len(cx: &mut gpui::MutableAppContext) {
3093        cx.add_model(|cx| {
3094            let mut buffer = Buffer::new(0, "", cx);
3095            buffer.edit(vec![0..0], "abcd\nefg\nhij", cx);
3096            buffer.edit(vec![12..12], "kl\nmno", cx);
3097            buffer.edit(vec![18..18], "\npqrs\n", cx);
3098            buffer.edit(vec![18..21], "\nPQ", cx);
3099
3100            assert_eq!(buffer.line_len(0), 4);
3101            assert_eq!(buffer.line_len(1), 3);
3102            assert_eq!(buffer.line_len(2), 5);
3103            assert_eq!(buffer.line_len(3), 3);
3104            assert_eq!(buffer.line_len(4), 4);
3105            assert_eq!(buffer.line_len(5), 0);
3106            buffer
3107        });
3108    }
3109
3110    #[gpui::test]
3111    fn test_text_summary_for_range(cx: &mut gpui::MutableAppContext) {
3112        cx.add_model(|cx| {
3113            let buffer = Buffer::new(0, "ab\nefg\nhklm\nnopqrs\ntuvwxyz", cx);
3114            assert_eq!(
3115                buffer.text_summary_for_range(1..3),
3116                TextSummary {
3117                    bytes: 2,
3118                    lines: Point::new(1, 0),
3119                    first_line_chars: 1,
3120                    last_line_chars: 0,
3121                    longest_row: 0,
3122                    longest_row_chars: 1,
3123                }
3124            );
3125            assert_eq!(
3126                buffer.text_summary_for_range(1..12),
3127                TextSummary {
3128                    bytes: 11,
3129                    lines: Point::new(3, 0),
3130                    first_line_chars: 1,
3131                    last_line_chars: 0,
3132                    longest_row: 2,
3133                    longest_row_chars: 4,
3134                }
3135            );
3136            assert_eq!(
3137                buffer.text_summary_for_range(0..20),
3138                TextSummary {
3139                    bytes: 20,
3140                    lines: Point::new(4, 1),
3141                    first_line_chars: 2,
3142                    last_line_chars: 1,
3143                    longest_row: 3,
3144                    longest_row_chars: 6,
3145                }
3146            );
3147            assert_eq!(
3148                buffer.text_summary_for_range(0..22),
3149                TextSummary {
3150                    bytes: 22,
3151                    lines: Point::new(4, 3),
3152                    first_line_chars: 2,
3153                    last_line_chars: 3,
3154                    longest_row: 3,
3155                    longest_row_chars: 6,
3156                }
3157            );
3158            assert_eq!(
3159                buffer.text_summary_for_range(7..22),
3160                TextSummary {
3161                    bytes: 15,
3162                    lines: Point::new(2, 3),
3163                    first_line_chars: 4,
3164                    last_line_chars: 3,
3165                    longest_row: 1,
3166                    longest_row_chars: 6,
3167                }
3168            );
3169            buffer
3170        });
3171    }
3172
3173    #[gpui::test]
3174    fn test_chars_at(cx: &mut gpui::MutableAppContext) {
3175        cx.add_model(|cx| {
3176            let mut buffer = Buffer::new(0, "", cx);
3177            buffer.edit(vec![0..0], "abcd\nefgh\nij", cx);
3178            buffer.edit(vec![12..12], "kl\nmno", cx);
3179            buffer.edit(vec![18..18], "\npqrs", cx);
3180            buffer.edit(vec![18..21], "\nPQ", cx);
3181
3182            let chars = buffer.chars_at(Point::new(0, 0));
3183            assert_eq!(chars.collect::<String>(), "abcd\nefgh\nijkl\nmno\nPQrs");
3184
3185            let chars = buffer.chars_at(Point::new(1, 0));
3186            assert_eq!(chars.collect::<String>(), "efgh\nijkl\nmno\nPQrs");
3187
3188            let chars = buffer.chars_at(Point::new(2, 0));
3189            assert_eq!(chars.collect::<String>(), "ijkl\nmno\nPQrs");
3190
3191            let chars = buffer.chars_at(Point::new(3, 0));
3192            assert_eq!(chars.collect::<String>(), "mno\nPQrs");
3193
3194            let chars = buffer.chars_at(Point::new(4, 0));
3195            assert_eq!(chars.collect::<String>(), "PQrs");
3196
3197            // Regression test:
3198            let mut buffer = Buffer::new(0, "", cx);
3199            buffer.edit(vec![0..0], "[workspace]\nmembers = [\n    \"xray_core\",\n    \"xray_server\",\n    \"xray_cli\",\n    \"xray_wasm\",\n]\n", cx);
3200            buffer.edit(vec![60..60], "\n", cx);
3201
3202            let chars = buffer.chars_at(Point::new(6, 0));
3203            assert_eq!(chars.collect::<String>(), "    \"xray_wasm\",\n]\n");
3204
3205            buffer
3206        });
3207    }
3208
3209    #[gpui::test]
3210    fn test_anchors(cx: &mut gpui::MutableAppContext) {
3211        cx.add_model(|cx| {
3212            let mut buffer = Buffer::new(0, "", cx);
3213            buffer.edit(vec![0..0], "abc", cx);
3214            let left_anchor = buffer.anchor_before(2);
3215            let right_anchor = buffer.anchor_after(2);
3216
3217            buffer.edit(vec![1..1], "def\n", cx);
3218            assert_eq!(buffer.text(), "adef\nbc");
3219            assert_eq!(left_anchor.to_offset(&buffer), 6);
3220            assert_eq!(right_anchor.to_offset(&buffer), 6);
3221            assert_eq!(left_anchor.to_point(&buffer), Point { row: 1, column: 1 });
3222            assert_eq!(right_anchor.to_point(&buffer), Point { row: 1, column: 1 });
3223
3224            buffer.edit(vec![2..3], "", cx);
3225            assert_eq!(buffer.text(), "adf\nbc");
3226            assert_eq!(left_anchor.to_offset(&buffer), 5);
3227            assert_eq!(right_anchor.to_offset(&buffer), 5);
3228            assert_eq!(left_anchor.to_point(&buffer), Point { row: 1, column: 1 });
3229            assert_eq!(right_anchor.to_point(&buffer), Point { row: 1, column: 1 });
3230
3231            buffer.edit(vec![5..5], "ghi\n", cx);
3232            assert_eq!(buffer.text(), "adf\nbghi\nc");
3233            assert_eq!(left_anchor.to_offset(&buffer), 5);
3234            assert_eq!(right_anchor.to_offset(&buffer), 9);
3235            assert_eq!(left_anchor.to_point(&buffer), Point { row: 1, column: 1 });
3236            assert_eq!(right_anchor.to_point(&buffer), Point { row: 2, column: 0 });
3237
3238            buffer.edit(vec![7..9], "", cx);
3239            assert_eq!(buffer.text(), "adf\nbghc");
3240            assert_eq!(left_anchor.to_offset(&buffer), 5);
3241            assert_eq!(right_anchor.to_offset(&buffer), 7);
3242            assert_eq!(left_anchor.to_point(&buffer), Point { row: 1, column: 1 },);
3243            assert_eq!(right_anchor.to_point(&buffer), Point { row: 1, column: 3 });
3244
3245            // Ensure anchoring to a point is equivalent to anchoring to an offset.
3246            assert_eq!(
3247                buffer.anchor_before(Point { row: 0, column: 0 }),
3248                buffer.anchor_before(0)
3249            );
3250            assert_eq!(
3251                buffer.anchor_before(Point { row: 0, column: 1 }),
3252                buffer.anchor_before(1)
3253            );
3254            assert_eq!(
3255                buffer.anchor_before(Point { row: 0, column: 2 }),
3256                buffer.anchor_before(2)
3257            );
3258            assert_eq!(
3259                buffer.anchor_before(Point { row: 0, column: 3 }),
3260                buffer.anchor_before(3)
3261            );
3262            assert_eq!(
3263                buffer.anchor_before(Point { row: 1, column: 0 }),
3264                buffer.anchor_before(4)
3265            );
3266            assert_eq!(
3267                buffer.anchor_before(Point { row: 1, column: 1 }),
3268                buffer.anchor_before(5)
3269            );
3270            assert_eq!(
3271                buffer.anchor_before(Point { row: 1, column: 2 }),
3272                buffer.anchor_before(6)
3273            );
3274            assert_eq!(
3275                buffer.anchor_before(Point { row: 1, column: 3 }),
3276                buffer.anchor_before(7)
3277            );
3278            assert_eq!(
3279                buffer.anchor_before(Point { row: 1, column: 4 }),
3280                buffer.anchor_before(8)
3281            );
3282
3283            // Comparison between anchors.
3284            let anchor_at_offset_0 = buffer.anchor_before(0);
3285            let anchor_at_offset_1 = buffer.anchor_before(1);
3286            let anchor_at_offset_2 = buffer.anchor_before(2);
3287
3288            assert_eq!(
3289                anchor_at_offset_0
3290                    .cmp(&anchor_at_offset_0, &buffer)
3291                    .unwrap(),
3292                Ordering::Equal
3293            );
3294            assert_eq!(
3295                anchor_at_offset_1
3296                    .cmp(&anchor_at_offset_1, &buffer)
3297                    .unwrap(),
3298                Ordering::Equal
3299            );
3300            assert_eq!(
3301                anchor_at_offset_2
3302                    .cmp(&anchor_at_offset_2, &buffer)
3303                    .unwrap(),
3304                Ordering::Equal
3305            );
3306
3307            assert_eq!(
3308                anchor_at_offset_0
3309                    .cmp(&anchor_at_offset_1, &buffer)
3310                    .unwrap(),
3311                Ordering::Less
3312            );
3313            assert_eq!(
3314                anchor_at_offset_1
3315                    .cmp(&anchor_at_offset_2, &buffer)
3316                    .unwrap(),
3317                Ordering::Less
3318            );
3319            assert_eq!(
3320                anchor_at_offset_0
3321                    .cmp(&anchor_at_offset_2, &buffer)
3322                    .unwrap(),
3323                Ordering::Less
3324            );
3325
3326            assert_eq!(
3327                anchor_at_offset_1
3328                    .cmp(&anchor_at_offset_0, &buffer)
3329                    .unwrap(),
3330                Ordering::Greater
3331            );
3332            assert_eq!(
3333                anchor_at_offset_2
3334                    .cmp(&anchor_at_offset_1, &buffer)
3335                    .unwrap(),
3336                Ordering::Greater
3337            );
3338            assert_eq!(
3339                anchor_at_offset_2
3340                    .cmp(&anchor_at_offset_0, &buffer)
3341                    .unwrap(),
3342                Ordering::Greater
3343            );
3344            buffer
3345        });
3346    }
3347
3348    #[gpui::test]
3349    fn test_anchors_at_start_and_end(cx: &mut gpui::MutableAppContext) {
3350        cx.add_model(|cx| {
3351            let mut buffer = Buffer::new(0, "", cx);
3352            let before_start_anchor = buffer.anchor_before(0);
3353            let after_end_anchor = buffer.anchor_after(0);
3354
3355            buffer.edit(vec![0..0], "abc", cx);
3356            assert_eq!(buffer.text(), "abc");
3357            assert_eq!(before_start_anchor.to_offset(&buffer), 0);
3358            assert_eq!(after_end_anchor.to_offset(&buffer), 3);
3359
3360            let after_start_anchor = buffer.anchor_after(0);
3361            let before_end_anchor = buffer.anchor_before(3);
3362
3363            buffer.edit(vec![3..3], "def", cx);
3364            buffer.edit(vec![0..0], "ghi", cx);
3365            assert_eq!(buffer.text(), "ghiabcdef");
3366            assert_eq!(before_start_anchor.to_offset(&buffer), 0);
3367            assert_eq!(after_start_anchor.to_offset(&buffer), 3);
3368            assert_eq!(before_end_anchor.to_offset(&buffer), 6);
3369            assert_eq!(after_end_anchor.to_offset(&buffer), 9);
3370            buffer
3371        });
3372    }
3373
3374    #[gpui::test]
3375    async fn test_is_dirty(mut cx: gpui::TestAppContext) {
3376        let dir = temp_tree(json!({
3377            "file1": "abc",
3378            "file2": "def",
3379            "file3": "ghi",
3380        }));
3381        let tree = Worktree::open_local(
3382            dir.path(),
3383            Default::default(),
3384            Arc::new(RealFs),
3385            &mut cx.to_async(),
3386        )
3387        .await
3388        .unwrap();
3389        tree.flush_fs_events(&cx).await;
3390        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3391            .await;
3392
3393        let buffer1 = tree
3394            .update(&mut cx, |tree, cx| tree.open_buffer("file1", cx))
3395            .await
3396            .unwrap();
3397        let events = Rc::new(RefCell::new(Vec::new()));
3398
3399        // initially, the buffer isn't dirty.
3400        buffer1.update(&mut cx, |buffer, cx| {
3401            cx.subscribe(&buffer1, {
3402                let events = events.clone();
3403                move |_, _, event, _| events.borrow_mut().push(event.clone())
3404            })
3405            .detach();
3406
3407            assert!(!buffer.is_dirty());
3408            assert!(events.borrow().is_empty());
3409
3410            buffer.edit(vec![1..2], "", cx);
3411        });
3412
3413        // after the first edit, the buffer is dirty, and emits a dirtied event.
3414        buffer1.update(&mut cx, |buffer, cx| {
3415            assert!(buffer.text() == "ac");
3416            assert!(buffer.is_dirty());
3417            assert_eq!(*events.borrow(), &[Event::Edited, Event::Dirtied]);
3418            events.borrow_mut().clear();
3419            buffer.did_save(buffer.version(), buffer.file().unwrap().mtime, cx);
3420        });
3421
3422        // after saving, the buffer is not dirty, and emits a saved event.
3423        buffer1.update(&mut cx, |buffer, cx| {
3424            assert!(!buffer.is_dirty());
3425            assert_eq!(*events.borrow(), &[Event::Saved]);
3426            events.borrow_mut().clear();
3427
3428            buffer.edit(vec![1..1], "B", cx);
3429            buffer.edit(vec![2..2], "D", cx);
3430        });
3431
3432        // after editing again, the buffer is dirty, and emits another dirty event.
3433        buffer1.update(&mut cx, |buffer, cx| {
3434            assert!(buffer.text() == "aBDc");
3435            assert!(buffer.is_dirty());
3436            assert_eq!(
3437                *events.borrow(),
3438                &[Event::Edited, Event::Dirtied, Event::Edited],
3439            );
3440            events.borrow_mut().clear();
3441
3442            // TODO - currently, after restoring the buffer to its
3443            // previously-saved state, the is still considered dirty.
3444            buffer.edit(vec![1..3], "", cx);
3445            assert!(buffer.text() == "ac");
3446            assert!(buffer.is_dirty());
3447        });
3448
3449        assert_eq!(*events.borrow(), &[Event::Edited]);
3450
3451        // When a file is deleted, the buffer is considered dirty.
3452        let events = Rc::new(RefCell::new(Vec::new()));
3453        let buffer2 = tree
3454            .update(&mut cx, |tree, cx| tree.open_buffer("file2", cx))
3455            .await
3456            .unwrap();
3457        buffer2.update(&mut cx, |_, cx| {
3458            cx.subscribe(&buffer2, {
3459                let events = events.clone();
3460                move |_, _, event, _| events.borrow_mut().push(event.clone())
3461            })
3462            .detach();
3463        });
3464
3465        fs::remove_file(dir.path().join("file2")).unwrap();
3466        buffer2.condition(&cx, |b, _| b.is_dirty()).await;
3467        assert_eq!(
3468            *events.borrow(),
3469            &[Event::Dirtied, Event::FileHandleChanged]
3470        );
3471
3472        // When a file is already dirty when deleted, we don't emit a Dirtied event.
3473        let events = Rc::new(RefCell::new(Vec::new()));
3474        let buffer3 = tree
3475            .update(&mut cx, |tree, cx| tree.open_buffer("file3", cx))
3476            .await
3477            .unwrap();
3478        buffer3.update(&mut cx, |_, cx| {
3479            cx.subscribe(&buffer3, {
3480                let events = events.clone();
3481                move |_, _, event, _| events.borrow_mut().push(event.clone())
3482            })
3483            .detach();
3484        });
3485
3486        tree.flush_fs_events(&cx).await;
3487        buffer3.update(&mut cx, |buffer, cx| {
3488            buffer.edit(Some(0..0), "x", cx);
3489        });
3490        events.borrow_mut().clear();
3491        fs::remove_file(dir.path().join("file3")).unwrap();
3492        buffer3
3493            .condition(&cx, |_, _| !events.borrow().is_empty())
3494            .await;
3495        assert_eq!(*events.borrow(), &[Event::FileHandleChanged]);
3496        cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
3497    }
3498
3499    #[gpui::test]
3500    async fn test_file_changes_on_disk(mut cx: gpui::TestAppContext) {
3501        let initial_contents = "aaa\nbbbbb\nc\n";
3502        let dir = temp_tree(json!({ "the-file": initial_contents }));
3503        let tree = Worktree::open_local(
3504            dir.path(),
3505            Default::default(),
3506            Arc::new(RealFs),
3507            &mut cx.to_async(),
3508        )
3509        .await
3510        .unwrap();
3511        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3512            .await;
3513
3514        let abs_path = dir.path().join("the-file");
3515        let buffer = tree
3516            .update(&mut cx, |tree, cx| {
3517                tree.open_buffer(Path::new("the-file"), cx)
3518            })
3519            .await
3520            .unwrap();
3521
3522        // Add a cursor at the start of each row.
3523        let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3524            assert!(!buffer.is_dirty());
3525            buffer.add_selection_set(
3526                (0..3)
3527                    .map(|row| {
3528                        let anchor = buffer.anchor_at(Point::new(row, 0), Bias::Right);
3529                        Selection {
3530                            id: row as usize,
3531                            start: anchor.clone(),
3532                            end: anchor,
3533                            reversed: false,
3534                            goal: SelectionGoal::None,
3535                        }
3536                    })
3537                    .collect::<Vec<_>>(),
3538                cx,
3539            )
3540        });
3541
3542        // Change the file on disk, adding two new lines of text, and removing
3543        // one line.
3544        buffer.read_with(&cx, |buffer, _| {
3545            assert!(!buffer.is_dirty());
3546            assert!(!buffer.has_conflict());
3547        });
3548        let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3549        fs::write(&abs_path, new_contents).unwrap();
3550
3551        // Because the buffer was not modified, it is reloaded from disk. Its
3552        // contents are edited according to the diff between the old and new
3553        // file contents.
3554        buffer
3555            .condition(&cx, |buffer, _| buffer.text() != initial_contents)
3556            .await;
3557
3558        buffer.update(&mut cx, |buffer, _| {
3559            assert_eq!(buffer.text(), new_contents);
3560            assert!(!buffer.is_dirty());
3561            assert!(!buffer.has_conflict());
3562
3563            let set = buffer.selection_set(selection_set_id).unwrap();
3564            let cursor_positions = set
3565                .selections
3566                .iter()
3567                .map(|selection| {
3568                    assert_eq!(selection.start, selection.end);
3569                    selection.start.to_point(&*buffer)
3570                })
3571                .collect::<Vec<_>>();
3572            assert_eq!(
3573                cursor_positions,
3574                &[Point::new(1, 0), Point::new(3, 0), Point::new(4, 0),]
3575            );
3576        });
3577
3578        // Modify the buffer
3579        buffer.update(&mut cx, |buffer, cx| {
3580            buffer.edit(vec![0..0], " ", cx);
3581            assert!(buffer.is_dirty());
3582        });
3583
3584        // Change the file on disk again, adding blank lines to the beginning.
3585        fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3586
3587        // Becaues the buffer is modified, it doesn't reload from disk, but is
3588        // marked as having a conflict.
3589        buffer
3590            .condition(&cx, |buffer, _| buffer.has_conflict())
3591            .await;
3592    }
3593
3594    #[gpui::test]
3595    async fn test_apply_diff(mut cx: gpui::TestAppContext) {
3596        let text = "a\nbb\nccc\ndddd\neeeee\nffffff\n";
3597        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
3598
3599        let text = "a\nccc\ndddd\nffffff\n";
3600        let diff = buffer.read_with(&cx, |b, cx| b.diff(text.into(), cx)).await;
3601        buffer.update(&mut cx, |b, cx| b.apply_diff(diff, cx));
3602        cx.read(|cx| assert_eq!(buffer.read(cx).text(), text));
3603
3604        let text = "a\n1\n\nccc\ndd2dd\nffffff\n";
3605        let diff = buffer.read_with(&cx, |b, cx| b.diff(text.into(), cx)).await;
3606        buffer.update(&mut cx, |b, cx| b.apply_diff(diff, cx));
3607        cx.read(|cx| assert_eq!(buffer.read(cx).text(), text));
3608    }
3609
3610    #[gpui::test]
3611    fn test_undo_redo(cx: &mut gpui::MutableAppContext) {
3612        cx.add_model(|cx| {
3613            let mut buffer = Buffer::new(0, "1234", cx);
3614            // Set group interval to zero so as to not group edits in the undo stack.
3615            buffer.history.group_interval = Duration::from_secs(0);
3616
3617            buffer.edit(vec![1..1], "abx", cx);
3618            buffer.edit(vec![3..4], "yzef", cx);
3619            buffer.edit(vec![3..5], "cd", cx);
3620            assert_eq!(buffer.text(), "1abcdef234");
3621
3622            let transactions = buffer.history.undo_stack.clone();
3623            assert_eq!(transactions.len(), 3);
3624
3625            buffer.undo_or_redo(transactions[0].clone(), cx).unwrap();
3626            assert_eq!(buffer.text(), "1cdef234");
3627            buffer.undo_or_redo(transactions[0].clone(), cx).unwrap();
3628            assert_eq!(buffer.text(), "1abcdef234");
3629
3630            buffer.undo_or_redo(transactions[1].clone(), cx).unwrap();
3631            assert_eq!(buffer.text(), "1abcdx234");
3632            buffer.undo_or_redo(transactions[2].clone(), cx).unwrap();
3633            assert_eq!(buffer.text(), "1abx234");
3634            buffer.undo_or_redo(transactions[1].clone(), cx).unwrap();
3635            assert_eq!(buffer.text(), "1abyzef234");
3636            buffer.undo_or_redo(transactions[2].clone(), cx).unwrap();
3637            assert_eq!(buffer.text(), "1abcdef234");
3638
3639            buffer.undo_or_redo(transactions[2].clone(), cx).unwrap();
3640            assert_eq!(buffer.text(), "1abyzef234");
3641            buffer.undo_or_redo(transactions[0].clone(), cx).unwrap();
3642            assert_eq!(buffer.text(), "1yzef234");
3643            buffer.undo_or_redo(transactions[1].clone(), cx).unwrap();
3644            assert_eq!(buffer.text(), "1234");
3645
3646            buffer
3647        });
3648    }
3649
3650    #[gpui::test]
3651    fn test_history(cx: &mut gpui::MutableAppContext) {
3652        cx.add_model(|cx| {
3653            let mut now = Instant::now();
3654            let mut buffer = Buffer::new(0, "123456", cx);
3655
3656            let set_id =
3657                buffer.add_selection_set(buffer.selections_from_ranges(vec![4..4]).unwrap(), cx);
3658            buffer.start_transaction_at(Some(set_id), now).unwrap();
3659            buffer.edit(vec![2..4], "cd", cx);
3660            buffer.end_transaction_at(Some(set_id), now, cx).unwrap();
3661            assert_eq!(buffer.text(), "12cd56");
3662            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![4..4]);
3663
3664            buffer.start_transaction_at(Some(set_id), now).unwrap();
3665            buffer
3666                .update_selection_set(
3667                    set_id,
3668                    buffer.selections_from_ranges(vec![1..3]).unwrap(),
3669                    cx,
3670                )
3671                .unwrap();
3672            buffer.edit(vec![4..5], "e", cx);
3673            buffer.end_transaction_at(Some(set_id), now, cx).unwrap();
3674            assert_eq!(buffer.text(), "12cde6");
3675            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![1..3]);
3676
3677            now += buffer.history.group_interval + Duration::from_millis(1);
3678            buffer.start_transaction_at(Some(set_id), now).unwrap();
3679            buffer
3680                .update_selection_set(
3681                    set_id,
3682                    buffer.selections_from_ranges(vec![2..2]).unwrap(),
3683                    cx,
3684                )
3685                .unwrap();
3686            buffer.edit(vec![0..1], "a", cx);
3687            buffer.edit(vec![1..1], "b", cx);
3688            buffer.end_transaction_at(Some(set_id), now, cx).unwrap();
3689            assert_eq!(buffer.text(), "ab2cde6");
3690            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![3..3]);
3691
3692            // Last transaction happened past the group interval, undo it on its
3693            // own.
3694            buffer.undo(cx);
3695            assert_eq!(buffer.text(), "12cde6");
3696            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![1..3]);
3697
3698            // First two transactions happened within the group interval, undo them
3699            // together.
3700            buffer.undo(cx);
3701            assert_eq!(buffer.text(), "123456");
3702            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![4..4]);
3703
3704            // Redo the first two transactions together.
3705            buffer.redo(cx);
3706            assert_eq!(buffer.text(), "12cde6");
3707            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![1..3]);
3708
3709            // Redo the last transaction on its own.
3710            buffer.redo(cx);
3711            assert_eq!(buffer.text(), "ab2cde6");
3712            assert_eq!(buffer.selection_ranges(set_id).unwrap(), vec![3..3]);
3713
3714            buffer
3715        });
3716    }
3717
3718    #[gpui::test]
3719    fn test_concurrent_edits(cx: &mut gpui::MutableAppContext) {
3720        let text = "abcdef";
3721
3722        let buffer1 = cx.add_model(|cx| Buffer::new(1, text, cx));
3723        let buffer2 = cx.add_model(|cx| Buffer::new(2, text, cx));
3724        let buffer3 = cx.add_model(|cx| Buffer::new(3, text, cx));
3725
3726        let buf1_op = buffer1.update(cx, |buffer, cx| {
3727            buffer.edit(vec![1..2], "12", cx);
3728            assert_eq!(buffer.text(), "a12cdef");
3729            buffer.operations.last().unwrap().clone()
3730        });
3731        let buf2_op = buffer2.update(cx, |buffer, cx| {
3732            buffer.edit(vec![3..4], "34", cx);
3733            assert_eq!(buffer.text(), "abc34ef");
3734            buffer.operations.last().unwrap().clone()
3735        });
3736        let buf3_op = buffer3.update(cx, |buffer, cx| {
3737            buffer.edit(vec![5..6], "56", cx);
3738            assert_eq!(buffer.text(), "abcde56");
3739            buffer.operations.last().unwrap().clone()
3740        });
3741
3742        buffer1.update(cx, |buffer, _| {
3743            buffer.apply_op(buf2_op.clone()).unwrap();
3744            buffer.apply_op(buf3_op.clone()).unwrap();
3745        });
3746        buffer2.update(cx, |buffer, _| {
3747            buffer.apply_op(buf1_op.clone()).unwrap();
3748            buffer.apply_op(buf3_op.clone()).unwrap();
3749        });
3750        buffer3.update(cx, |buffer, _| {
3751            buffer.apply_op(buf1_op.clone()).unwrap();
3752            buffer.apply_op(buf2_op.clone()).unwrap();
3753        });
3754
3755        assert_eq!(buffer1.read(cx).text(), "a12c34e56");
3756        assert_eq!(buffer2.read(cx).text(), "a12c34e56");
3757        assert_eq!(buffer3.read(cx).text(), "a12c34e56");
3758    }
3759
3760    #[gpui::test(iterations = 100)]
3761    fn test_random_concurrent_edits(cx: &mut gpui::MutableAppContext, mut rng: StdRng) {
3762        use crate::test::Network;
3763
3764        let peers = env::var("PEERS")
3765            .map(|i| i.parse().expect("invalid `PEERS` variable"))
3766            .unwrap_or(5);
3767        let operations = env::var("OPERATIONS")
3768            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3769            .unwrap_or(10);
3770
3771        let base_text_len = rng.gen_range(0..10);
3772        let base_text = RandomCharIter::new(&mut rng)
3773            .take(base_text_len)
3774            .collect::<String>();
3775        let mut replica_ids = Vec::new();
3776        let mut buffers = Vec::new();
3777        let mut network = Network::new(rng.clone());
3778
3779        for i in 0..peers {
3780            let buffer = cx.add_model(|cx| {
3781                let mut buf = Buffer::new(i as ReplicaId, base_text.as_str(), cx);
3782                buf.history.group_interval = Duration::from_millis(rng.gen_range(0..=200));
3783                buf
3784            });
3785            buffers.push(buffer);
3786            replica_ids.push(i as u16);
3787            network.add_peer(i as u16);
3788        }
3789
3790        log::info!("initial text: {:?}", base_text);
3791
3792        let mut mutation_count = operations;
3793        loop {
3794            let replica_index = rng.gen_range(0..peers);
3795            let replica_id = replica_ids[replica_index];
3796            buffers[replica_index].update(cx, |buffer, cx| match rng.gen_range(0..=100) {
3797                0..=50 if mutation_count != 0 => {
3798                    buffer.randomly_mutate(&mut rng, cx);
3799                    network.broadcast(buffer.replica_id, mem::take(&mut buffer.operations));
3800                    log::info!("buffer {} text: {:?}", buffer.replica_id, buffer.text());
3801                    mutation_count -= 1;
3802                }
3803                51..=70 if mutation_count != 0 => {
3804                    buffer.randomly_undo_redo(&mut rng, cx);
3805                    network.broadcast(buffer.replica_id, mem::take(&mut buffer.operations));
3806                    mutation_count -= 1;
3807                }
3808                71..=100 if network.has_unreceived(replica_id) => {
3809                    let ops = network.receive(replica_id);
3810                    if !ops.is_empty() {
3811                        log::info!(
3812                            "peer {} applying {} ops from the network.",
3813                            replica_id,
3814                            ops.len()
3815                        );
3816                        buffer.apply_ops(ops, cx).unwrap();
3817                    }
3818                }
3819                _ => {}
3820            });
3821
3822            if mutation_count == 0 && network.is_idle() {
3823                break;
3824            }
3825        }
3826
3827        let first_buffer = buffers[0].read(cx);
3828        for buffer in &buffers[1..] {
3829            let buffer = buffer.read(cx);
3830            assert_eq!(
3831                buffer.text(),
3832                first_buffer.text(),
3833                "Replica {} text != Replica 0 text",
3834                buffer.replica_id
3835            );
3836            assert_eq!(
3837                buffer.selection_sets().collect::<HashMap<_, _>>(),
3838                first_buffer.selection_sets().collect::<HashMap<_, _>>()
3839            );
3840            assert_eq!(
3841                buffer.all_selection_ranges().collect::<HashMap<_, _>>(),
3842                first_buffer
3843                    .all_selection_ranges()
3844                    .collect::<HashMap<_, _>>()
3845            );
3846        }
3847    }
3848
3849    #[gpui::test]
3850    async fn test_reparse(mut cx: gpui::TestAppContext) {
3851        let languages = LanguageRegistry::new();
3852        let rust_lang = languages.select_language("test.rs");
3853        assert!(rust_lang.is_some());
3854
3855        let buffer = cx.add_model(|cx| {
3856            let text = "fn a() {}".into();
3857            Buffer::from_history(0, History::new(text), None, rust_lang.cloned(), cx)
3858        });
3859
3860        // Wait for the initial text to parse
3861        buffer
3862            .condition(&cx, |buffer, _| !buffer.is_parsing())
3863            .await;
3864        assert_eq!(
3865            get_tree_sexp(&buffer, &cx),
3866            concat!(
3867                "(source_file (function_item name: (identifier) ",
3868                "parameters: (parameters) ",
3869                "body: (block)))"
3870            )
3871        );
3872
3873        buffer.update(&mut cx, |buffer, _| {
3874            buffer.set_sync_parse_timeout(Duration::ZERO)
3875        });
3876
3877        // Perform some edits (add parameter and variable reference)
3878        // Parsing doesn't begin until the transaction is complete
3879        buffer.update(&mut cx, |buf, cx| {
3880            buf.start_transaction(None).unwrap();
3881
3882            let offset = buf.text().find(")").unwrap();
3883            buf.edit(vec![offset..offset], "b: C", cx);
3884            assert!(!buf.is_parsing());
3885
3886            let offset = buf.text().find("}").unwrap();
3887            buf.edit(vec![offset..offset], " d; ", cx);
3888            assert!(!buf.is_parsing());
3889
3890            buf.end_transaction(None, cx).unwrap();
3891            assert_eq!(buf.text(), "fn a(b: C) { d; }");
3892            assert!(buf.is_parsing());
3893        });
3894        buffer
3895            .condition(&cx, |buffer, _| !buffer.is_parsing())
3896            .await;
3897        assert_eq!(
3898            get_tree_sexp(&buffer, &cx),
3899            concat!(
3900                "(source_file (function_item name: (identifier) ",
3901                    "parameters: (parameters (parameter pattern: (identifier) type: (type_identifier))) ",
3902                    "body: (block (identifier))))"
3903            )
3904        );
3905
3906        // Perform a series of edits without waiting for the current parse to complete:
3907        // * turn identifier into a field expression
3908        // * turn field expression into a method call
3909        // * add a turbofish to the method call
3910        buffer.update(&mut cx, |buf, cx| {
3911            let offset = buf.text().find(";").unwrap();
3912            buf.edit(vec![offset..offset], ".e", cx);
3913            assert_eq!(buf.text(), "fn a(b: C) { d.e; }");
3914            assert!(buf.is_parsing());
3915        });
3916        buffer.update(&mut cx, |buf, cx| {
3917            let offset = buf.text().find(";").unwrap();
3918            buf.edit(vec![offset..offset], "(f)", cx);
3919            assert_eq!(buf.text(), "fn a(b: C) { d.e(f); }");
3920            assert!(buf.is_parsing());
3921        });
3922        buffer.update(&mut cx, |buf, cx| {
3923            let offset = buf.text().find("(f)").unwrap();
3924            buf.edit(vec![offset..offset], "::<G>", cx);
3925            assert_eq!(buf.text(), "fn a(b: C) { d.e::<G>(f); }");
3926            assert!(buf.is_parsing());
3927        });
3928        buffer
3929            .condition(&cx, |buffer, _| !buffer.is_parsing())
3930            .await;
3931        assert_eq!(
3932            get_tree_sexp(&buffer, &cx),
3933            concat!(
3934                "(source_file (function_item name: (identifier) ",
3935                    "parameters: (parameters (parameter pattern: (identifier) type: (type_identifier))) ",
3936                    "body: (block (call_expression ",
3937                        "function: (generic_function ",
3938                            "function: (field_expression value: (identifier) field: (field_identifier)) ",
3939                            "type_arguments: (type_arguments (type_identifier))) ",
3940                            "arguments: (arguments (identifier))))))",
3941            )
3942        );
3943
3944        buffer.update(&mut cx, |buf, cx| {
3945            buf.undo(cx);
3946            assert_eq!(buf.text(), "fn a() {}");
3947            assert!(buf.is_parsing());
3948        });
3949        buffer
3950            .condition(&cx, |buffer, _| !buffer.is_parsing())
3951            .await;
3952        assert_eq!(
3953            get_tree_sexp(&buffer, &cx),
3954            concat!(
3955                "(source_file (function_item name: (identifier) ",
3956                "parameters: (parameters) ",
3957                "body: (block)))"
3958            )
3959        );
3960
3961        buffer.update(&mut cx, |buf, cx| {
3962            buf.redo(cx);
3963            assert_eq!(buf.text(), "fn a(b: C) { d.e::<G>(f); }");
3964            assert!(buf.is_parsing());
3965        });
3966        buffer
3967            .condition(&cx, |buffer, _| !buffer.is_parsing())
3968            .await;
3969        assert_eq!(
3970            get_tree_sexp(&buffer, &cx),
3971            concat!(
3972                "(source_file (function_item name: (identifier) ",
3973                    "parameters: (parameters (parameter pattern: (identifier) type: (type_identifier))) ",
3974                    "body: (block (call_expression ",
3975                        "function: (generic_function ",
3976                            "function: (field_expression value: (identifier) field: (field_identifier)) ",
3977                            "type_arguments: (type_arguments (type_identifier))) ",
3978                            "arguments: (arguments (identifier))))))",
3979            )
3980        );
3981
3982        fn get_tree_sexp(buffer: &ModelHandle<Buffer>, cx: &gpui::TestAppContext) -> String {
3983            buffer.read_with(cx, |buffer, _| {
3984                buffer.syntax_tree().unwrap().root_node().to_sexp()
3985            })
3986        }
3987    }
3988
3989    #[gpui::test]
3990    async fn test_enclosing_bracket_ranges(mut cx: gpui::TestAppContext) {
3991        use unindent::Unindent as _;
3992
3993        let languages = LanguageRegistry::new();
3994        let rust_lang = languages.select_language("test.rs");
3995        assert!(rust_lang.is_some());
3996
3997        let buffer = cx.add_model(|cx| {
3998            let text = "
3999                mod x {
4000                    mod y {
4001
4002                    }
4003                }
4004            "
4005            .unindent()
4006            .into();
4007            Buffer::from_history(0, History::new(text), None, rust_lang.cloned(), cx)
4008        });
4009        buffer
4010            .condition(&cx, |buffer, _| !buffer.is_parsing())
4011            .await;
4012        buffer.read_with(&cx, |buf, _| {
4013            assert_eq!(
4014                buf.enclosing_bracket_point_ranges(Point::new(1, 6)..Point::new(1, 6)),
4015                Some((
4016                    Point::new(0, 6)..Point::new(0, 7),
4017                    Point::new(4, 0)..Point::new(4, 1)
4018                ))
4019            );
4020            assert_eq!(
4021                buf.enclosing_bracket_point_ranges(Point::new(1, 10)..Point::new(1, 10)),
4022                Some((
4023                    Point::new(1, 10)..Point::new(1, 11),
4024                    Point::new(3, 4)..Point::new(3, 5)
4025                ))
4026            );
4027            assert_eq!(
4028                buf.enclosing_bracket_point_ranges(Point::new(3, 5)..Point::new(3, 5)),
4029                Some((
4030                    Point::new(1, 10)..Point::new(1, 11),
4031                    Point::new(3, 4)..Point::new(3, 5)
4032                ))
4033            );
4034        });
4035    }
4036
4037    impl Buffer {
4038        fn random_byte_range(&mut self, start_offset: usize, rng: &mut impl Rng) -> Range<usize> {
4039            let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
4040            let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
4041            start..end
4042        }
4043
4044        pub fn randomly_edit<T>(
4045            &mut self,
4046            rng: &mut T,
4047            old_range_count: usize,
4048            cx: &mut ModelContext<Self>,
4049        ) -> (Vec<Range<usize>>, String)
4050        where
4051            T: Rng,
4052        {
4053            let mut old_ranges: Vec<Range<usize>> = Vec::new();
4054            for _ in 0..old_range_count {
4055                let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
4056                if last_end > self.len() {
4057                    break;
4058                }
4059                old_ranges.push(self.random_byte_range(last_end, rng));
4060            }
4061            let new_text_len = rng.gen_range(0..10);
4062            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
4063            log::info!(
4064                "mutating buffer {} at {:?}: {:?}",
4065                self.replica_id,
4066                old_ranges,
4067                new_text
4068            );
4069            self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
4070            (old_ranges, new_text)
4071        }
4072
4073        pub fn randomly_mutate<T>(
4074            &mut self,
4075            rng: &mut T,
4076            cx: &mut ModelContext<Self>,
4077        ) -> (Vec<Range<usize>>, String)
4078        where
4079            T: Rng,
4080        {
4081            let (old_ranges, new_text) = self.randomly_edit(rng, 5, cx);
4082
4083            // Randomly add, remove or mutate selection sets.
4084            let replica_selection_sets = &self
4085                .selection_sets()
4086                .map(|(set_id, _)| *set_id)
4087                .filter(|set_id| self.replica_id == set_id.replica_id)
4088                .collect::<Vec<_>>();
4089            let set_id = replica_selection_sets.choose(rng);
4090            if set_id.is_some() && rng.gen_bool(1.0 / 6.0) {
4091                self.remove_selection_set(*set_id.unwrap(), cx).unwrap();
4092            } else {
4093                let mut ranges = Vec::new();
4094                for _ in 0..5 {
4095                    ranges.push(self.random_byte_range(0, rng));
4096                }
4097                let new_selections = self.selections_from_ranges(ranges).unwrap();
4098
4099                if set_id.is_none() || rng.gen_bool(1.0 / 5.0) {
4100                    self.add_selection_set(new_selections, cx);
4101                } else {
4102                    self.update_selection_set(*set_id.unwrap(), new_selections, cx)
4103                        .unwrap();
4104                }
4105            }
4106
4107            (old_ranges, new_text)
4108        }
4109
4110        pub fn randomly_undo_redo(&mut self, rng: &mut impl Rng, cx: &mut ModelContext<Self>) {
4111            for _ in 0..rng.gen_range(1..=5) {
4112                if let Some(transaction) = self.history.undo_stack.choose(rng).cloned() {
4113                    log::info!(
4114                        "undoing buffer {} transaction {:?}",
4115                        self.replica_id,
4116                        transaction
4117                    );
4118                    self.undo_or_redo(transaction, cx).unwrap();
4119                }
4120            }
4121        }
4122
4123        fn selections_from_ranges<I>(&self, ranges: I) -> Result<Vec<Selection>>
4124        where
4125            I: IntoIterator<Item = Range<usize>>,
4126        {
4127            static NEXT_SELECTION_ID: AtomicUsize = AtomicUsize::new(0);
4128
4129            let mut ranges = ranges.into_iter().collect::<Vec<_>>();
4130            ranges.sort_unstable_by_key(|range| range.start);
4131
4132            let mut selections = Vec::with_capacity(ranges.len());
4133            for range in ranges {
4134                if range.start > range.end {
4135                    selections.push(Selection {
4136                        id: NEXT_SELECTION_ID.fetch_add(1, atomic::Ordering::SeqCst),
4137                        start: self.anchor_before(range.end),
4138                        end: self.anchor_before(range.start),
4139                        reversed: true,
4140                        goal: SelectionGoal::None,
4141                    });
4142                } else {
4143                    selections.push(Selection {
4144                        id: NEXT_SELECTION_ID.fetch_add(1, atomic::Ordering::SeqCst),
4145                        start: self.anchor_after(range.start),
4146                        end: self.anchor_before(range.end),
4147                        reversed: false,
4148                        goal: SelectionGoal::None,
4149                    });
4150                }
4151            }
4152            Ok(selections)
4153        }
4154
4155        pub fn selection_ranges<'a>(&'a self, set_id: SelectionSetId) -> Result<Vec<Range<usize>>> {
4156            Ok(self
4157                .selection_set(set_id)?
4158                .selections
4159                .iter()
4160                .map(move |selection| {
4161                    let start = selection.start.to_offset(self);
4162                    let end = selection.end.to_offset(self);
4163                    if selection.reversed {
4164                        end..start
4165                    } else {
4166                        start..end
4167                    }
4168                })
4169                .collect())
4170        }
4171
4172        pub fn all_selection_ranges<'a>(
4173            &'a self,
4174        ) -> impl 'a + Iterator<Item = (SelectionSetId, Vec<Range<usize>>)> {
4175            self.selections
4176                .keys()
4177                .map(move |set_id| (*set_id, self.selection_ranges(*set_id).unwrap()))
4178        }
4179
4180        pub fn enclosing_bracket_point_ranges<T: ToOffset>(
4181            &self,
4182            range: Range<T>,
4183        ) -> Option<(Range<Point>, Range<Point>)> {
4184            self.enclosing_bracket_ranges(range).map(|(start, end)| {
4185                let point_start = start.start.to_point(self)..start.end.to_point(self);
4186                let point_end = end.start.to_point(self)..end.end.to_point(self);
4187                (point_start, point_end)
4188            })
4189        }
4190    }
4191}