lib.rs

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