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