text.rs

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