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.len() > 0 {
 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.into_iter().zip(new_text.into_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    pub fn undo_to_transaction(&mut self, transaction_id: TransactionId) -> Vec<Operation> {
1246        let transactions = self
1247            .history
1248            .remove_from_undo(transaction_id)
1249            .iter()
1250            .map(|entry| entry.transaction.clone())
1251            .collect::<Vec<_>>();
1252        transactions
1253            .into_iter()
1254            .map(|transaction| self.undo_or_redo(transaction).unwrap())
1255            .collect()
1256    }
1257
1258    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1259        self.history.forget(transaction_id);
1260    }
1261
1262    pub fn redo(&mut self) -> Option<(TransactionId, Operation)> {
1263        if let Some(entry) = self.history.pop_redo() {
1264            let transaction = entry.transaction.clone();
1265            let transaction_id = transaction.id;
1266            let op = self.undo_or_redo(transaction).unwrap();
1267            Some((transaction_id, op))
1268        } else {
1269            None
1270        }
1271    }
1272
1273    pub fn redo_to_transaction(&mut self, transaction_id: TransactionId) -> Vec<Operation> {
1274        let transactions = self
1275            .history
1276            .remove_from_redo(transaction_id)
1277            .iter()
1278            .map(|entry| entry.transaction.clone())
1279            .collect::<Vec<_>>();
1280        transactions
1281            .into_iter()
1282            .map(|transaction| self.undo_or_redo(transaction).unwrap())
1283            .collect()
1284    }
1285
1286    fn undo_or_redo(&mut self, transaction: Transaction) -> Result<Operation> {
1287        let mut counts = HashMap::default();
1288        for edit_id in transaction.edit_ids {
1289            counts.insert(edit_id, self.undo_map.undo_count(edit_id) + 1);
1290        }
1291
1292        let undo = UndoOperation {
1293            id: self.local_clock.tick(),
1294            version: self.version(),
1295            counts,
1296            transaction_version: transaction.start.clone(),
1297        };
1298        self.apply_undo(&undo)?;
1299        let operation = Operation::Undo {
1300            undo,
1301            lamport_timestamp: self.lamport_clock.tick(),
1302        };
1303        self.snapshot.version.observe(operation.local_timestamp());
1304        self.history.push(operation.clone());
1305        Ok(operation)
1306    }
1307
1308    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1309        self.history.push_transaction(transaction, now);
1310        self.history.finalize_last_transaction();
1311    }
1312
1313    pub fn edited_ranges_for_transaction<'a, D>(
1314        &'a self,
1315        transaction: &'a Transaction,
1316    ) -> impl 'a + Iterator<Item = Range<D>>
1317    where
1318        D: TextDimension,
1319    {
1320        // get fragment ranges
1321        let mut cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1322        let offset_ranges = self
1323            .fragment_ids_for_edits(transaction.edit_ids.iter())
1324            .into_iter()
1325            .filter_map(move |fragment_id| {
1326                cursor.seek_forward(&Some(fragment_id), Bias::Left, &None);
1327                let fragment = cursor.item()?;
1328                let start_offset = cursor.start().1;
1329                let end_offset = start_offset + if fragment.visible { fragment.len } else { 0 };
1330                Some(start_offset..end_offset)
1331            });
1332
1333        // combine adjacent ranges
1334        let mut prev_range: Option<Range<usize>> = None;
1335        let disjoint_ranges = offset_ranges
1336            .map(Some)
1337            .chain([None])
1338            .filter_map(move |range| {
1339                if let Some((range, prev_range)) = range.as_ref().zip(prev_range.as_mut()) {
1340                    if prev_range.end == range.start {
1341                        prev_range.end = range.end;
1342                        return None;
1343                    }
1344                }
1345                let result = prev_range.clone();
1346                prev_range = range;
1347                result
1348            });
1349
1350        // convert to the desired text dimension.
1351        let mut position = D::default();
1352        let mut rope_cursor = self.visible_text.cursor(0);
1353        disjoint_ranges.map(move |range| {
1354            position.add_assign(&rope_cursor.summary(range.start));
1355            let start = position.clone();
1356            position.add_assign(&rope_cursor.summary(range.end));
1357            let end = position.clone();
1358            start..end
1359        })
1360    }
1361
1362    pub fn subscribe(&mut self) -> Subscription {
1363        self.subscriptions.subscribe()
1364    }
1365
1366    pub fn wait_for_edits(
1367        &mut self,
1368        edit_ids: impl IntoIterator<Item = clock::Local>,
1369    ) -> impl 'static + Future<Output = ()> {
1370        let mut futures = Vec::new();
1371        for edit_id in edit_ids {
1372            if !self.version.observed(edit_id) {
1373                let (tx, rx) = oneshot::channel();
1374                self.edit_id_resolvers.entry(edit_id).or_default().push(tx);
1375                futures.push(rx);
1376            }
1377        }
1378
1379        async move {
1380            for mut future in futures {
1381                future.recv().await;
1382            }
1383        }
1384    }
1385
1386    pub fn wait_for_anchors<'a>(
1387        &mut self,
1388        anchors: impl IntoIterator<Item = &'a Anchor>,
1389    ) -> impl 'static + Future<Output = ()> {
1390        let mut futures = Vec::new();
1391        for anchor in anchors {
1392            if !self.version.observed(anchor.timestamp)
1393                && *anchor != Anchor::MAX
1394                && *anchor != Anchor::MIN
1395            {
1396                let (tx, rx) = oneshot::channel();
1397                self.edit_id_resolvers
1398                    .entry(anchor.timestamp)
1399                    .or_default()
1400                    .push(tx);
1401                futures.push(rx);
1402            }
1403        }
1404
1405        async move {
1406            for mut future in futures {
1407                future.recv().await;
1408            }
1409        }
1410    }
1411
1412    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1413        let (tx, mut rx) = barrier::channel();
1414        if !self.snapshot.version.observed_all(&version) {
1415            self.version_barriers.push((version, tx));
1416        }
1417        async move {
1418            rx.recv().await;
1419        }
1420    }
1421
1422    fn resolve_edit(&mut self, edit_id: clock::Local) {
1423        for mut tx in self
1424            .edit_id_resolvers
1425            .remove(&edit_id)
1426            .into_iter()
1427            .flatten()
1428        {
1429            let _ = tx.try_send(());
1430        }
1431    }
1432}
1433
1434#[cfg(any(test, feature = "test-support"))]
1435impl Buffer {
1436    pub fn check_invariants(&self) {
1437        // Ensure every fragment is ordered by locator in the fragment tree and corresponds
1438        // to an insertion fragment in the insertions tree.
1439        let mut prev_fragment_id = Locator::min();
1440        for fragment in self.snapshot.fragments.items(&None) {
1441            assert!(fragment.id > prev_fragment_id);
1442            prev_fragment_id = fragment.id.clone();
1443
1444            let insertion_fragment = self
1445                .snapshot
1446                .insertions
1447                .get(
1448                    &InsertionFragmentKey {
1449                        timestamp: fragment.insertion_timestamp.local(),
1450                        split_offset: fragment.insertion_offset,
1451                    },
1452                    &(),
1453                )
1454                .unwrap();
1455            assert_eq!(
1456                insertion_fragment.fragment_id, fragment.id,
1457                "fragment: {:?}\ninsertion: {:?}",
1458                fragment, insertion_fragment
1459            );
1460        }
1461
1462        let mut cursor = self.snapshot.fragments.cursor::<Option<&Locator>>();
1463        for insertion_fragment in self.snapshot.insertions.cursor::<()>() {
1464            cursor.seek(&Some(&insertion_fragment.fragment_id), Bias::Left, &None);
1465            let fragment = cursor.item().unwrap();
1466            assert_eq!(insertion_fragment.fragment_id, fragment.id);
1467            assert_eq!(insertion_fragment.split_offset, fragment.insertion_offset);
1468        }
1469
1470        let fragment_summary = self.snapshot.fragments.summary();
1471        assert_eq!(
1472            fragment_summary.text.visible,
1473            self.snapshot.visible_text.len()
1474        );
1475        assert_eq!(
1476            fragment_summary.text.deleted,
1477            self.snapshot.deleted_text.len()
1478        );
1479
1480        assert!(!self.text().contains("\r\n"));
1481    }
1482
1483    pub fn set_group_interval(&mut self, group_interval: Duration) {
1484        self.history.group_interval = group_interval;
1485    }
1486
1487    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
1488        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
1489        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
1490        start..end
1491    }
1492
1493    pub fn randomly_edit<T>(
1494        &mut self,
1495        rng: &mut T,
1496        edit_count: usize,
1497    ) -> (Vec<(Range<usize>, Arc<str>)>, Operation)
1498    where
1499        T: rand::Rng,
1500    {
1501        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1502        let mut last_end = None;
1503        for _ in 0..edit_count {
1504            if last_end.map_or(false, |last_end| last_end >= self.len()) {
1505                break;
1506            }
1507            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1508            let range = self.random_byte_range(new_start, rng);
1509            last_end = Some(range.end);
1510
1511            let new_text_len = rng.gen_range(0..10);
1512            let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1513                .take(new_text_len)
1514                .collect();
1515
1516            edits.push((range, new_text.into()));
1517        }
1518
1519        log::info!("mutating buffer {} with {:?}", self.replica_id, edits);
1520        let op = self.edit(edits.iter().cloned());
1521        if let Operation::Edit(edit) = &op {
1522            assert_eq!(edits.len(), edit.new_text.len());
1523            for (edit, new_text) in edits.iter_mut().zip(&edit.new_text) {
1524                edit.1 = new_text.clone();
1525            }
1526        } else {
1527            unreachable!()
1528        }
1529
1530        (edits, op)
1531    }
1532
1533    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng) -> Vec<Operation> {
1534        use rand::prelude::*;
1535
1536        let mut ops = Vec::new();
1537        for _ in 0..rng.gen_range(1..=5) {
1538            if let Some(entry) = self.history.undo_stack.choose(rng) {
1539                let transaction = entry.transaction.clone();
1540                log::info!(
1541                    "undoing buffer {} transaction {:?}",
1542                    self.replica_id,
1543                    transaction
1544                );
1545                ops.push(self.undo_or_redo(transaction).unwrap());
1546            }
1547        }
1548        ops
1549    }
1550}
1551
1552impl Deref for Buffer {
1553    type Target = BufferSnapshot;
1554
1555    fn deref(&self) -> &Self::Target {
1556        &self.snapshot
1557    }
1558}
1559
1560impl BufferSnapshot {
1561    pub fn as_rope(&self) -> &Rope {
1562        &self.visible_text
1563    }
1564
1565    pub fn replica_id(&self) -> ReplicaId {
1566        self.replica_id
1567    }
1568
1569    pub fn row_count(&self) -> u32 {
1570        self.max_point().row + 1
1571    }
1572
1573    pub fn len(&self) -> usize {
1574        self.visible_text.len()
1575    }
1576
1577    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
1578        self.chars_at(0)
1579    }
1580
1581    pub fn chars_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = char> + '_ {
1582        self.text_for_range(range).flat_map(str::chars)
1583    }
1584
1585    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1586    where
1587        T: ToOffset,
1588    {
1589        let position = position.to_offset(self);
1590        position == self.clip_offset(position, Bias::Left)
1591            && self
1592                .bytes_in_range(position..self.len())
1593                .flatten()
1594                .copied()
1595                .take(needle.len())
1596                .eq(needle.bytes())
1597    }
1598
1599    pub fn common_prefix_at<T>(&self, position: T, needle: &str) -> Range<T>
1600    where
1601        T: ToOffset + TextDimension,
1602    {
1603        let offset = position.to_offset(self);
1604        let common_prefix_len = needle
1605            .char_indices()
1606            .map(|(index, _)| index)
1607            .chain([needle.len()])
1608            .take_while(|&len| len <= offset)
1609            .filter(|&len| {
1610                let left = self
1611                    .chars_for_range(offset - len..offset)
1612                    .flat_map(|c| char::to_lowercase(c));
1613                let right = needle[..len].chars().flat_map(|c| char::to_lowercase(c));
1614                left.eq(right)
1615            })
1616            .last()
1617            .unwrap_or(0);
1618        let start_offset = offset - common_prefix_len;
1619        let start = self.text_summary_for_range(0..start_offset);
1620        start..position
1621    }
1622
1623    pub fn text(&self) -> String {
1624        self.visible_text.to_string()
1625    }
1626
1627    pub fn line_ending(&self) -> LineEnding {
1628        self.line_ending
1629    }
1630
1631    pub fn deleted_text(&self) -> String {
1632        self.deleted_text.to_string()
1633    }
1634
1635    pub fn fragments(&self) -> impl Iterator<Item = &Fragment> {
1636        self.fragments.iter()
1637    }
1638
1639    pub fn text_summary(&self) -> TextSummary {
1640        self.visible_text.summary()
1641    }
1642
1643    pub fn max_point(&self) -> Point {
1644        self.visible_text.max_point()
1645    }
1646
1647    pub fn max_point_utf16(&self) -> PointUtf16 {
1648        self.visible_text.max_point_utf16()
1649    }
1650
1651    pub fn point_to_offset(&self, point: Point) -> usize {
1652        self.visible_text.point_to_offset(point)
1653    }
1654
1655    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1656        self.visible_text.point_utf16_to_offset(point)
1657    }
1658
1659    pub fn point_utf16_to_point(&self, point: PointUtf16) -> Point {
1660        self.visible_text.point_utf16_to_point(point)
1661    }
1662
1663    pub fn offset_utf16_to_offset(&self, offset: OffsetUtf16) -> usize {
1664        self.visible_text.offset_utf16_to_offset(offset)
1665    }
1666
1667    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
1668        self.visible_text.offset_to_offset_utf16(offset)
1669    }
1670
1671    pub fn offset_to_point(&self, offset: usize) -> Point {
1672        self.visible_text.offset_to_point(offset)
1673    }
1674
1675    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1676        self.visible_text.offset_to_point_utf16(offset)
1677    }
1678
1679    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1680        self.visible_text.point_to_point_utf16(point)
1681    }
1682
1683    pub fn version(&self) -> &clock::Global {
1684        &self.version
1685    }
1686
1687    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1688        let offset = position.to_offset(self);
1689        self.visible_text.chars_at(offset)
1690    }
1691
1692    pub fn reversed_chars_at<'a, T: ToOffset>(
1693        &'a self,
1694        position: T,
1695    ) -> impl Iterator<Item = char> + 'a {
1696        let offset = position.to_offset(self);
1697        self.visible_text.reversed_chars_at(offset)
1698    }
1699
1700    pub fn reversed_chunks_in_range<T: ToOffset>(&self, range: Range<T>) -> rope::Chunks {
1701        let range = range.start.to_offset(self)..range.end.to_offset(self);
1702        self.visible_text.reversed_chunks_in_range(range)
1703    }
1704
1705    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> rope::Bytes<'a> {
1706        let start = range.start.to_offset(self);
1707        let end = range.end.to_offset(self);
1708        self.visible_text.bytes_in_range(start..end)
1709    }
1710
1711    pub fn text_for_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> Chunks<'a> {
1712        let start = range.start.to_offset(self);
1713        let end = range.end.to_offset(self);
1714        self.visible_text.chunks_in_range(start..end)
1715    }
1716
1717    pub fn line_len(&self, row: u32) -> u32 {
1718        let row_start_offset = Point::new(row, 0).to_offset(self);
1719        let row_end_offset = if row >= self.max_point().row {
1720            self.len()
1721        } else {
1722            Point::new(row + 1, 0).to_offset(self) - 1
1723        };
1724        (row_end_offset - row_start_offset) as u32
1725    }
1726
1727    pub fn is_line_blank(&self, row: u32) -> bool {
1728        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1729            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1730    }
1731
1732    pub fn text_summary_for_range<'a, D, O: ToOffset>(&'a self, range: Range<O>) -> D
1733    where
1734        D: TextDimension,
1735    {
1736        self.visible_text
1737            .cursor(range.start.to_offset(self))
1738            .summary(range.end.to_offset(self))
1739    }
1740
1741    pub fn summaries_for_anchors<'a, D, A>(&'a self, anchors: A) -> impl 'a + Iterator<Item = D>
1742    where
1743        D: 'a + TextDimension,
1744        A: 'a + IntoIterator<Item = &'a Anchor>,
1745    {
1746        let anchors = anchors.into_iter();
1747        let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1748        let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1749        let mut text_cursor = self.visible_text.cursor(0);
1750        let mut position = D::default();
1751
1752        anchors.map(move |anchor| {
1753            if *anchor == Anchor::MIN {
1754                return D::default();
1755            } else if *anchor == Anchor::MAX {
1756                return D::from_text_summary(&self.visible_text.summary());
1757            }
1758
1759            let anchor_key = InsertionFragmentKey {
1760                timestamp: anchor.timestamp,
1761                split_offset: anchor.offset,
1762            };
1763            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1764            if let Some(insertion) = insertion_cursor.item() {
1765                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1766                if comparison == Ordering::Greater
1767                    || (anchor.bias == Bias::Left
1768                        && comparison == Ordering::Equal
1769                        && anchor.offset > 0)
1770                {
1771                    insertion_cursor.prev(&());
1772                }
1773            } else {
1774                insertion_cursor.prev(&());
1775            }
1776            let insertion = insertion_cursor.item().expect("invalid insertion");
1777            assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1778
1779            fragment_cursor.seek_forward(&Some(&insertion.fragment_id), Bias::Left, &None);
1780            let fragment = fragment_cursor.item().unwrap();
1781            let mut fragment_offset = fragment_cursor.start().1;
1782            if fragment.visible {
1783                fragment_offset += anchor.offset - insertion.split_offset;
1784            }
1785
1786            position.add_assign(&text_cursor.summary(fragment_offset));
1787            position.clone()
1788        })
1789    }
1790
1791    fn summary_for_anchor<'a, D>(&'a self, anchor: &Anchor) -> D
1792    where
1793        D: TextDimension,
1794    {
1795        if *anchor == Anchor::MIN {
1796            D::default()
1797        } else if *anchor == Anchor::MAX {
1798            D::from_text_summary(&self.visible_text.summary())
1799        } else {
1800            let anchor_key = InsertionFragmentKey {
1801                timestamp: anchor.timestamp,
1802                split_offset: anchor.offset,
1803            };
1804            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1805            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1806            if let Some(insertion) = insertion_cursor.item() {
1807                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1808                if comparison == Ordering::Greater
1809                    || (anchor.bias == Bias::Left
1810                        && comparison == Ordering::Equal
1811                        && anchor.offset > 0)
1812                {
1813                    insertion_cursor.prev(&());
1814                }
1815            } else {
1816                insertion_cursor.prev(&());
1817            }
1818            let insertion = insertion_cursor.item().expect("invalid insertion");
1819            assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1820
1821            let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1822            fragment_cursor.seek(&Some(&insertion.fragment_id), Bias::Left, &None);
1823            let fragment = fragment_cursor.item().unwrap();
1824            let mut fragment_offset = fragment_cursor.start().1;
1825            if fragment.visible {
1826                fragment_offset += anchor.offset - insertion.split_offset;
1827            }
1828            self.text_summary_for_range(0..fragment_offset)
1829        }
1830    }
1831
1832    fn fragment_id_for_anchor(&self, anchor: &Anchor) -> &Locator {
1833        if *anchor == Anchor::MIN {
1834            &locator::MIN
1835        } else if *anchor == Anchor::MAX {
1836            &locator::MAX
1837        } else {
1838            let anchor_key = InsertionFragmentKey {
1839                timestamp: anchor.timestamp,
1840                split_offset: anchor.offset,
1841            };
1842            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1843            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1844            if let Some(insertion) = insertion_cursor.item() {
1845                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1846                if comparison == Ordering::Greater
1847                    || (anchor.bias == Bias::Left
1848                        && comparison == Ordering::Equal
1849                        && anchor.offset > 0)
1850                {
1851                    insertion_cursor.prev(&());
1852                }
1853            } else {
1854                insertion_cursor.prev(&());
1855            }
1856            let insertion = insertion_cursor.item().expect("invalid insertion");
1857            debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1858            &insertion.fragment_id
1859        }
1860    }
1861
1862    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1863        self.anchor_at(position, Bias::Left)
1864    }
1865
1866    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1867        self.anchor_at(position, Bias::Right)
1868    }
1869
1870    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1871        let offset = position.to_offset(self);
1872        if bias == Bias::Left && offset == 0 {
1873            Anchor::MIN
1874        } else if bias == Bias::Right && offset == self.len() {
1875            Anchor::MAX
1876        } else {
1877            let mut fragment_cursor = self.fragments.cursor::<usize>();
1878            fragment_cursor.seek(&offset, bias, &None);
1879            let fragment = fragment_cursor.item().unwrap();
1880            let overshoot = offset - *fragment_cursor.start();
1881            Anchor {
1882                timestamp: fragment.insertion_timestamp.local(),
1883                offset: fragment.insertion_offset + overshoot,
1884                bias,
1885                buffer_id: Some(self.remote_id),
1886            }
1887        }
1888    }
1889
1890    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1891        *anchor == Anchor::MIN
1892            || *anchor == Anchor::MAX
1893            || (Some(self.remote_id) == anchor.buffer_id && self.version.observed(anchor.timestamp))
1894    }
1895
1896    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1897        self.visible_text.clip_offset(offset, bias)
1898    }
1899
1900    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1901        self.visible_text.clip_point(point, bias)
1902    }
1903
1904    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1905        self.visible_text.clip_point_utf16(point, bias)
1906    }
1907
1908    pub fn edits_since<'a, D>(
1909        &'a self,
1910        since: &'a clock::Global,
1911    ) -> impl 'a + Iterator<Item = Edit<D>>
1912    where
1913        D: TextDimension + Ord,
1914    {
1915        self.edits_since_in_range(since, Anchor::MIN..Anchor::MAX)
1916    }
1917
1918    pub fn edits_since_in_range<'a, D>(
1919        &'a self,
1920        since: &'a clock::Global,
1921        range: Range<Anchor>,
1922    ) -> impl 'a + Iterator<Item = Edit<D>>
1923    where
1924        D: TextDimension + Ord,
1925    {
1926        let fragments_cursor = if *since == self.version {
1927            None
1928        } else {
1929            let mut cursor = self
1930                .fragments
1931                .filter(move |summary| !since.observed_all(&summary.max_version));
1932            cursor.next(&None);
1933            Some(cursor)
1934        };
1935        let mut cursor = self
1936            .fragments
1937            .cursor::<(Option<&Locator>, FragmentTextSummary)>();
1938
1939        let start_fragment_id = self.fragment_id_for_anchor(&range.start);
1940        cursor.seek(&Some(start_fragment_id), Bias::Left, &None);
1941        let mut visible_start = cursor.start().1.visible;
1942        let mut deleted_start = cursor.start().1.deleted;
1943        if let Some(fragment) = cursor.item() {
1944            let overshoot = range.start.offset - fragment.insertion_offset;
1945            if fragment.visible {
1946                visible_start += overshoot;
1947            } else {
1948                deleted_start += overshoot;
1949            }
1950        }
1951        let end_fragment_id = self.fragment_id_for_anchor(&range.end);
1952
1953        Edits {
1954            visible_cursor: self.visible_text.cursor(visible_start),
1955            deleted_cursor: self.deleted_text.cursor(deleted_start),
1956            fragments_cursor,
1957            undos: &self.undo_map,
1958            since,
1959            old_end: Default::default(),
1960            new_end: Default::default(),
1961            range: (start_fragment_id, range.start.offset)..(end_fragment_id, range.end.offset),
1962        }
1963    }
1964}
1965
1966struct RopeBuilder<'a> {
1967    old_visible_cursor: rope::Cursor<'a>,
1968    old_deleted_cursor: rope::Cursor<'a>,
1969    new_visible: Rope,
1970    new_deleted: Rope,
1971}
1972
1973impl<'a> RopeBuilder<'a> {
1974    fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
1975        Self {
1976            old_visible_cursor,
1977            old_deleted_cursor,
1978            new_visible: Rope::new(),
1979            new_deleted: Rope::new(),
1980        }
1981    }
1982
1983    fn push_tree(&mut self, len: FragmentTextSummary) {
1984        self.push(len.visible, true, true);
1985        self.push(len.deleted, false, false);
1986    }
1987
1988    fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
1989        debug_assert!(fragment.len > 0);
1990        self.push(fragment.len, was_visible, fragment.visible)
1991    }
1992
1993    fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
1994        let text = if was_visible {
1995            self.old_visible_cursor
1996                .slice(self.old_visible_cursor.offset() + len)
1997        } else {
1998            self.old_deleted_cursor
1999                .slice(self.old_deleted_cursor.offset() + len)
2000        };
2001        if is_visible {
2002            self.new_visible.append(text);
2003        } else {
2004            self.new_deleted.append(text);
2005        }
2006    }
2007
2008    fn push_str(&mut self, text: &str) {
2009        self.new_visible.push(text);
2010    }
2011
2012    fn finish(mut self) -> (Rope, Rope) {
2013        self.new_visible.append(self.old_visible_cursor.suffix());
2014        self.new_deleted.append(self.old_deleted_cursor.suffix());
2015        (self.new_visible, self.new_deleted)
2016    }
2017}
2018
2019impl<'a, D: TextDimension + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator for Edits<'a, D, F> {
2020    type Item = Edit<D>;
2021
2022    fn next(&mut self) -> Option<Self::Item> {
2023        let mut pending_edit: Option<Edit<D>> = None;
2024        let cursor = self.fragments_cursor.as_mut()?;
2025
2026        while let Some(fragment) = cursor.item() {
2027            if fragment.id < *self.range.start.0 {
2028                cursor.next(&None);
2029                continue;
2030            } else if fragment.id > *self.range.end.0 {
2031                break;
2032            }
2033
2034            if cursor.start().visible > self.visible_cursor.offset() {
2035                let summary = self.visible_cursor.summary(cursor.start().visible);
2036                self.old_end.add_assign(&summary);
2037                self.new_end.add_assign(&summary);
2038            }
2039
2040            if pending_edit
2041                .as_ref()
2042                .map_or(false, |change| change.new.end < self.new_end)
2043            {
2044                break;
2045            }
2046
2047            if !fragment.was_visible(&self.since, &self.undos) && fragment.visible {
2048                let mut visible_end = cursor.end(&None).visible;
2049                if fragment.id == *self.range.end.0 {
2050                    visible_end = cmp::min(
2051                        visible_end,
2052                        cursor.start().visible + (self.range.end.1 - fragment.insertion_offset),
2053                    );
2054                }
2055
2056                let fragment_summary = self.visible_cursor.summary(visible_end);
2057                let mut new_end = self.new_end.clone();
2058                new_end.add_assign(&fragment_summary);
2059                if let Some(pending_edit) = pending_edit.as_mut() {
2060                    pending_edit.new.end = new_end.clone();
2061                } else {
2062                    pending_edit = Some(Edit {
2063                        old: self.old_end.clone()..self.old_end.clone(),
2064                        new: self.new_end.clone()..new_end.clone(),
2065                    });
2066                }
2067
2068                self.new_end = new_end;
2069            } else if fragment.was_visible(&self.since, &self.undos) && !fragment.visible {
2070                let mut deleted_end = cursor.end(&None).deleted;
2071                if fragment.id == *self.range.end.0 {
2072                    deleted_end = cmp::min(
2073                        deleted_end,
2074                        cursor.start().deleted + (self.range.end.1 - fragment.insertion_offset),
2075                    );
2076                }
2077
2078                if cursor.start().deleted > self.deleted_cursor.offset() {
2079                    self.deleted_cursor.seek_forward(cursor.start().deleted);
2080                }
2081                let fragment_summary = self.deleted_cursor.summary(deleted_end);
2082                let mut old_end = self.old_end.clone();
2083                old_end.add_assign(&fragment_summary);
2084                if let Some(pending_edit) = pending_edit.as_mut() {
2085                    pending_edit.old.end = old_end.clone();
2086                } else {
2087                    pending_edit = Some(Edit {
2088                        old: self.old_end.clone()..old_end.clone(),
2089                        new: self.new_end.clone()..self.new_end.clone(),
2090                    });
2091                }
2092
2093                self.old_end = old_end;
2094            }
2095
2096            cursor.next(&None);
2097        }
2098
2099        pending_edit
2100    }
2101}
2102
2103impl Fragment {
2104    fn insertion_slice(&self) -> InsertionSlice {
2105        InsertionSlice {
2106            insertion_id: self.insertion_timestamp.local(),
2107            range: self.insertion_offset..self.insertion_offset + self.len,
2108        }
2109    }
2110
2111    fn is_visible(&self, undos: &UndoMap) -> bool {
2112        !undos.is_undone(self.insertion_timestamp.local())
2113            && self.deletions.iter().all(|d| undos.is_undone(*d))
2114    }
2115
2116    fn was_visible(&self, version: &clock::Global, undos: &UndoMap) -> bool {
2117        (version.observed(self.insertion_timestamp.local())
2118            && !undos.was_undone(self.insertion_timestamp.local(), version))
2119            && self
2120                .deletions
2121                .iter()
2122                .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
2123    }
2124}
2125
2126impl sum_tree::Item for Fragment {
2127    type Summary = FragmentSummary;
2128
2129    fn summary(&self) -> Self::Summary {
2130        let mut max_version = clock::Global::new();
2131        max_version.observe(self.insertion_timestamp.local());
2132        for deletion in &self.deletions {
2133            max_version.observe(*deletion);
2134        }
2135        max_version.join(&self.max_undos);
2136
2137        let mut min_insertion_version = clock::Global::new();
2138        min_insertion_version.observe(self.insertion_timestamp.local());
2139        let max_insertion_version = min_insertion_version.clone();
2140        if self.visible {
2141            FragmentSummary {
2142                max_id: self.id.clone(),
2143                text: FragmentTextSummary {
2144                    visible: self.len,
2145                    deleted: 0,
2146                },
2147                max_version,
2148                min_insertion_version,
2149                max_insertion_version,
2150            }
2151        } else {
2152            FragmentSummary {
2153                max_id: self.id.clone(),
2154                text: FragmentTextSummary {
2155                    visible: 0,
2156                    deleted: self.len,
2157                },
2158                max_version,
2159                min_insertion_version,
2160                max_insertion_version,
2161            }
2162        }
2163    }
2164}
2165
2166impl sum_tree::Summary for FragmentSummary {
2167    type Context = Option<clock::Global>;
2168
2169    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2170        self.max_id.assign(&other.max_id);
2171        self.text.visible += &other.text.visible;
2172        self.text.deleted += &other.text.deleted;
2173        self.max_version.join(&other.max_version);
2174        self.min_insertion_version
2175            .meet(&other.min_insertion_version);
2176        self.max_insertion_version
2177            .join(&other.max_insertion_version);
2178    }
2179}
2180
2181impl Default for FragmentSummary {
2182    fn default() -> Self {
2183        FragmentSummary {
2184            max_id: Locator::min(),
2185            text: FragmentTextSummary::default(),
2186            max_version: clock::Global::new(),
2187            min_insertion_version: clock::Global::new(),
2188            max_insertion_version: clock::Global::new(),
2189        }
2190    }
2191}
2192
2193impl sum_tree::Item for InsertionFragment {
2194    type Summary = InsertionFragmentKey;
2195
2196    fn summary(&self) -> Self::Summary {
2197        InsertionFragmentKey {
2198            timestamp: self.timestamp,
2199            split_offset: self.split_offset,
2200        }
2201    }
2202}
2203
2204impl sum_tree::KeyedItem for InsertionFragment {
2205    type Key = InsertionFragmentKey;
2206
2207    fn key(&self) -> Self::Key {
2208        sum_tree::Item::summary(self)
2209    }
2210}
2211
2212impl InsertionFragment {
2213    fn new(fragment: &Fragment) -> Self {
2214        Self {
2215            timestamp: fragment.insertion_timestamp.local(),
2216            split_offset: fragment.insertion_offset,
2217            fragment_id: fragment.id.clone(),
2218        }
2219    }
2220
2221    fn insert_new(fragment: &Fragment) -> sum_tree::Edit<Self> {
2222        sum_tree::Edit::Insert(Self::new(fragment))
2223    }
2224}
2225
2226impl sum_tree::Summary for InsertionFragmentKey {
2227    type Context = ();
2228
2229    fn add_summary(&mut self, summary: &Self, _: &()) {
2230        *self = *summary;
2231    }
2232}
2233
2234#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
2235pub struct FullOffset(pub usize);
2236
2237impl ops::AddAssign<usize> for FullOffset {
2238    fn add_assign(&mut self, rhs: usize) {
2239        self.0 += rhs;
2240    }
2241}
2242
2243impl ops::Add<usize> for FullOffset {
2244    type Output = Self;
2245
2246    fn add(mut self, rhs: usize) -> Self::Output {
2247        self += rhs;
2248        self
2249    }
2250}
2251
2252impl ops::Sub for FullOffset {
2253    type Output = usize;
2254
2255    fn sub(self, rhs: Self) -> Self::Output {
2256        self.0 - rhs.0
2257    }
2258}
2259
2260impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2261    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2262        *self += summary.text.visible;
2263    }
2264}
2265
2266impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FullOffset {
2267    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2268        self.0 += summary.text.visible + summary.text.deleted;
2269    }
2270}
2271
2272impl<'a> sum_tree::Dimension<'a, FragmentSummary> for Option<&'a Locator> {
2273    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2274        *self = Some(&summary.max_id);
2275    }
2276}
2277
2278impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, FragmentTextSummary> for usize {
2279    fn cmp(
2280        &self,
2281        cursor_location: &FragmentTextSummary,
2282        _: &Option<clock::Global>,
2283    ) -> cmp::Ordering {
2284        Ord::cmp(self, &cursor_location.visible)
2285    }
2286}
2287
2288#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2289enum VersionedFullOffset {
2290    Offset(FullOffset),
2291    Invalid,
2292}
2293
2294impl VersionedFullOffset {
2295    fn full_offset(&self) -> FullOffset {
2296        if let Self::Offset(position) = self {
2297            *position
2298        } else {
2299            panic!("invalid version")
2300        }
2301    }
2302}
2303
2304impl Default for VersionedFullOffset {
2305    fn default() -> Self {
2306        Self::Offset(Default::default())
2307    }
2308}
2309
2310impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedFullOffset {
2311    fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<clock::Global>) {
2312        if let Self::Offset(offset) = self {
2313            let version = cx.as_ref().unwrap();
2314            if version.observed_all(&summary.max_insertion_version) {
2315                *offset += summary.text.visible + summary.text.deleted;
2316            } else if version.observed_any(&summary.min_insertion_version) {
2317                *self = Self::Invalid;
2318            }
2319        }
2320    }
2321}
2322
2323impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, Self> for VersionedFullOffset {
2324    fn cmp(&self, cursor_position: &Self, _: &Option<clock::Global>) -> cmp::Ordering {
2325        match (self, cursor_position) {
2326            (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2327            (Self::Offset(_), Self::Invalid) => cmp::Ordering::Less,
2328            (Self::Invalid, _) => unreachable!(),
2329        }
2330    }
2331}
2332
2333impl Operation {
2334    fn replica_id(&self) -> ReplicaId {
2335        operation_queue::Operation::lamport_timestamp(self).replica_id
2336    }
2337
2338    pub fn local_timestamp(&self) -> clock::Local {
2339        match self {
2340            Operation::Edit(edit) => edit.timestamp.local(),
2341            Operation::Undo { undo, .. } => undo.id,
2342        }
2343    }
2344
2345    pub fn as_edit(&self) -> Option<&EditOperation> {
2346        match self {
2347            Operation::Edit(edit) => Some(edit),
2348            _ => None,
2349        }
2350    }
2351
2352    pub fn is_edit(&self) -> bool {
2353        match self {
2354            Operation::Edit { .. } => true,
2355            _ => false,
2356        }
2357    }
2358}
2359
2360impl operation_queue::Operation for Operation {
2361    fn lamport_timestamp(&self) -> clock::Lamport {
2362        match self {
2363            Operation::Edit(edit) => edit.timestamp.lamport(),
2364            Operation::Undo {
2365                lamport_timestamp, ..
2366            } => *lamport_timestamp,
2367        }
2368    }
2369}
2370
2371impl Default for LineEnding {
2372    fn default() -> Self {
2373        #[cfg(unix)]
2374        return Self::Unix;
2375
2376        #[cfg(not(unix))]
2377        return Self::CRLF;
2378    }
2379}
2380
2381impl LineEnding {
2382    pub fn as_str(&self) -> &'static str {
2383        match self {
2384            LineEnding::Unix => "\n",
2385            LineEnding::Windows => "\r\n",
2386        }
2387    }
2388
2389    pub fn detect(text: &str) -> Self {
2390        let mut max_ix = cmp::min(text.len(), 1000);
2391        while !text.is_char_boundary(max_ix) {
2392            max_ix -= 1;
2393        }
2394
2395        if let Some(ix) = text[..max_ix].find(&['\n']) {
2396            if ix > 0 && text.as_bytes()[ix - 1] == b'\r' {
2397                Self::Windows
2398            } else {
2399                Self::Unix
2400            }
2401        } else {
2402            Self::default()
2403        }
2404    }
2405
2406    pub fn normalize(text: &mut String) {
2407        if let Cow::Owned(replaced) = CARRIAGE_RETURNS_REGEX.replace_all(text, "\n") {
2408            *text = replaced;
2409        }
2410    }
2411
2412    fn normalize_arc(text: Arc<str>) -> Arc<str> {
2413        if let Cow::Owned(replaced) = CARRIAGE_RETURNS_REGEX.replace_all(&text, "\n") {
2414            replaced.into()
2415        } else {
2416            text
2417        }
2418    }
2419}
2420
2421pub trait ToOffset {
2422    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize;
2423}
2424
2425impl ToOffset for Point {
2426    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2427        snapshot.point_to_offset(*self)
2428    }
2429}
2430
2431impl ToOffset for PointUtf16 {
2432    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2433        snapshot.point_utf16_to_offset(*self)
2434    }
2435}
2436
2437impl ToOffset for usize {
2438    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2439        assert!(*self <= snapshot.len(), "offset is out of range");
2440        *self
2441    }
2442}
2443
2444impl ToOffset for OffsetUtf16 {
2445    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2446        snapshot.offset_utf16_to_offset(*self)
2447    }
2448}
2449
2450impl ToOffset for Anchor {
2451    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2452        snapshot.summary_for_anchor(self)
2453    }
2454}
2455
2456impl<'a, T: ToOffset> ToOffset for &'a T {
2457    fn to_offset(&self, content: &BufferSnapshot) -> usize {
2458        (*self).to_offset(content)
2459    }
2460}
2461
2462pub trait ToPoint {
2463    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point;
2464}
2465
2466impl ToPoint for Anchor {
2467    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point {
2468        snapshot.summary_for_anchor(self)
2469    }
2470}
2471
2472impl ToPoint for usize {
2473    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point {
2474        snapshot.offset_to_point(*self)
2475    }
2476}
2477
2478impl ToPoint for PointUtf16 {
2479    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point {
2480        snapshot.point_utf16_to_point(*self)
2481    }
2482}
2483
2484impl ToPoint for Point {
2485    fn to_point<'a>(&self, _: &BufferSnapshot) -> Point {
2486        *self
2487    }
2488}
2489
2490pub trait ToPointUtf16 {
2491    fn to_point_utf16<'a>(&self, snapshot: &BufferSnapshot) -> PointUtf16;
2492}
2493
2494impl ToPointUtf16 for Anchor {
2495    fn to_point_utf16<'a>(&self, snapshot: &BufferSnapshot) -> PointUtf16 {
2496        snapshot.summary_for_anchor(self)
2497    }
2498}
2499
2500impl ToPointUtf16 for usize {
2501    fn to_point_utf16<'a>(&self, snapshot: &BufferSnapshot) -> PointUtf16 {
2502        snapshot.offset_to_point_utf16(*self)
2503    }
2504}
2505
2506impl ToPointUtf16 for PointUtf16 {
2507    fn to_point_utf16<'a>(&self, _: &BufferSnapshot) -> PointUtf16 {
2508        *self
2509    }
2510}
2511
2512impl ToPointUtf16 for Point {
2513    fn to_point_utf16<'a>(&self, snapshot: &BufferSnapshot) -> PointUtf16 {
2514        snapshot.point_to_point_utf16(*self)
2515    }
2516}
2517
2518pub trait ToOffsetUtf16 {
2519    fn to_offset_utf16<'a>(&self, snapshot: &BufferSnapshot) -> OffsetUtf16;
2520}
2521
2522impl ToOffsetUtf16 for Anchor {
2523    fn to_offset_utf16<'a>(&self, snapshot: &BufferSnapshot) -> OffsetUtf16 {
2524        snapshot.summary_for_anchor(self)
2525    }
2526}
2527
2528impl ToOffsetUtf16 for usize {
2529    fn to_offset_utf16<'a>(&self, snapshot: &BufferSnapshot) -> OffsetUtf16 {
2530        snapshot.offset_to_offset_utf16(*self)
2531    }
2532}
2533
2534impl ToOffsetUtf16 for OffsetUtf16 {
2535    fn to_offset_utf16<'a>(&self, _snapshot: &BufferSnapshot) -> OffsetUtf16 {
2536        *self
2537    }
2538}
2539
2540pub trait Clip {
2541    fn clip(&self, bias: Bias, snapshot: &BufferSnapshot) -> Self;
2542}
2543
2544impl Clip for usize {
2545    fn clip(&self, bias: Bias, snapshot: &BufferSnapshot) -> Self {
2546        snapshot.clip_offset(*self, bias)
2547    }
2548}
2549
2550impl Clip for Point {
2551    fn clip(&self, bias: Bias, snapshot: &BufferSnapshot) -> Self {
2552        snapshot.clip_point(*self, bias)
2553    }
2554}
2555
2556impl Clip for PointUtf16 {
2557    fn clip(&self, bias: Bias, snapshot: &BufferSnapshot) -> Self {
2558        snapshot.clip_point_utf16(*self, bias)
2559    }
2560}
2561
2562pub trait FromAnchor {
2563    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self;
2564}
2565
2566impl FromAnchor for Point {
2567    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2568        snapshot.summary_for_anchor(anchor)
2569    }
2570}
2571
2572impl FromAnchor for PointUtf16 {
2573    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2574        snapshot.summary_for_anchor(anchor)
2575    }
2576}
2577
2578impl FromAnchor for usize {
2579    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2580        snapshot.summary_for_anchor(anchor)
2581    }
2582}