lib.rs

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