text.rs

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