text.rs

   1mod anchor;
   2mod locator;
   3mod operation_queue;
   4mod patch;
   5mod point;
   6mod point_utf16;
   7#[cfg(any(test, feature = "test-support"))]
   8pub mod random_char_iter;
   9pub mod rope;
  10mod selection;
  11#[cfg(test)]
  12mod tests;
  13
  14pub use anchor::*;
  15use anyhow::{anyhow, Result};
  16use clock::ReplicaId;
  17use collections::{HashMap, HashSet};
  18use locator::Locator;
  19use operation_queue::OperationQueue;
  20use parking_lot::Mutex;
  21pub use patch::Patch;
  22pub use point::*;
  23pub use point_utf16::*;
  24#[cfg(any(test, feature = "test-support"))]
  25pub use random_char_iter::*;
  26use rope::TextDimension;
  27pub use rope::{Chunks, Rope, TextSummary};
  28pub use selection::*;
  29use std::{
  30    cmp::{self, Reverse},
  31    iter::Iterator,
  32    ops::{self, Deref, Range, Sub},
  33    str,
  34    sync::{Arc, Weak},
  35    time::{Duration, Instant},
  36};
  37pub use sum_tree::Bias;
  38use sum_tree::{FilterCursor, SumTree};
  39
  40pub struct Buffer {
  41    snapshot: Snapshot,
  42    last_edit: clock::Local,
  43    history: History,
  44    selections: HashMap<SelectionSetId, SelectionSet>,
  45    deferred_ops: OperationQueue,
  46    deferred_replicas: HashSet<ReplicaId>,
  47    replica_id: ReplicaId,
  48    remote_id: u64,
  49    local_clock: clock::Local,
  50    lamport_clock: clock::Lamport,
  51    subscriptions: Vec<Weak<Mutex<Vec<Patch<usize>>>>>,
  52}
  53
  54#[derive(Clone)]
  55pub struct Snapshot {
  56    visible_text: Rope,
  57    deleted_text: Rope,
  58    undo_map: UndoMap,
  59    fragments: SumTree<Fragment>,
  60    insertions: SumTree<InsertionFragment>,
  61    pub version: clock::Global,
  62}
  63
  64#[derive(Clone, Debug)]
  65pub struct Transaction {
  66    start: clock::Global,
  67    end: clock::Global,
  68    edits: Vec<clock::Local>,
  69    ranges: Vec<Range<FullOffset>>,
  70    selections_before: HashMap<SelectionSetId, Arc<AnchorRangeMap<SelectionState>>>,
  71    selections_after: HashMap<SelectionSetId, Arc<AnchorRangeMap<SelectionState>>>,
  72    first_edit_at: Instant,
  73    last_edit_at: Instant,
  74}
  75
  76impl Transaction {
  77    pub fn starting_selection_set_ids<'a>(&'a self) -> impl Iterator<Item = SelectionSetId> + 'a {
  78        self.selections_before.keys().copied()
  79    }
  80
  81    fn push_edit(&mut self, edit: &EditOperation) {
  82        self.edits.push(edit.timestamp.local());
  83        self.end.observe(edit.timestamp.local());
  84
  85        let mut other_ranges = edit.ranges.iter().peekable();
  86        let mut new_ranges = Vec::new();
  87        let insertion_len = edit.new_text.as_ref().map_or(0, |t| t.len());
  88        let mut delta = 0;
  89
  90        for mut self_range in self.ranges.iter().cloned() {
  91            self_range.start += delta;
  92            self_range.end += delta;
  93
  94            while let Some(other_range) = other_ranges.peek() {
  95                let mut other_range = (*other_range).clone();
  96                other_range.start += delta;
  97                other_range.end += delta;
  98
  99                if other_range.start <= self_range.end {
 100                    other_ranges.next().unwrap();
 101                    delta += insertion_len;
 102
 103                    if other_range.end < self_range.start {
 104                        new_ranges.push(other_range.start..other_range.end + insertion_len);
 105                        self_range.start += insertion_len;
 106                        self_range.end += insertion_len;
 107                    } else {
 108                        self_range.start = cmp::min(self_range.start, other_range.start);
 109                        self_range.end = cmp::max(self_range.end, other_range.end) + insertion_len;
 110                    }
 111                } else {
 112                    break;
 113                }
 114            }
 115
 116            new_ranges.push(self_range);
 117        }
 118
 119        for other_range in other_ranges {
 120            new_ranges.push(other_range.start + delta..other_range.end + delta + insertion_len);
 121            delta += insertion_len;
 122        }
 123
 124        self.ranges = new_ranges;
 125    }
 126}
 127
 128#[derive(Clone)]
 129pub struct History {
 130    // TODO: Turn this into a String or Rope, maybe.
 131    pub base_text: Arc<str>,
 132    ops: HashMap<clock::Local, EditOperation>,
 133    undo_stack: Vec<Transaction>,
 134    redo_stack: Vec<Transaction>,
 135    transaction_depth: usize,
 136    group_interval: Duration,
 137}
 138
 139impl History {
 140    pub fn new(base_text: Arc<str>) -> Self {
 141        Self {
 142            base_text,
 143            ops: Default::default(),
 144            undo_stack: Vec::new(),
 145            redo_stack: Vec::new(),
 146            transaction_depth: 0,
 147            group_interval: Duration::from_millis(300),
 148        }
 149    }
 150
 151    fn push(&mut self, op: EditOperation) {
 152        self.ops.insert(op.timestamp.local(), op);
 153    }
 154
 155    fn start_transaction(
 156        &mut self,
 157        start: clock::Global,
 158        selections_before: HashMap<SelectionSetId, Arc<AnchorRangeMap<SelectionState>>>,
 159        now: Instant,
 160    ) {
 161        self.transaction_depth += 1;
 162        if self.transaction_depth == 1 {
 163            self.undo_stack.push(Transaction {
 164                start: start.clone(),
 165                end: start,
 166                edits: Vec::new(),
 167                ranges: Vec::new(),
 168                selections_before,
 169                selections_after: Default::default(),
 170                first_edit_at: now,
 171                last_edit_at: now,
 172            });
 173        }
 174    }
 175
 176    fn end_transaction(
 177        &mut self,
 178        selections_after: HashMap<SelectionSetId, Arc<AnchorRangeMap<SelectionState>>>,
 179        now: Instant,
 180    ) -> Option<&Transaction> {
 181        assert_ne!(self.transaction_depth, 0);
 182        self.transaction_depth -= 1;
 183        if self.transaction_depth == 0 {
 184            if self.undo_stack.last().unwrap().ranges.is_empty() {
 185                self.undo_stack.pop();
 186                None
 187            } else {
 188                let transaction = self.undo_stack.last_mut().unwrap();
 189                transaction.selections_after = selections_after;
 190                transaction.last_edit_at = now;
 191                Some(transaction)
 192            }
 193        } else {
 194            None
 195        }
 196    }
 197
 198    fn group(&mut self) {
 199        let mut new_len = self.undo_stack.len();
 200        let mut transactions = self.undo_stack.iter_mut();
 201
 202        if let Some(mut transaction) = transactions.next_back() {
 203            while let Some(prev_transaction) = transactions.next_back() {
 204                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
 205                    && transaction.start == prev_transaction.end
 206                {
 207                    transaction = prev_transaction;
 208                    new_len -= 1;
 209                } else {
 210                    break;
 211                }
 212            }
 213        }
 214
 215        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
 216        if let Some(last_transaction) = transactions_to_keep.last_mut() {
 217            for transaction in &*transactions_to_merge {
 218                for edit_id in &transaction.edits {
 219                    last_transaction.push_edit(&self.ops[edit_id]);
 220                }
 221            }
 222
 223            if let Some(transaction) = transactions_to_merge.last_mut() {
 224                last_transaction.last_edit_at = transaction.last_edit_at;
 225                last_transaction
 226                    .selections_after
 227                    .extend(transaction.selections_after.drain());
 228                last_transaction.end = transaction.end.clone();
 229            }
 230        }
 231
 232        self.undo_stack.truncate(new_len);
 233    }
 234
 235    fn push_undo(&mut self, edit_id: clock::Local) {
 236        assert_ne!(self.transaction_depth, 0);
 237        let last_transaction = self.undo_stack.last_mut().unwrap();
 238        last_transaction.push_edit(&self.ops[&edit_id]);
 239    }
 240
 241    fn pop_undo(&mut self) -> Option<&Transaction> {
 242        assert_eq!(self.transaction_depth, 0);
 243        if let Some(transaction) = self.undo_stack.pop() {
 244            self.redo_stack.push(transaction);
 245            self.redo_stack.last()
 246        } else {
 247            None
 248        }
 249    }
 250
 251    fn pop_redo(&mut self) -> Option<&Transaction> {
 252        assert_eq!(self.transaction_depth, 0);
 253        if let Some(transaction) = self.redo_stack.pop() {
 254            self.undo_stack.push(transaction);
 255            self.undo_stack.last()
 256        } else {
 257            None
 258        }
 259    }
 260}
 261
 262#[derive(Clone, Default, Debug)]
 263struct UndoMap(HashMap<clock::Local, Vec<(clock::Local, u32)>>);
 264
 265impl UndoMap {
 266    fn insert(&mut self, undo: &UndoOperation) {
 267        for (edit_id, count) in &undo.counts {
 268            self.0.entry(*edit_id).or_default().push((undo.id, *count));
 269        }
 270    }
 271
 272    fn is_undone(&self, edit_id: clock::Local) -> bool {
 273        self.undo_count(edit_id) % 2 == 1
 274    }
 275
 276    fn was_undone(&self, edit_id: clock::Local, version: &clock::Global) -> bool {
 277        let undo_count = self
 278            .0
 279            .get(&edit_id)
 280            .unwrap_or(&Vec::new())
 281            .iter()
 282            .filter(|(undo_id, _)| version.observed(*undo_id))
 283            .map(|(_, undo_count)| *undo_count)
 284            .max()
 285            .unwrap_or(0);
 286        undo_count % 2 == 1
 287    }
 288
 289    fn undo_count(&self, edit_id: clock::Local) -> u32 {
 290        self.0
 291            .get(&edit_id)
 292            .unwrap_or(&Vec::new())
 293            .iter()
 294            .map(|(_, undo_count)| *undo_count)
 295            .max()
 296            .unwrap_or(0)
 297    }
 298}
 299
 300struct Edits<'a, D: TextDimension<'a>, F: FnMut(&FragmentSummary) -> bool> {
 301    visible_cursor: rope::Cursor<'a>,
 302    deleted_cursor: rope::Cursor<'a>,
 303    fragments_cursor: Option<FilterCursor<'a, F, Fragment, FragmentTextSummary>>,
 304    undos: &'a UndoMap,
 305    since: &'a clock::Global,
 306    old_end: D,
 307    new_end: D,
 308}
 309
 310#[derive(Clone, Debug, Default, Eq, PartialEq)]
 311pub struct Edit<D> {
 312    pub old: Range<D>,
 313    pub new: Range<D>,
 314}
 315
 316impl<D> Edit<D>
 317where
 318    D: Sub<D, Output = D> + PartialEq + Copy,
 319{
 320    pub fn old_len(&self) -> D {
 321        self.old.end - self.old.start
 322    }
 323
 324    pub fn new_len(&self) -> D {
 325        self.new.end - self.new.start
 326    }
 327
 328    pub fn is_empty(&self) -> bool {
 329        self.old.start == self.old.end && self.new.start == self.new.end
 330    }
 331}
 332
 333impl<D1, D2> Edit<(D1, D2)> {
 334    pub fn flatten(self) -> (Edit<D1>, Edit<D2>) {
 335        (
 336            Edit {
 337                old: self.old.start.0..self.old.end.0,
 338                new: self.new.start.0..self.new.end.0,
 339            },
 340            Edit {
 341                old: self.old.start.1..self.old.end.1,
 342                new: self.new.start.1..self.new.end.1,
 343            },
 344        )
 345    }
 346}
 347
 348#[derive(Clone, Default)]
 349pub struct Subscription(Arc<Mutex<Vec<Patch<usize>>>>);
 350
 351impl Subscription {
 352    pub fn consume(&self) -> Patch<usize> {
 353        let mut patches = self.0.lock();
 354        let mut changes = Patch::default();
 355        for patch in patches.drain(..) {
 356            changes = changes.compose(&patch);
 357        }
 358        changes
 359    }
 360}
 361
 362#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
 363pub struct InsertionTimestamp {
 364    pub replica_id: ReplicaId,
 365    pub local: clock::Seq,
 366    pub lamport: clock::Seq,
 367}
 368
 369impl InsertionTimestamp {
 370    fn local(&self) -> clock::Local {
 371        clock::Local {
 372            replica_id: self.replica_id,
 373            value: self.local,
 374        }
 375    }
 376
 377    fn lamport(&self) -> clock::Lamport {
 378        clock::Lamport {
 379            replica_id: self.replica_id,
 380            value: self.lamport,
 381        }
 382    }
 383}
 384
 385#[derive(Eq, PartialEq, Clone, Debug)]
 386struct Fragment {
 387    id: Locator,
 388    insertion_timestamp: InsertionTimestamp,
 389    insertion_offset: usize,
 390    len: usize,
 391    visible: bool,
 392    deletions: HashSet<clock::Local>,
 393    max_undos: clock::Global,
 394}
 395
 396#[derive(Eq, PartialEq, Clone, Debug)]
 397pub struct FragmentSummary {
 398    text: FragmentTextSummary,
 399    max_id: Locator,
 400    max_version: clock::Global,
 401    min_insertion_version: clock::Global,
 402    max_insertion_version: clock::Global,
 403}
 404
 405#[derive(Copy, Default, Clone, Debug, PartialEq, Eq)]
 406struct FragmentTextSummary {
 407    visible: usize,
 408    deleted: usize,
 409}
 410
 411#[derive(Eq, PartialEq, Clone, Debug)]
 412struct InsertionFragment {
 413    timestamp: InsertionTimestamp,
 414    split_offset: usize,
 415    fragment_id: Locator,
 416}
 417
 418#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
 419struct InsertionFragmentKey {
 420    timestamp: InsertionTimestamp,
 421    split_offset: usize,
 422}
 423
 424#[derive(Clone, Debug, Eq, PartialEq)]
 425pub enum Operation {
 426    Edit(EditOperation),
 427    Undo {
 428        undo: UndoOperation,
 429        lamport_timestamp: clock::Lamport,
 430    },
 431    UpdateSelections {
 432        set_id: SelectionSetId,
 433        selections: Arc<AnchorRangeMap<SelectionState>>,
 434        lamport_timestamp: clock::Lamport,
 435    },
 436    RemoveSelections {
 437        set_id: SelectionSetId,
 438        lamport_timestamp: clock::Lamport,
 439    },
 440    SetActiveSelections {
 441        set_id: Option<SelectionSetId>,
 442        lamport_timestamp: clock::Lamport,
 443    },
 444    #[cfg(test)]
 445    Test(clock::Lamport),
 446}
 447
 448#[derive(Clone, Debug, Eq, PartialEq)]
 449pub struct EditOperation {
 450    pub timestamp: InsertionTimestamp,
 451    pub version: clock::Global,
 452    pub ranges: Vec<Range<FullOffset>>,
 453    pub new_text: Option<String>,
 454}
 455
 456#[derive(Clone, Debug, Eq, PartialEq)]
 457pub struct UndoOperation {
 458    pub id: clock::Local,
 459    pub counts: HashMap<clock::Local, u32>,
 460    pub ranges: Vec<Range<FullOffset>>,
 461    pub version: clock::Global,
 462}
 463
 464impl Buffer {
 465    pub fn new(replica_id: u16, remote_id: u64, history: History) -> Buffer {
 466        let mut fragments = SumTree::new();
 467        let mut insertions = SumTree::new();
 468
 469        let mut local_clock = clock::Local::new(replica_id);
 470        let mut lamport_clock = clock::Lamport::new(replica_id);
 471        let mut version = clock::Global::new();
 472        let visible_text = Rope::from(history.base_text.as_ref());
 473        if visible_text.len() > 0 {
 474            let insertion_timestamp = InsertionTimestamp {
 475                replica_id: 0,
 476                local: 1,
 477                lamport: 1,
 478            };
 479            local_clock.observe(insertion_timestamp.local());
 480            lamport_clock.observe(insertion_timestamp.lamport());
 481            version.observe(insertion_timestamp.local());
 482            let fragment_id = Locator::between(&Locator::min(), &Locator::max());
 483            let fragment = Fragment {
 484                id: fragment_id,
 485                insertion_timestamp,
 486                insertion_offset: 0,
 487                len: visible_text.len(),
 488                visible: true,
 489                deletions: Default::default(),
 490                max_undos: Default::default(),
 491            };
 492            insertions.push(InsertionFragment::new(&fragment), &());
 493            fragments.push(fragment, &None);
 494        }
 495
 496        Buffer {
 497            snapshot: Snapshot {
 498                visible_text,
 499                deleted_text: Rope::new(),
 500                fragments,
 501                insertions,
 502                version,
 503                undo_map: Default::default(),
 504            },
 505            last_edit: clock::Local::default(),
 506            history,
 507            selections: Default::default(),
 508            deferred_ops: OperationQueue::new(),
 509            deferred_replicas: HashSet::default(),
 510            replica_id,
 511            remote_id,
 512            local_clock,
 513            lamport_clock,
 514            subscriptions: Default::default(),
 515        }
 516    }
 517
 518    pub fn version(&self) -> clock::Global {
 519        self.version.clone()
 520    }
 521
 522    pub fn snapshot(&self) -> Snapshot {
 523        self.snapshot.clone()
 524    }
 525
 526    pub fn replica_id(&self) -> ReplicaId {
 527        self.local_clock.replica_id
 528    }
 529
 530    pub fn remote_id(&self) -> u64 {
 531        self.remote_id
 532    }
 533
 534    pub fn deferred_ops_len(&self) -> usize {
 535        self.deferred_ops.len()
 536    }
 537
 538    pub fn edit<R, I, S, T>(&mut self, ranges: R, new_text: T) -> EditOperation
 539    where
 540        R: IntoIterator<IntoIter = I>,
 541        I: ExactSizeIterator<Item = Range<S>>,
 542        S: ToOffset,
 543        T: Into<String>,
 544    {
 545        let new_text = new_text.into();
 546        let new_text_len = new_text.len();
 547        let new_text = if new_text_len > 0 {
 548            Some(new_text)
 549        } else {
 550            None
 551        };
 552
 553        self.start_transaction(None).unwrap();
 554        let timestamp = InsertionTimestamp {
 555            replica_id: self.replica_id,
 556            local: self.local_clock.tick().value,
 557            lamport: self.lamport_clock.tick().value,
 558        };
 559        let edit = self.apply_local_edit(ranges.into_iter(), new_text, timestamp);
 560
 561        self.history.push(edit.clone());
 562        self.history.push_undo(edit.timestamp.local());
 563        self.last_edit = edit.timestamp.local();
 564        self.snapshot.version.observe(edit.timestamp.local());
 565        self.end_transaction(None);
 566        edit
 567    }
 568
 569    fn apply_local_edit<S: ToOffset>(
 570        &mut self,
 571        ranges: impl ExactSizeIterator<Item = Range<S>>,
 572        new_text: Option<String>,
 573        timestamp: InsertionTimestamp,
 574    ) -> EditOperation {
 575        let mut edits = Patch::default();
 576        let mut edit_op = EditOperation {
 577            timestamp,
 578            version: self.version(),
 579            ranges: Vec::with_capacity(ranges.len()),
 580            new_text: None,
 581        };
 582        let mut new_insertions = Vec::new();
 583
 584        let mut ranges = ranges
 585            .map(|range| range.start.to_offset(&*self)..range.end.to_offset(&*self))
 586            .peekable();
 587
 588        let mut new_ropes =
 589            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
 590        let mut old_fragments = self.fragments.cursor::<FragmentTextSummary>();
 591        let mut new_fragments =
 592            old_fragments.slice(&ranges.peek().unwrap().start, Bias::Right, &None);
 593        new_ropes.push_tree(new_fragments.summary().text);
 594
 595        let mut fragment_start = old_fragments.start().visible;
 596        for range in ranges {
 597            let fragment_end = old_fragments.end(&None).visible;
 598
 599            // If the current fragment ends before this range, then jump ahead to the first fragment
 600            // that extends past the start of this range, reusing any intervening fragments.
 601            if fragment_end < range.start {
 602                // If the current fragment has been partially consumed, then consume the rest of it
 603                // and advance to the next fragment before slicing.
 604                if fragment_start > old_fragments.start().visible {
 605                    if fragment_end > fragment_start {
 606                        let mut suffix = old_fragments.item().unwrap().clone();
 607                        suffix.len = fragment_end - fragment_start;
 608                        suffix.insertion_offset += fragment_start - old_fragments.start().visible;
 609                        new_insertions.push(InsertionFragment::insert_new(&suffix));
 610                        new_ropes.push_fragment(&suffix, suffix.visible);
 611                        new_fragments.push(suffix, &None);
 612                    }
 613                    old_fragments.next(&None);
 614                }
 615
 616                let slice = old_fragments.slice(&range.start, Bias::Right, &None);
 617                new_ropes.push_tree(slice.summary().text);
 618                new_fragments.push_tree(slice, &None);
 619                fragment_start = old_fragments.start().visible;
 620            }
 621
 622            let full_range_start = FullOffset(range.start + old_fragments.start().deleted);
 623
 624            // Preserve any portion of the current fragment that precedes this range.
 625            if fragment_start < range.start {
 626                let mut prefix = old_fragments.item().unwrap().clone();
 627                prefix.len = range.start - fragment_start;
 628                prefix.insertion_offset += fragment_start - old_fragments.start().visible;
 629
 630                // log::info!(
 631                //     "pushing prefix between {:?} and {:?}",
 632                //     new_fragments.summary().max_id,
 633                //     prefix.id
 634                // );
 635                prefix.id = Locator::between(&new_fragments.summary().max_id, &prefix.id);
 636                new_insertions.push(InsertionFragment::insert_new(&prefix));
 637                new_ropes.push_fragment(&prefix, prefix.visible);
 638                new_fragments.push(prefix, &None);
 639                fragment_start = range.start;
 640            }
 641
 642            // Insert the new text before any existing fragments within the range.
 643            if let Some(new_text) = new_text.as_deref() {
 644                let new_start = new_fragments.summary().text.visible;
 645                edits.push(Edit {
 646                    old: fragment_start..fragment_start,
 647                    new: new_start..new_start + new_text.len(),
 648                });
 649
 650                // log::info!(
 651                //     "pushing new fragment between {:?} and {:?}",
 652                //     new_fragments.summary().max_id,
 653                //     old_fragments
 654                //         .item()
 655                //         .map_or(&Locator::max(), |old_fragment| &old_fragment.id)
 656                // );
 657
 658                let fragment = Fragment {
 659                    id: Locator::between(
 660                        &new_fragments.summary().max_id,
 661                        old_fragments
 662                            .item()
 663                            .map_or(&Locator::max(), |old_fragment| &old_fragment.id),
 664                    ),
 665                    insertion_timestamp: timestamp,
 666                    insertion_offset: 0,
 667                    len: new_text.len(),
 668                    deletions: Default::default(),
 669                    max_undos: Default::default(),
 670                    visible: true,
 671                };
 672                new_insertions.push(InsertionFragment::insert_new(&fragment));
 673                new_ropes.push_str(new_text);
 674                new_fragments.push(fragment, &None);
 675            }
 676
 677            // Advance through every fragment that intersects this range, marking the intersecting
 678            // portions as deleted.
 679            while fragment_start < range.end {
 680                let fragment = old_fragments.item().unwrap();
 681                let fragment_end = old_fragments.end(&None).visible;
 682                let mut intersection = fragment.clone();
 683                let intersection_end = cmp::min(range.end, fragment_end);
 684                if fragment.visible {
 685                    intersection.len = intersection_end - fragment_start;
 686                    intersection.id =
 687                        Locator::between(&new_fragments.summary().max_id, &intersection.id);
 688                    intersection.deletions.insert(timestamp.local());
 689                    intersection.visible = false;
 690                }
 691                if intersection.len > 0 {
 692                    if fragment.visible && !intersection.visible {
 693                        let new_start = new_fragments.summary().text.visible;
 694                        edits.push(Edit {
 695                            old: fragment_start..intersection_end,
 696                            new: new_start..new_start,
 697                        });
 698                    }
 699                    new_insertions.push(InsertionFragment::insert_new(&intersection));
 700                    new_ropes.push_fragment(&intersection, fragment.visible);
 701                    new_fragments.push(intersection, &None);
 702                    fragment_start = intersection_end;
 703                }
 704                if fragment_end <= range.end {
 705                    old_fragments.next(&None);
 706                }
 707            }
 708
 709            let full_range_end = FullOffset(range.end + old_fragments.start().deleted);
 710            edit_op.ranges.push(full_range_start..full_range_end);
 711        }
 712
 713        // If the current fragment has been partially consumed, then consume the rest of it
 714        // and advance to the next fragment before slicing.
 715        if fragment_start > old_fragments.start().visible {
 716            let fragment_end = old_fragments.end(&None).visible;
 717            if fragment_end > fragment_start {
 718                let mut suffix = old_fragments.item().unwrap().clone();
 719                suffix.len = fragment_end - fragment_start;
 720                suffix.insertion_offset += fragment_start - old_fragments.start().visible;
 721                new_insertions.push(InsertionFragment::insert_new(&suffix));
 722                new_ropes.push_fragment(&suffix, suffix.visible);
 723                new_fragments.push(suffix, &None);
 724            }
 725            old_fragments.next(&None);
 726        }
 727
 728        let suffix = old_fragments.suffix(&None);
 729        new_ropes.push_tree(suffix.summary().text);
 730        new_fragments.push_tree(suffix, &None);
 731        let (visible_text, deleted_text) = new_ropes.finish();
 732        drop(old_fragments);
 733
 734        self.snapshot.fragments = new_fragments;
 735        self.snapshot.insertions.edit(new_insertions, &());
 736        self.snapshot.visible_text = visible_text;
 737        self.snapshot.deleted_text = deleted_text;
 738        self.update_subscriptions(edits);
 739        edit_op.new_text = new_text;
 740        edit_op
 741    }
 742
 743    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I) -> Result<()> {
 744        let mut deferred_ops = Vec::new();
 745        for op in ops {
 746            if self.can_apply_op(&op) {
 747                self.apply_op(op)?;
 748            } else {
 749                self.deferred_replicas.insert(op.replica_id());
 750                deferred_ops.push(op);
 751            }
 752        }
 753        self.deferred_ops.insert(deferred_ops);
 754        self.flush_deferred_ops()?;
 755        Ok(())
 756    }
 757
 758    fn apply_op(&mut self, op: Operation) -> Result<()> {
 759        match op {
 760            Operation::Edit(edit) => {
 761                if !self.version.observed(edit.timestamp.local()) {
 762                    self.apply_remote_edit(
 763                        &edit.version,
 764                        &edit.ranges,
 765                        edit.new_text.as_deref(),
 766                        edit.timestamp,
 767                    );
 768                    self.snapshot.version.observe(edit.timestamp.local());
 769                    self.history.push(edit);
 770                }
 771            }
 772            Operation::Undo {
 773                undo,
 774                lamport_timestamp,
 775            } => {
 776                if !self.version.observed(undo.id) {
 777                    self.apply_undo(&undo)?;
 778                    self.snapshot.version.observe(undo.id);
 779                    self.lamport_clock.observe(lamport_timestamp);
 780                }
 781            }
 782            Operation::UpdateSelections {
 783                set_id,
 784                selections,
 785                lamport_timestamp,
 786            } => {
 787                if let Some(set) = self.selections.get_mut(&set_id) {
 788                    set.selections = selections;
 789                } else {
 790                    self.selections.insert(
 791                        set_id,
 792                        SelectionSet {
 793                            id: set_id,
 794                            selections,
 795                            active: false,
 796                        },
 797                    );
 798                }
 799                self.lamport_clock.observe(lamport_timestamp);
 800            }
 801            Operation::RemoveSelections {
 802                set_id,
 803                lamport_timestamp,
 804            } => {
 805                self.selections.remove(&set_id);
 806                self.lamport_clock.observe(lamport_timestamp);
 807            }
 808            Operation::SetActiveSelections {
 809                set_id,
 810                lamport_timestamp,
 811            } => {
 812                for (id, set) in &mut self.selections {
 813                    if id.replica_id == lamport_timestamp.replica_id {
 814                        if Some(*id) == set_id {
 815                            set.active = true;
 816                        } else {
 817                            set.active = false;
 818                        }
 819                    }
 820                }
 821                self.lamport_clock.observe(lamport_timestamp);
 822            }
 823            #[cfg(test)]
 824            Operation::Test(_) => {}
 825        }
 826        Ok(())
 827    }
 828
 829    fn apply_remote_edit(
 830        &mut self,
 831        version: &clock::Global,
 832        ranges: &[Range<FullOffset>],
 833        new_text: Option<&str>,
 834        timestamp: InsertionTimestamp,
 835    ) {
 836        if ranges.is_empty() {
 837            return;
 838        }
 839
 840        let mut edits = Patch::default();
 841        let cx = Some(version.clone());
 842        let mut new_ropes =
 843            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
 844        let mut old_fragments = self.fragments.cursor::<(VersionedFullOffset, usize)>();
 845        let mut new_fragments = old_fragments.slice(
 846            &VersionedFullOffset::Offset(ranges[0].start),
 847            Bias::Left,
 848            &cx,
 849        );
 850        new_ropes.push_tree(new_fragments.summary().text);
 851
 852        let mut fragment_start = old_fragments.start().0.full_offset();
 853        for range in ranges {
 854            let fragment_end = old_fragments.end(&cx).0.full_offset();
 855
 856            // If the current fragment ends before this range, then jump ahead to the first fragment
 857            // that extends past the start of this range, reusing any intervening fragments.
 858            if fragment_end < range.start {
 859                // If the current fragment has been partially consumed, then consume the rest of it
 860                // and advance to the next fragment before slicing.
 861                if fragment_start > old_fragments.start().0.full_offset() {
 862                    if fragment_end > fragment_start {
 863                        let mut suffix = old_fragments.item().unwrap().clone();
 864                        suffix.len = fragment_end.0 - fragment_start.0;
 865                        new_ropes.push_fragment(&suffix, suffix.visible);
 866                        new_fragments.push(suffix, &None);
 867                    }
 868                    old_fragments.next(&cx);
 869                }
 870
 871                let slice =
 872                    old_fragments.slice(&VersionedFullOffset::Offset(range.start), Bias::Left, &cx);
 873                new_ropes.push_tree(slice.summary().text);
 874                new_fragments.push_tree(slice, &None);
 875                fragment_start = old_fragments.start().0.full_offset();
 876            }
 877
 878            // If we are at the end of a non-concurrent fragment, advance to the next one.
 879            let fragment_end = old_fragments.end(&cx).0.full_offset();
 880            if fragment_end == range.start && fragment_end > fragment_start {
 881                let mut fragment = old_fragments.item().unwrap().clone();
 882                fragment.len = fragment_end.0 - fragment_start.0;
 883                new_ropes.push_fragment(&fragment, fragment.visible);
 884                new_fragments.push(fragment, &None);
 885                old_fragments.next(&cx);
 886                fragment_start = old_fragments.start().0.full_offset();
 887            }
 888
 889            // Skip over insertions that are concurrent to this edit, but have a lower lamport
 890            // timestamp.
 891            while let Some(fragment) = old_fragments.item() {
 892                if fragment_start == range.start
 893                    && fragment.insertion_timestamp.lamport() > timestamp.lamport()
 894                {
 895                    new_ropes.push_fragment(fragment, fragment.visible);
 896                    new_fragments.push(fragment.clone(), &None);
 897                    old_fragments.next(&cx);
 898                    debug_assert_eq!(fragment_start, range.start);
 899                } else {
 900                    break;
 901                }
 902            }
 903            debug_assert!(fragment_start <= range.start);
 904
 905            // Preserve any portion of the current fragment that precedes this range.
 906            if fragment_start < range.start {
 907                let mut prefix = old_fragments.item().unwrap().clone();
 908                prefix.len = range.start.0 - fragment_start.0;
 909                fragment_start = range.start;
 910                new_ropes.push_fragment(&prefix, prefix.visible);
 911                new_fragments.push(prefix, &None);
 912            }
 913
 914            // Insert the new text before any existing fragments within the range.
 915            if let Some(new_text) = new_text {
 916                let mut old_start = old_fragments.start().1;
 917                if old_fragments.item().map_or(false, |f| f.visible) {
 918                    old_start += fragment_start.0 - old_fragments.start().0.full_offset().0;
 919                }
 920                let new_start = new_fragments.summary().text.visible;
 921                edits.push(Edit {
 922                    old: old_start..old_start,
 923                    new: new_start..new_start + new_text.len(),
 924                });
 925                new_ropes.push_str(new_text);
 926                new_fragments.push(
 927                    Fragment {
 928                        id: todo!(),
 929                        insertion_timestamp: timestamp,
 930                        insertion_offset: todo!(),
 931                        len: new_text.len(),
 932                        deletions: Default::default(),
 933                        max_undos: Default::default(),
 934                        visible: true,
 935                    },
 936                    &None,
 937                );
 938            }
 939
 940            // Advance through every fragment that intersects this range, marking the intersecting
 941            // portions as deleted.
 942            while fragment_start < range.end {
 943                let fragment = old_fragments.item().unwrap();
 944                let fragment_end = old_fragments.end(&cx).0.full_offset();
 945                let mut intersection = fragment.clone();
 946                let intersection_end = cmp::min(range.end, fragment_end);
 947                if fragment.was_visible(version, &self.undo_map) {
 948                    intersection.len = intersection_end.0 - fragment_start.0;
 949                    intersection.deletions.insert(timestamp.local());
 950                    intersection.visible = false;
 951                }
 952                if intersection.len > 0 {
 953                    if fragment.visible && !intersection.visible {
 954                        let old_start = old_fragments.start().1
 955                            + (fragment_start.0 - old_fragments.start().0.full_offset().0);
 956                        let new_start = new_fragments.summary().text.visible;
 957                        edits.push(Edit {
 958                            old: old_start..old_start + intersection.len,
 959                            new: new_start..new_start,
 960                        });
 961                    }
 962                    new_ropes.push_fragment(&intersection, fragment.visible);
 963                    new_fragments.push(intersection, &None);
 964                    fragment_start = intersection_end;
 965                }
 966                if fragment_end <= range.end {
 967                    old_fragments.next(&cx);
 968                }
 969            }
 970        }
 971
 972        // If the current fragment has been partially consumed, then consume the rest of it
 973        // and advance to the next fragment before slicing.
 974        if fragment_start > old_fragments.start().0.full_offset() {
 975            let fragment_end = old_fragments.end(&cx).0.full_offset();
 976            if fragment_end > fragment_start {
 977                let mut suffix = old_fragments.item().unwrap().clone();
 978                suffix.len = fragment_end.0 - fragment_start.0;
 979                new_ropes.push_fragment(&suffix, suffix.visible);
 980                new_fragments.push(suffix, &None);
 981            }
 982            old_fragments.next(&cx);
 983        }
 984
 985        let suffix = old_fragments.suffix(&cx);
 986        new_ropes.push_tree(suffix.summary().text);
 987        new_fragments.push_tree(suffix, &None);
 988        let (visible_text, deleted_text) = new_ropes.finish();
 989        drop(old_fragments);
 990
 991        self.snapshot.fragments = new_fragments;
 992        self.snapshot.visible_text = visible_text;
 993        self.snapshot.deleted_text = deleted_text;
 994        self.local_clock.observe(timestamp.local());
 995        self.lamport_clock.observe(timestamp.lamport());
 996        self.update_subscriptions(edits);
 997    }
 998
 999    fn apply_undo(&mut self, undo: &UndoOperation) -> Result<()> {
1000        let mut edits = Patch::default();
1001        self.snapshot.undo_map.insert(undo);
1002
1003        let mut cx = undo.version.clone();
1004        for edit_id in undo.counts.keys().copied() {
1005            cx.observe(edit_id);
1006        }
1007        let cx = Some(cx);
1008
1009        let mut old_fragments = self.fragments.cursor::<(VersionedFullOffset, usize)>();
1010        let mut new_fragments = old_fragments.slice(
1011            &VersionedFullOffset::Offset(undo.ranges[0].start),
1012            Bias::Right,
1013            &cx,
1014        );
1015        let mut new_ropes =
1016            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
1017        new_ropes.push_tree(new_fragments.summary().text);
1018
1019        for range in &undo.ranges {
1020            let mut end_offset = old_fragments.end(&cx).0.full_offset();
1021
1022            if end_offset < range.start {
1023                let preceding_fragments = old_fragments.slice(
1024                    &VersionedFullOffset::Offset(range.start),
1025                    Bias::Right,
1026                    &cx,
1027                );
1028                new_ropes.push_tree(preceding_fragments.summary().text);
1029                new_fragments.push_tree(preceding_fragments, &None);
1030            }
1031
1032            while end_offset <= range.end {
1033                if let Some(fragment) = old_fragments.item() {
1034                    let mut fragment = fragment.clone();
1035                    let fragment_was_visible = fragment.visible;
1036
1037                    if fragment.was_visible(&undo.version, &self.undo_map)
1038                        || undo
1039                            .counts
1040                            .contains_key(&fragment.insertion_timestamp.local())
1041                    {
1042                        fragment.visible = fragment.is_visible(&self.undo_map);
1043                        fragment.max_undos.observe(undo.id);
1044                    }
1045
1046                    let old_start = old_fragments.start().1;
1047                    let new_start = new_fragments.summary().text.visible;
1048                    if fragment_was_visible && !fragment.visible {
1049                        edits.push(Edit {
1050                            old: old_start..old_start + fragment.len,
1051                            new: new_start..new_start,
1052                        });
1053                    } else if !fragment_was_visible && fragment.visible {
1054                        edits.push(Edit {
1055                            old: old_start..old_start,
1056                            new: new_start..new_start + fragment.len,
1057                        });
1058                    }
1059                    new_ropes.push_fragment(&fragment, fragment_was_visible);
1060                    new_fragments.push(fragment, &None);
1061
1062                    old_fragments.next(&cx);
1063                    if end_offset == old_fragments.end(&cx).0.full_offset() {
1064                        let unseen_fragments = old_fragments.slice(
1065                            &VersionedFullOffset::Offset(end_offset),
1066                            Bias::Right,
1067                            &cx,
1068                        );
1069                        new_ropes.push_tree(unseen_fragments.summary().text);
1070                        new_fragments.push_tree(unseen_fragments, &None);
1071                    }
1072                    end_offset = old_fragments.end(&cx).0.full_offset();
1073                } else {
1074                    break;
1075                }
1076            }
1077        }
1078
1079        let suffix = old_fragments.suffix(&cx);
1080        new_ropes.push_tree(suffix.summary().text);
1081        new_fragments.push_tree(suffix, &None);
1082
1083        drop(old_fragments);
1084        let (visible_text, deleted_text) = new_ropes.finish();
1085        self.snapshot.fragments = new_fragments;
1086        self.snapshot.visible_text = visible_text;
1087        self.snapshot.deleted_text = deleted_text;
1088        self.update_subscriptions(edits);
1089        Ok(())
1090    }
1091
1092    fn flush_deferred_ops(&mut self) -> Result<()> {
1093        self.deferred_replicas.clear();
1094        let mut deferred_ops = Vec::new();
1095        for op in self.deferred_ops.drain().cursor().cloned() {
1096            if self.can_apply_op(&op) {
1097                self.apply_op(op)?;
1098            } else {
1099                self.deferred_replicas.insert(op.replica_id());
1100                deferred_ops.push(op);
1101            }
1102        }
1103        self.deferred_ops.insert(deferred_ops);
1104        Ok(())
1105    }
1106
1107    fn can_apply_op(&self, op: &Operation) -> bool {
1108        if self.deferred_replicas.contains(&op.replica_id()) {
1109            false
1110        } else {
1111            match op {
1112                Operation::Edit(edit) => self.version.ge(&edit.version),
1113                Operation::Undo { undo, .. } => self.version.ge(&undo.version),
1114                Operation::UpdateSelections { selections, .. } => {
1115                    self.version.ge(selections.version())
1116                }
1117                Operation::RemoveSelections { .. } => true,
1118                Operation::SetActiveSelections { set_id, .. } => {
1119                    set_id.map_or(true, |set_id| self.selections.contains_key(&set_id))
1120                }
1121                #[cfg(test)]
1122                Operation::Test(_) => true,
1123            }
1124        }
1125    }
1126
1127    pub fn peek_undo_stack(&self) -> Option<&Transaction> {
1128        self.history.undo_stack.last()
1129    }
1130
1131    pub fn start_transaction(
1132        &mut self,
1133        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1134    ) -> Result<()> {
1135        self.start_transaction_at(selection_set_ids, Instant::now())
1136    }
1137
1138    pub fn start_transaction_at(
1139        &mut self,
1140        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1141        now: Instant,
1142    ) -> Result<()> {
1143        let selections = selection_set_ids
1144            .into_iter()
1145            .map(|set_id| {
1146                let set = self
1147                    .selections
1148                    .get(&set_id)
1149                    .expect("invalid selection set id");
1150                (set_id, set.selections.clone())
1151            })
1152            .collect();
1153        self.history
1154            .start_transaction(self.version.clone(), selections, now);
1155        Ok(())
1156    }
1157
1158    pub fn end_transaction(&mut self, selection_set_ids: impl IntoIterator<Item = SelectionSetId>) {
1159        self.end_transaction_at(selection_set_ids, Instant::now());
1160    }
1161
1162    pub fn end_transaction_at(
1163        &mut self,
1164        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1165        now: Instant,
1166    ) -> Option<clock::Global> {
1167        let selections = selection_set_ids
1168            .into_iter()
1169            .map(|set_id| {
1170                let set = self
1171                    .selections
1172                    .get(&set_id)
1173                    .expect("invalid selection set id");
1174                (set_id, set.selections.clone())
1175            })
1176            .collect();
1177
1178        if let Some(transaction) = self.history.end_transaction(selections, now) {
1179            let since = transaction.start.clone();
1180            self.history.group();
1181            Some(since)
1182        } else {
1183            None
1184        }
1185    }
1186
1187    pub fn remove_peer(&mut self, replica_id: ReplicaId) {
1188        self.selections
1189            .retain(|set_id, _| set_id.replica_id != replica_id)
1190    }
1191
1192    pub fn base_text(&self) -> &Arc<str> {
1193        &self.history.base_text
1194    }
1195
1196    pub fn history(&self) -> impl Iterator<Item = &EditOperation> {
1197        self.history.ops.values()
1198    }
1199
1200    pub fn undo(&mut self) -> Vec<Operation> {
1201        let mut ops = Vec::new();
1202        if let Some(transaction) = self.history.pop_undo().cloned() {
1203            let selections = transaction.selections_before.clone();
1204            ops.push(self.undo_or_redo(transaction).unwrap());
1205            for (set_id, selections) in selections {
1206                ops.extend(self.restore_selection_set(set_id, selections));
1207            }
1208        }
1209        ops
1210    }
1211
1212    pub fn redo(&mut self) -> Vec<Operation> {
1213        let mut ops = Vec::new();
1214        if let Some(transaction) = self.history.pop_redo().cloned() {
1215            let selections = transaction.selections_after.clone();
1216            ops.push(self.undo_or_redo(transaction).unwrap());
1217            for (set_id, selections) in selections {
1218                ops.extend(self.restore_selection_set(set_id, selections));
1219            }
1220        }
1221        ops
1222    }
1223
1224    fn undo_or_redo(&mut self, transaction: Transaction) -> Result<Operation> {
1225        let mut counts = HashMap::default();
1226        for edit_id in transaction.edits {
1227            counts.insert(edit_id, self.undo_map.undo_count(edit_id) + 1);
1228        }
1229
1230        let undo = UndoOperation {
1231            id: self.local_clock.tick(),
1232            counts,
1233            ranges: transaction.ranges,
1234            version: transaction.start.clone(),
1235        };
1236        self.apply_undo(&undo)?;
1237        self.snapshot.version.observe(undo.id);
1238
1239        Ok(Operation::Undo {
1240            undo,
1241            lamport_timestamp: self.lamport_clock.tick(),
1242        })
1243    }
1244
1245    pub fn subscribe(&mut self) -> Subscription {
1246        let subscription = Subscription(Default::default());
1247        self.subscriptions.push(Arc::downgrade(&subscription.0));
1248        subscription
1249    }
1250
1251    fn update_subscriptions(&mut self, edits: Patch<usize>) {
1252        self.subscriptions.retain(|subscription| {
1253            if let Some(subscription) = subscription.upgrade() {
1254                subscription.lock().push(edits.clone());
1255                true
1256            } else {
1257                false
1258            }
1259        });
1260    }
1261
1262    pub fn selection_set(&self, set_id: SelectionSetId) -> Result<&SelectionSet> {
1263        self.selections
1264            .get(&set_id)
1265            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))
1266    }
1267
1268    pub fn selection_sets(&self) -> impl Iterator<Item = (&SelectionSetId, &SelectionSet)> {
1269        self.selections.iter()
1270    }
1271
1272    fn build_selection_anchor_range_map<T: ToOffset>(
1273        &self,
1274        selections: &[Selection<T>],
1275    ) -> Arc<AnchorRangeMap<SelectionState>> {
1276        Arc::new(self.anchor_range_map(
1277            Bias::Left,
1278            Bias::Left,
1279            selections.iter().map(|selection| {
1280                let start = selection.start.to_offset(self);
1281                let end = selection.end.to_offset(self);
1282                let range = start..end;
1283                let state = SelectionState {
1284                    id: selection.id,
1285                    reversed: selection.reversed,
1286                    goal: selection.goal,
1287                };
1288                (range, state)
1289            }),
1290        ))
1291    }
1292
1293    pub fn update_selection_set<T: ToOffset>(
1294        &mut self,
1295        set_id: SelectionSetId,
1296        selections: &[Selection<T>],
1297    ) -> Result<Operation> {
1298        let selections = self.build_selection_anchor_range_map(selections);
1299        let set = self
1300            .selections
1301            .get_mut(&set_id)
1302            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1303        set.selections = selections.clone();
1304        Ok(Operation::UpdateSelections {
1305            set_id,
1306            selections,
1307            lamport_timestamp: self.lamport_clock.tick(),
1308        })
1309    }
1310
1311    pub fn restore_selection_set(
1312        &mut self,
1313        set_id: SelectionSetId,
1314        selections: Arc<AnchorRangeMap<SelectionState>>,
1315    ) -> Result<Operation> {
1316        let set = self
1317            .selections
1318            .get_mut(&set_id)
1319            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1320        set.selections = selections.clone();
1321        Ok(Operation::UpdateSelections {
1322            set_id,
1323            selections,
1324            lamport_timestamp: self.lamport_clock.tick(),
1325        })
1326    }
1327
1328    pub fn add_selection_set<T: ToOffset>(&mut self, selections: &[Selection<T>]) -> Operation {
1329        let selections = self.build_selection_anchor_range_map(selections);
1330        let set_id = self.lamport_clock.tick();
1331        self.selections.insert(
1332            set_id,
1333            SelectionSet {
1334                id: set_id,
1335                selections: selections.clone(),
1336                active: false,
1337            },
1338        );
1339        Operation::UpdateSelections {
1340            set_id,
1341            selections,
1342            lamport_timestamp: set_id,
1343        }
1344    }
1345
1346    pub fn add_raw_selection_set(&mut self, id: SelectionSetId, selections: SelectionSet) {
1347        self.selections.insert(id, selections);
1348    }
1349
1350    pub fn set_active_selection_set(
1351        &mut self,
1352        set_id: Option<SelectionSetId>,
1353    ) -> Result<Operation> {
1354        if let Some(set_id) = set_id {
1355            assert_eq!(set_id.replica_id, self.replica_id());
1356        }
1357
1358        for (id, set) in &mut self.selections {
1359            if id.replica_id == self.local_clock.replica_id {
1360                if Some(*id) == set_id {
1361                    set.active = true;
1362                } else {
1363                    set.active = false;
1364                }
1365            }
1366        }
1367
1368        Ok(Operation::SetActiveSelections {
1369            set_id,
1370            lamport_timestamp: self.lamport_clock.tick(),
1371        })
1372    }
1373
1374    pub fn remove_selection_set(&mut self, set_id: SelectionSetId) -> Result<Operation> {
1375        self.selections
1376            .remove(&set_id)
1377            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1378        Ok(Operation::RemoveSelections {
1379            set_id,
1380            lamport_timestamp: self.lamport_clock.tick(),
1381        })
1382    }
1383}
1384
1385#[cfg(any(test, feature = "test-support"))]
1386impl Buffer {
1387    fn random_byte_range(&mut self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
1388        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
1389        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
1390        start..end
1391    }
1392
1393    pub fn randomly_edit<T>(
1394        &mut self,
1395        rng: &mut T,
1396        old_range_count: usize,
1397    ) -> (Vec<Range<usize>>, String, Operation)
1398    where
1399        T: rand::Rng,
1400    {
1401        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1402        for _ in 0..old_range_count {
1403            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1404            if last_end > self.len() {
1405                break;
1406            }
1407            old_ranges.push(self.random_byte_range(last_end, rng));
1408        }
1409        let new_text_len = rng.gen_range(0..10);
1410        let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1411            .take(new_text_len)
1412            .collect();
1413        log::info!(
1414            "mutating buffer {} at {:?}: {:?}",
1415            self.replica_id,
1416            old_ranges,
1417            new_text
1418        );
1419        let op = self.edit(old_ranges.iter().cloned(), new_text.as_str());
1420        (old_ranges, new_text, Operation::Edit(op))
1421    }
1422
1423    pub fn randomly_mutate<T>(&mut self, rng: &mut T) -> Vec<Operation>
1424    where
1425        T: rand::Rng,
1426    {
1427        use rand::prelude::*;
1428
1429        let mut ops = vec![self.randomly_edit(rng, 5).2];
1430
1431        // Randomly add, remove or mutate selection sets.
1432        let replica_selection_sets = &self
1433            .selection_sets()
1434            .map(|(set_id, _)| *set_id)
1435            .filter(|set_id| self.replica_id == set_id.replica_id)
1436            .collect::<Vec<_>>();
1437        let set_id = replica_selection_sets.choose(rng);
1438        if set_id.is_some() && rng.gen_bool(1.0 / 6.0) {
1439            ops.push(self.remove_selection_set(*set_id.unwrap()).unwrap());
1440        } else {
1441            let mut ranges = Vec::new();
1442            for _ in 0..5 {
1443                ranges.push(self.random_byte_range(0, rng));
1444            }
1445            let new_selections = self.selections_from_ranges(ranges).unwrap();
1446
1447            let op = if set_id.is_none() || rng.gen_bool(1.0 / 5.0) {
1448                self.add_selection_set(&new_selections)
1449            } else {
1450                self.update_selection_set(*set_id.unwrap(), &new_selections)
1451                    .unwrap()
1452            };
1453            ops.push(op);
1454        }
1455
1456        ops
1457    }
1458
1459    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng) -> Vec<Operation> {
1460        use rand::prelude::*;
1461
1462        let mut ops = Vec::new();
1463        for _ in 0..rng.gen_range(1..=5) {
1464            if let Some(transaction) = self.history.undo_stack.choose(rng).cloned() {
1465                log::info!(
1466                    "undoing buffer {} transaction {:?}",
1467                    self.replica_id,
1468                    transaction
1469                );
1470                ops.push(self.undo_or_redo(transaction).unwrap());
1471            }
1472        }
1473        ops
1474    }
1475
1476    fn selections_from_ranges<I>(&self, ranges: I) -> Result<Vec<Selection<usize>>>
1477    where
1478        I: IntoIterator<Item = Range<usize>>,
1479    {
1480        use std::sync::atomic::{self, AtomicUsize};
1481
1482        static NEXT_SELECTION_ID: AtomicUsize = AtomicUsize::new(0);
1483
1484        let mut ranges = ranges.into_iter().collect::<Vec<_>>();
1485        ranges.sort_unstable_by_key(|range| range.start);
1486
1487        let mut selections = Vec::<Selection<usize>>::with_capacity(ranges.len());
1488        for mut range in ranges {
1489            let mut reversed = false;
1490            if range.start > range.end {
1491                reversed = true;
1492                std::mem::swap(&mut range.start, &mut range.end);
1493            }
1494
1495            if let Some(selection) = selections.last_mut() {
1496                if selection.end >= range.start {
1497                    selection.end = range.end;
1498                    continue;
1499                }
1500            }
1501
1502            selections.push(Selection {
1503                id: NEXT_SELECTION_ID.fetch_add(1, atomic::Ordering::SeqCst),
1504                start: range.start,
1505                end: range.end,
1506                reversed,
1507                goal: SelectionGoal::None,
1508            });
1509        }
1510        Ok(selections)
1511    }
1512
1513    #[cfg(test)]
1514    pub fn selection_ranges<'a, D>(&'a self, set_id: SelectionSetId) -> Result<Vec<Range<D>>>
1515    where
1516        D: 'a + TextDimension<'a>,
1517    {
1518        Ok(self
1519            .selection_set(set_id)?
1520            .selections(self)
1521            .map(move |selection| {
1522                if selection.reversed {
1523                    selection.end..selection.start
1524                } else {
1525                    selection.start..selection.end
1526                }
1527            })
1528            .collect())
1529    }
1530
1531    #[cfg(test)]
1532    pub fn all_selection_ranges<'a, D>(
1533        &'a self,
1534    ) -> impl 'a + Iterator<Item = (SelectionSetId, Vec<Range<usize>>)>
1535    where
1536        D: 'a + TextDimension<'a>,
1537    {
1538        self.selections
1539            .keys()
1540            .map(move |set_id| (*set_id, self.selection_ranges(*set_id).unwrap()))
1541    }
1542}
1543
1544impl Deref for Buffer {
1545    type Target = Snapshot;
1546
1547    fn deref(&self) -> &Self::Target {
1548        &self.snapshot
1549    }
1550}
1551
1552impl Snapshot {
1553    pub fn as_rope(&self) -> &Rope {
1554        &self.visible_text
1555    }
1556
1557    pub fn row_count(&self) -> u32 {
1558        self.max_point().row + 1
1559    }
1560
1561    pub fn len(&self) -> usize {
1562        self.visible_text.len()
1563    }
1564
1565    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
1566        self.chars_at(0)
1567    }
1568
1569    pub fn chars_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = char> + '_ {
1570        self.text_for_range(range).flat_map(str::chars)
1571    }
1572
1573    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1574    where
1575        T: ToOffset,
1576    {
1577        let position = position.to_offset(self);
1578        position == self.clip_offset(position, Bias::Left)
1579            && self
1580                .bytes_in_range(position..self.len())
1581                .flatten()
1582                .copied()
1583                .take(needle.len())
1584                .eq(needle.bytes())
1585    }
1586
1587    pub fn text(&self) -> String {
1588        self.text_for_range(0..self.len()).collect()
1589    }
1590
1591    pub fn text_summary(&self) -> TextSummary {
1592        self.visible_text.summary()
1593    }
1594
1595    pub fn max_point(&self) -> Point {
1596        self.visible_text.max_point()
1597    }
1598
1599    pub fn to_offset(&self, point: Point) -> usize {
1600        self.visible_text.point_to_offset(point)
1601    }
1602
1603    pub fn to_point(&self, offset: usize) -> Point {
1604        self.visible_text.offset_to_point(offset)
1605    }
1606
1607    pub fn version(&self) -> &clock::Global {
1608        &self.version
1609    }
1610
1611    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1612        let offset = position.to_offset(self);
1613        self.visible_text.chars_at(offset)
1614    }
1615
1616    pub fn reversed_chars_at<'a, T: ToOffset>(
1617        &'a self,
1618        position: T,
1619    ) -> impl Iterator<Item = char> + 'a {
1620        let offset = position.to_offset(self);
1621        self.visible_text.reversed_chars_at(offset)
1622    }
1623
1624    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> rope::Bytes<'a> {
1625        let start = range.start.to_offset(self);
1626        let end = range.end.to_offset(self);
1627        self.visible_text.bytes_in_range(start..end)
1628    }
1629
1630    pub fn text_for_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> Chunks<'a> {
1631        let start = range.start.to_offset(self);
1632        let end = range.end.to_offset(self);
1633        self.visible_text.chunks_in_range(start..end)
1634    }
1635
1636    pub fn line_len(&self, row: u32) -> u32 {
1637        let row_start_offset = Point::new(row, 0).to_offset(self);
1638        let row_end_offset = if row >= self.max_point().row {
1639            self.len()
1640        } else {
1641            Point::new(row + 1, 0).to_offset(self) - 1
1642        };
1643        (row_end_offset - row_start_offset) as u32
1644    }
1645
1646    pub fn is_line_blank(&self, row: u32) -> bool {
1647        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1648            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1649    }
1650
1651    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1652        let mut result = 0;
1653        for c in self.chars_at(Point::new(row, 0)) {
1654            if c == ' ' {
1655                result += 1;
1656            } else {
1657                break;
1658            }
1659        }
1660        result
1661    }
1662
1663    fn summary_for_anchor<'a, D>(&'a self, anchor: &Anchor) -> D
1664    where
1665        D: TextDimension<'a>,
1666    {
1667        let cx = Some(anchor.version.clone());
1668        let mut cursor = self.fragments.cursor::<(VersionedFullOffset, usize)>();
1669        cursor.seek(
1670            &VersionedFullOffset::Offset(anchor.full_offset),
1671            anchor.bias,
1672            &cx,
1673        );
1674        let overshoot = if cursor.item().map_or(false, |fragment| fragment.visible) {
1675            anchor.full_offset - cursor.start().0.full_offset()
1676        } else {
1677            0
1678        };
1679        self.text_summary_for_range(0..cursor.start().1 + overshoot)
1680    }
1681
1682    pub fn text_summary_for_range<'a, D, O: ToOffset>(&'a self, range: Range<O>) -> D
1683    where
1684        D: TextDimension<'a>,
1685    {
1686        self.visible_text
1687            .cursor(range.start.to_offset(self))
1688            .summary(range.end.to_offset(self))
1689    }
1690
1691    fn summaries_for_anchors<'a, D, I>(
1692        &'a self,
1693        version: clock::Global,
1694        bias: Bias,
1695        ranges: I,
1696    ) -> impl 'a + Iterator<Item = D>
1697    where
1698        D: 'a + TextDimension<'a>,
1699        I: 'a + IntoIterator<Item = &'a FullOffset>,
1700    {
1701        let cx = Some(version.clone());
1702        let mut summary = D::default();
1703        let mut rope_cursor = self.visible_text.cursor(0);
1704        let mut cursor = self.fragments.cursor::<(VersionedFullOffset, usize)>();
1705        ranges.into_iter().map(move |offset| {
1706            cursor.seek_forward(&VersionedFullOffset::Offset(*offset), bias, &cx);
1707            let overshoot = if cursor.item().map_or(false, |fragment| fragment.visible) {
1708                *offset - cursor.start().0.full_offset()
1709            } else {
1710                0
1711            };
1712            summary.add_assign(&rope_cursor.summary(cursor.start().1 + overshoot));
1713            summary.clone()
1714        })
1715    }
1716
1717    fn summaries_for_anchor_ranges<'a, D, I>(
1718        &'a self,
1719        version: clock::Global,
1720        start_bias: Bias,
1721        end_bias: Bias,
1722        ranges: I,
1723    ) -> impl 'a + Iterator<Item = Range<D>>
1724    where
1725        D: 'a + TextDimension<'a>,
1726        I: 'a + IntoIterator<Item = &'a Range<FullOffset>>,
1727    {
1728        let cx = Some(version);
1729        let mut summary = D::default();
1730        let mut rope_cursor = self.visible_text.cursor(0);
1731        let mut cursor = self.fragments.cursor::<(VersionedFullOffset, usize)>();
1732        ranges.into_iter().map(move |range| {
1733            cursor.seek_forward(&VersionedFullOffset::Offset(range.start), start_bias, &cx);
1734            let overshoot = if cursor.item().map_or(false, |fragment| fragment.visible) {
1735                range.start - cursor.start().0.full_offset()
1736            } else {
1737                0
1738            };
1739            summary.add_assign(&rope_cursor.summary::<D>(cursor.start().1 + overshoot));
1740            let start_summary = summary.clone();
1741
1742            cursor.seek_forward(&VersionedFullOffset::Offset(range.end), end_bias, &cx);
1743            let overshoot = if cursor.item().map_or(false, |fragment| fragment.visible) {
1744                range.end - cursor.start().0.full_offset()
1745            } else {
1746                0
1747            };
1748            summary.add_assign(&rope_cursor.summary::<D>(cursor.start().1 + overshoot));
1749            let end_summary = summary.clone();
1750
1751            start_summary..end_summary
1752        })
1753    }
1754
1755    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1756        self.anchor_at(position, Bias::Left)
1757    }
1758
1759    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1760        self.anchor_at(position, Bias::Right)
1761    }
1762
1763    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1764        Anchor {
1765            full_offset: position.to_full_offset(self, bias),
1766            bias,
1767            version: self.version.clone(),
1768        }
1769    }
1770
1771    pub fn anchor_map<T, E>(&self, bias: Bias, entries: E) -> AnchorMap<T>
1772    where
1773        E: IntoIterator<Item = (usize, T)>,
1774    {
1775        let version = self.version.clone();
1776        let mut cursor = self.fragments.cursor::<FragmentTextSummary>();
1777        let entries = entries
1778            .into_iter()
1779            .map(|(offset, value)| {
1780                cursor.seek_forward(&offset, bias, &None);
1781                let full_offset = FullOffset(cursor.start().deleted + offset);
1782                (full_offset, value)
1783            })
1784            .collect();
1785
1786        AnchorMap {
1787            version,
1788            bias,
1789            entries,
1790        }
1791    }
1792
1793    pub fn anchor_range_map<T, E>(
1794        &self,
1795        start_bias: Bias,
1796        end_bias: Bias,
1797        entries: E,
1798    ) -> AnchorRangeMap<T>
1799    where
1800        E: IntoIterator<Item = (Range<usize>, T)>,
1801    {
1802        let version = self.version.clone();
1803        let mut cursor = self.fragments.cursor::<FragmentTextSummary>();
1804        let entries = entries
1805            .into_iter()
1806            .map(|(range, value)| {
1807                let Range {
1808                    start: start_offset,
1809                    end: end_offset,
1810                } = range;
1811                cursor.seek_forward(&start_offset, start_bias, &None);
1812                let full_start_offset = FullOffset(cursor.start().deleted + start_offset);
1813                cursor.seek_forward(&end_offset, end_bias, &None);
1814                let full_end_offset = FullOffset(cursor.start().deleted + end_offset);
1815                (full_start_offset..full_end_offset, value)
1816            })
1817            .collect();
1818
1819        AnchorRangeMap {
1820            version,
1821            start_bias,
1822            end_bias,
1823            entries,
1824        }
1825    }
1826
1827    pub fn anchor_set<E>(&self, bias: Bias, entries: E) -> AnchorSet
1828    where
1829        E: IntoIterator<Item = usize>,
1830    {
1831        AnchorSet(self.anchor_map(bias, entries.into_iter().map(|range| (range, ()))))
1832    }
1833
1834    pub fn anchor_range_set<E>(
1835        &self,
1836        start_bias: Bias,
1837        end_bias: Bias,
1838        entries: E,
1839    ) -> AnchorRangeSet
1840    where
1841        E: IntoIterator<Item = Range<usize>>,
1842    {
1843        AnchorRangeSet(self.anchor_range_map(
1844            start_bias,
1845            end_bias,
1846            entries.into_iter().map(|range| (range, ())),
1847        ))
1848    }
1849
1850    pub fn anchor_range_multimap<T, E, O>(
1851        &self,
1852        start_bias: Bias,
1853        end_bias: Bias,
1854        entries: E,
1855    ) -> AnchorRangeMultimap<T>
1856    where
1857        T: Clone,
1858        E: IntoIterator<Item = (Range<O>, T)>,
1859        O: ToOffset,
1860    {
1861        let mut entries = entries
1862            .into_iter()
1863            .map(|(range, value)| AnchorRangeMultimapEntry {
1864                range: FullOffsetRange {
1865                    start: range.start.to_full_offset(self, start_bias),
1866                    end: range.end.to_full_offset(self, end_bias),
1867                },
1868                value,
1869            })
1870            .collect::<Vec<_>>();
1871        entries.sort_unstable_by_key(|i| (i.range.start, Reverse(i.range.end)));
1872        AnchorRangeMultimap {
1873            entries: SumTree::from_iter(entries, &()),
1874            version: self.version.clone(),
1875            start_bias,
1876            end_bias,
1877        }
1878    }
1879
1880    fn full_offset_for_anchor(&self, anchor: &Anchor) -> FullOffset {
1881        let cx = Some(anchor.version.clone());
1882        let mut cursor = self
1883            .fragments
1884            .cursor::<(VersionedFullOffset, FragmentTextSummary)>();
1885        cursor.seek(
1886            &VersionedFullOffset::Offset(anchor.full_offset),
1887            anchor.bias,
1888            &cx,
1889        );
1890        let overshoot = if cursor.item().is_some() {
1891            anchor.full_offset - cursor.start().0.full_offset()
1892        } else {
1893            0
1894        };
1895        let summary = cursor.start().1;
1896        FullOffset(summary.visible + summary.deleted + overshoot)
1897    }
1898
1899    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1900        self.visible_text.clip_offset(offset, bias)
1901    }
1902
1903    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1904        self.visible_text.clip_point(point, bias)
1905    }
1906
1907    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1908        self.visible_text.clip_point_utf16(point, bias)
1909    }
1910
1911    pub fn point_for_offset(&self, offset: usize) -> Result<Point> {
1912        if offset <= self.len() {
1913            Ok(self.text_summary_for_range(0..offset))
1914        } else {
1915            Err(anyhow!("offset out of bounds"))
1916        }
1917    }
1918
1919    pub fn edits_since<'a, D>(
1920        &'a self,
1921        since: &'a clock::Global,
1922    ) -> impl 'a + Iterator<Item = Edit<D>>
1923    where
1924        D: 'a + TextDimension<'a> + Ord,
1925    {
1926        let fragments_cursor = if *since == self.version {
1927            None
1928        } else {
1929            Some(
1930                self.fragments
1931                    .filter(move |summary| !since.ge(&summary.max_version), &None),
1932            )
1933        };
1934
1935        Edits {
1936            visible_cursor: self.visible_text.cursor(0),
1937            deleted_cursor: self.deleted_text.cursor(0),
1938            fragments_cursor,
1939            undos: &self.undo_map,
1940            since,
1941            old_end: Default::default(),
1942            new_end: Default::default(),
1943        }
1944    }
1945}
1946
1947struct RopeBuilder<'a> {
1948    old_visible_cursor: rope::Cursor<'a>,
1949    old_deleted_cursor: rope::Cursor<'a>,
1950    new_visible: Rope,
1951    new_deleted: Rope,
1952}
1953
1954impl<'a> RopeBuilder<'a> {
1955    fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
1956        Self {
1957            old_visible_cursor,
1958            old_deleted_cursor,
1959            new_visible: Rope::new(),
1960            new_deleted: Rope::new(),
1961        }
1962    }
1963
1964    fn push_tree(&mut self, len: FragmentTextSummary) {
1965        self.push(len.visible, true, true);
1966        self.push(len.deleted, false, false);
1967    }
1968
1969    fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
1970        debug_assert!(fragment.len > 0);
1971        self.push(fragment.len, was_visible, fragment.visible)
1972    }
1973
1974    fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
1975        let text = if was_visible {
1976            self.old_visible_cursor
1977                .slice(self.old_visible_cursor.offset() + len)
1978        } else {
1979            self.old_deleted_cursor
1980                .slice(self.old_deleted_cursor.offset() + len)
1981        };
1982        if is_visible {
1983            self.new_visible.append(text);
1984        } else {
1985            self.new_deleted.append(text);
1986        }
1987    }
1988
1989    fn push_str(&mut self, text: &str) {
1990        self.new_visible.push(text);
1991    }
1992
1993    fn finish(mut self) -> (Rope, Rope) {
1994        self.new_visible.append(self.old_visible_cursor.suffix());
1995        self.new_deleted.append(self.old_deleted_cursor.suffix());
1996        (self.new_visible, self.new_deleted)
1997    }
1998}
1999
2000impl<'a, D: TextDimension<'a> + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator
2001    for Edits<'a, D, F>
2002{
2003    type Item = Edit<D>;
2004
2005    fn next(&mut self) -> Option<Self::Item> {
2006        let mut pending_edit: Option<Edit<D>> = None;
2007        let cursor = self.fragments_cursor.as_mut()?;
2008
2009        while let Some(fragment) = cursor.item() {
2010            let summary = self.visible_cursor.summary(cursor.start().visible);
2011            self.old_end.add_assign(&summary);
2012            self.new_end.add_assign(&summary);
2013            if pending_edit
2014                .as_ref()
2015                .map_or(false, |change| change.new.end < self.new_end)
2016            {
2017                break;
2018            }
2019
2020            if !fragment.was_visible(&self.since, &self.undos) && fragment.visible {
2021                let fragment_summary = self.visible_cursor.summary(cursor.end(&None).visible);
2022                let mut new_end = self.new_end.clone();
2023                new_end.add_assign(&fragment_summary);
2024                if let Some(pending_edit) = pending_edit.as_mut() {
2025                    pending_edit.new.end = new_end.clone();
2026                } else {
2027                    pending_edit = Some(Edit {
2028                        old: self.old_end.clone()..self.old_end.clone(),
2029                        new: self.new_end.clone()..new_end.clone(),
2030                    });
2031                }
2032
2033                self.new_end = new_end;
2034            } else if fragment.was_visible(&self.since, &self.undos) && !fragment.visible {
2035                self.deleted_cursor.seek_forward(cursor.start().deleted);
2036                let fragment_summary = self.deleted_cursor.summary(cursor.end(&None).deleted);
2037                let mut old_end = self.old_end.clone();
2038                old_end.add_assign(&fragment_summary);
2039                if let Some(pending_edit) = pending_edit.as_mut() {
2040                    pending_edit.old.end = old_end.clone();
2041                } else {
2042                    pending_edit = Some(Edit {
2043                        old: self.old_end.clone()..old_end.clone(),
2044                        new: self.new_end.clone()..self.new_end.clone(),
2045                    });
2046                }
2047
2048                self.old_end = old_end;
2049            }
2050
2051            cursor.next(&None);
2052        }
2053
2054        pending_edit
2055    }
2056}
2057
2058impl Fragment {
2059    fn is_visible(&self, undos: &UndoMap) -> bool {
2060        !undos.is_undone(self.insertion_timestamp.local())
2061            && self.deletions.iter().all(|d| undos.is_undone(*d))
2062    }
2063
2064    fn was_visible(&self, version: &clock::Global, undos: &UndoMap) -> bool {
2065        (version.observed(self.insertion_timestamp.local())
2066            && !undos.was_undone(self.insertion_timestamp.local(), version))
2067            && self
2068                .deletions
2069                .iter()
2070                .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
2071    }
2072}
2073
2074impl sum_tree::Item for Fragment {
2075    type Summary = FragmentSummary;
2076
2077    fn summary(&self) -> Self::Summary {
2078        let mut max_version = clock::Global::new();
2079        max_version.observe(self.insertion_timestamp.local());
2080        for deletion in &self.deletions {
2081            max_version.observe(*deletion);
2082        }
2083        max_version.join(&self.max_undos);
2084
2085        let mut min_insertion_version = clock::Global::new();
2086        min_insertion_version.observe(self.insertion_timestamp.local());
2087        let max_insertion_version = min_insertion_version.clone();
2088        if self.visible {
2089            FragmentSummary {
2090                max_id: self.id.clone(),
2091                text: FragmentTextSummary {
2092                    visible: self.len,
2093                    deleted: 0,
2094                },
2095                max_version,
2096                min_insertion_version,
2097                max_insertion_version,
2098            }
2099        } else {
2100            FragmentSummary {
2101                max_id: self.id.clone(),
2102                text: FragmentTextSummary {
2103                    visible: 0,
2104                    deleted: self.len,
2105                },
2106                max_version,
2107                min_insertion_version,
2108                max_insertion_version,
2109            }
2110        }
2111    }
2112}
2113
2114impl sum_tree::Summary for FragmentSummary {
2115    type Context = Option<clock::Global>;
2116
2117    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2118        self.max_id = other.max_id.clone();
2119        self.text.visible += &other.text.visible;
2120        self.text.deleted += &other.text.deleted;
2121        self.max_version.join(&other.max_version);
2122        self.min_insertion_version
2123            .meet(&other.min_insertion_version);
2124        self.max_insertion_version
2125            .join(&other.max_insertion_version);
2126    }
2127}
2128
2129impl Default for FragmentSummary {
2130    fn default() -> Self {
2131        FragmentSummary {
2132            max_id: Locator::min(),
2133            text: FragmentTextSummary::default(),
2134            max_version: clock::Global::new(),
2135            min_insertion_version: clock::Global::new(),
2136            max_insertion_version: clock::Global::new(),
2137        }
2138    }
2139}
2140
2141impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FragmentTextSummary {
2142    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2143        self.visible += summary.text.visible;
2144        self.deleted += summary.text.deleted;
2145    }
2146}
2147
2148impl sum_tree::Item for InsertionFragment {
2149    type Summary = InsertionFragmentKey;
2150
2151    fn summary(&self) -> Self::Summary {
2152        InsertionFragmentKey {
2153            timestamp: self.timestamp,
2154            split_offset: self.split_offset,
2155        }
2156    }
2157}
2158
2159impl sum_tree::KeyedItem for InsertionFragment {
2160    type Key = InsertionFragmentKey;
2161
2162    fn key(&self) -> Self::Key {
2163        sum_tree::Item::summary(self)
2164    }
2165}
2166
2167impl InsertionFragment {
2168    fn new(fragment: &Fragment) -> Self {
2169        Self {
2170            timestamp: fragment.insertion_timestamp,
2171            split_offset: fragment.insertion_offset,
2172            fragment_id: fragment.id.clone(),
2173        }
2174    }
2175
2176    fn insert_new(fragment: &Fragment) -> sum_tree::Edit<Self> {
2177        sum_tree::Edit::Insert(Self::new(fragment))
2178    }
2179}
2180
2181impl sum_tree::Summary for InsertionFragmentKey {
2182    type Context = ();
2183
2184    fn add_summary(&mut self, summary: &Self, _: &()) {
2185        *self = *summary;
2186    }
2187}
2188
2189#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
2190pub struct FullOffset(pub usize);
2191
2192impl FullOffset {
2193    const MAX: Self = FullOffset(usize::MAX);
2194}
2195
2196impl ops::AddAssign<usize> for FullOffset {
2197    fn add_assign(&mut self, rhs: usize) {
2198        self.0 += rhs;
2199    }
2200}
2201
2202impl ops::Add<usize> for FullOffset {
2203    type Output = Self;
2204
2205    fn add(mut self, rhs: usize) -> Self::Output {
2206        self += rhs;
2207        self
2208    }
2209}
2210
2211impl ops::Sub for FullOffset {
2212    type Output = usize;
2213
2214    fn sub(self, rhs: Self) -> Self::Output {
2215        self.0 - rhs.0
2216    }
2217}
2218
2219impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2220    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2221        *self += summary.text.visible;
2222    }
2223}
2224
2225impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FullOffset {
2226    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2227        self.0 += summary.text.visible + summary.text.deleted;
2228    }
2229}
2230
2231impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, FragmentTextSummary> for usize {
2232    fn cmp(
2233        &self,
2234        cursor_location: &FragmentTextSummary,
2235        _: &Option<clock::Global>,
2236    ) -> cmp::Ordering {
2237        Ord::cmp(self, &cursor_location.visible)
2238    }
2239}
2240
2241#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2242enum VersionedFullOffset {
2243    Offset(FullOffset),
2244    Invalid,
2245}
2246
2247impl VersionedFullOffset {
2248    fn full_offset(&self) -> FullOffset {
2249        if let Self::Offset(position) = self {
2250            *position
2251        } else {
2252            panic!("invalid version")
2253        }
2254    }
2255}
2256
2257impl Default for VersionedFullOffset {
2258    fn default() -> Self {
2259        Self::Offset(Default::default())
2260    }
2261}
2262
2263impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedFullOffset {
2264    fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<clock::Global>) {
2265        if let Self::Offset(offset) = self {
2266            let version = cx.as_ref().unwrap();
2267            if version.ge(&summary.max_insertion_version) {
2268                *offset += summary.text.visible + summary.text.deleted;
2269            } else if version.observed_any(&summary.min_insertion_version) {
2270                *self = Self::Invalid;
2271            }
2272        }
2273    }
2274}
2275
2276impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, Self> for VersionedFullOffset {
2277    fn cmp(&self, cursor_position: &Self, _: &Option<clock::Global>) -> cmp::Ordering {
2278        match (self, cursor_position) {
2279            (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2280            (Self::Offset(_), Self::Invalid) => cmp::Ordering::Less,
2281            (Self::Invalid, _) => unreachable!(),
2282        }
2283    }
2284}
2285
2286impl Operation {
2287    fn replica_id(&self) -> ReplicaId {
2288        self.lamport_timestamp().replica_id
2289    }
2290
2291    fn lamport_timestamp(&self) -> clock::Lamport {
2292        match self {
2293            Operation::Edit(edit) => edit.timestamp.lamport(),
2294            Operation::Undo {
2295                lamport_timestamp, ..
2296            } => *lamport_timestamp,
2297            Operation::UpdateSelections {
2298                lamport_timestamp, ..
2299            } => *lamport_timestamp,
2300            Operation::RemoveSelections {
2301                lamport_timestamp, ..
2302            } => *lamport_timestamp,
2303            Operation::SetActiveSelections {
2304                lamport_timestamp, ..
2305            } => *lamport_timestamp,
2306            #[cfg(test)]
2307            Operation::Test(lamport_timestamp) => *lamport_timestamp,
2308        }
2309    }
2310
2311    pub fn is_edit(&self) -> bool {
2312        match self {
2313            Operation::Edit { .. } => true,
2314            _ => false,
2315        }
2316    }
2317}
2318
2319pub trait ToOffset {
2320    fn to_offset<'a>(&self, content: &Snapshot) -> usize;
2321
2322    fn to_full_offset<'a>(&self, content: &Snapshot, bias: Bias) -> FullOffset {
2323        let offset = self.to_offset(&content);
2324        let mut cursor = content.fragments.cursor::<FragmentTextSummary>();
2325        cursor.seek(&offset, bias, &None);
2326        FullOffset(offset + cursor.start().deleted)
2327    }
2328}
2329
2330impl ToOffset for Point {
2331    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2332        content.visible_text.point_to_offset(*self)
2333    }
2334}
2335
2336impl ToOffset for PointUtf16 {
2337    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2338        content.visible_text.point_utf16_to_offset(*self)
2339    }
2340}
2341
2342impl ToOffset for usize {
2343    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2344        assert!(*self <= content.len(), "offset is out of range");
2345        *self
2346    }
2347}
2348
2349impl ToOffset for Anchor {
2350    fn to_offset<'a>(&self, content: &Snapshot) -> usize {
2351        content.summary_for_anchor(self)
2352    }
2353}
2354
2355impl<'a> ToOffset for &'a Anchor {
2356    fn to_offset(&self, content: &Snapshot) -> usize {
2357        content.summary_for_anchor(self)
2358    }
2359}
2360
2361pub trait ToPoint {
2362    fn to_point<'a>(&self, content: &Snapshot) -> Point;
2363}
2364
2365impl ToPoint for Anchor {
2366    fn to_point<'a>(&self, content: &Snapshot) -> Point {
2367        content.summary_for_anchor(self)
2368    }
2369}
2370
2371impl ToPoint for usize {
2372    fn to_point<'a>(&self, content: &Snapshot) -> Point {
2373        content.visible_text.offset_to_point(*self)
2374    }
2375}
2376
2377impl ToPoint for Point {
2378    fn to_point<'a>(&self, _: &Snapshot) -> Point {
2379        *self
2380    }
2381}
2382
2383pub trait FromAnchor {
2384    fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self;
2385}
2386
2387impl FromAnchor for Point {
2388    fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self {
2389        anchor.to_point(content)
2390    }
2391}
2392
2393impl FromAnchor for usize {
2394    fn from_anchor(anchor: &Anchor, content: &Snapshot) -> Self {
2395        anchor.to_offset(content)
2396    }
2397}