text.rs

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