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 peek_undo_stack(&self) -> Option<&HistoryEntry> {
1269        self.history.undo_stack.last()
1270    }
1271
1272    pub fn peek_redo_stack(&self) -> Option<&HistoryEntry> {
1273        self.history.redo_stack.last()
1274    }
1275
1276    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1277        self.start_transaction_at(Instant::now())
1278    }
1279
1280    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1281        self.history
1282            .start_transaction(self.version.clone(), now, &mut self.lamport_clock)
1283    }
1284
1285    pub fn end_transaction(&mut self) -> Option<(TransactionId, clock::Global)> {
1286        self.end_transaction_at(Instant::now())
1287    }
1288
1289    pub fn end_transaction_at(&mut self, now: Instant) -> Option<(TransactionId, clock::Global)> {
1290        if let Some(entry) = self.history.end_transaction(now) {
1291            let since = entry.transaction.start.clone();
1292            let id = self.history.group().unwrap();
1293            Some((id, since))
1294        } else {
1295            None
1296        }
1297    }
1298
1299    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1300        self.history.finalize_last_transaction()
1301    }
1302
1303    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1304        self.history.group_until(transaction_id);
1305    }
1306
1307    pub fn base_text(&self) -> &Rope {
1308        &self.history.base_text
1309    }
1310
1311    pub fn operations(&self) -> &TreeMap<clock::Lamport, Operation> {
1312        &self.history.operations
1313    }
1314
1315    pub fn undo(&mut self) -> Option<(TransactionId, Operation)> {
1316        if let Some(entry) = self.history.pop_undo() {
1317            let transaction = entry.transaction.clone();
1318            let transaction_id = transaction.id;
1319            let op = self.undo_or_redo(transaction).unwrap();
1320            Some((transaction_id, op))
1321        } else {
1322            None
1323        }
1324    }
1325
1326    pub fn undo_transaction(&mut self, transaction_id: TransactionId) -> Option<Operation> {
1327        let transaction = self
1328            .history
1329            .remove_from_undo(transaction_id)?
1330            .transaction
1331            .clone();
1332        self.undo_or_redo(transaction).log_err()
1333    }
1334
1335    pub fn undo_to_transaction(&mut self, transaction_id: TransactionId) -> Vec<Operation> {
1336        let transactions = self
1337            .history
1338            .remove_from_undo_until(transaction_id)
1339            .iter()
1340            .map(|entry| entry.transaction.clone())
1341            .collect::<Vec<_>>();
1342
1343        transactions
1344            .into_iter()
1345            .map(|transaction| self.undo_or_redo(transaction).unwrap())
1346            .collect()
1347    }
1348
1349    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1350        self.history.forget(transaction_id);
1351    }
1352
1353    pub fn merge_transactions(&mut self, transaction: TransactionId, destination: TransactionId) {
1354        self.history.merge_transactions(transaction, destination);
1355    }
1356
1357    pub fn redo(&mut self) -> Option<(TransactionId, Operation)> {
1358        if let Some(entry) = self.history.pop_redo() {
1359            let transaction = entry.transaction.clone();
1360            let transaction_id = transaction.id;
1361            let op = self.undo_or_redo(transaction).unwrap();
1362            Some((transaction_id, op))
1363        } else {
1364            None
1365        }
1366    }
1367
1368    pub fn redo_to_transaction(&mut self, transaction_id: TransactionId) -> Vec<Operation> {
1369        let transactions = self
1370            .history
1371            .remove_from_redo(transaction_id)
1372            .iter()
1373            .map(|entry| entry.transaction.clone())
1374            .collect::<Vec<_>>();
1375
1376        transactions
1377            .into_iter()
1378            .map(|transaction| self.undo_or_redo(transaction).unwrap())
1379            .collect()
1380    }
1381
1382    fn undo_or_redo(&mut self, transaction: Transaction) -> Result<Operation> {
1383        let mut counts = HashMap::default();
1384        for edit_id in transaction.edit_ids {
1385            counts.insert(edit_id, self.undo_map.undo_count(edit_id) + 1);
1386        }
1387
1388        let undo = UndoOperation {
1389            timestamp: self.lamport_clock.tick(),
1390            version: self.version(),
1391            counts,
1392        };
1393        self.apply_undo(&undo)?;
1394        self.snapshot.version.observe(undo.timestamp);
1395        let operation = Operation::Undo(undo);
1396        self.history.push(operation.clone());
1397        Ok(operation)
1398    }
1399
1400    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1401        self.history.push_transaction(transaction, now);
1402        self.history.finalize_last_transaction();
1403    }
1404
1405    pub fn edited_ranges_for_transaction_id<D>(
1406        &self,
1407        transaction_id: TransactionId,
1408    ) -> impl '_ + Iterator<Item = Range<D>>
1409    where
1410        D: TextDimension,
1411    {
1412        self.history
1413            .transaction(transaction_id)
1414            .into_iter()
1415            .flat_map(|transaction| self.edited_ranges_for_transaction(transaction))
1416    }
1417
1418    pub fn edited_ranges_for_transaction<'a, D>(
1419        &'a self,
1420        transaction: &'a Transaction,
1421    ) -> impl 'a + Iterator<Item = Range<D>>
1422    where
1423        D: TextDimension,
1424    {
1425        // get fragment ranges
1426        let mut cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1427        let offset_ranges = self
1428            .fragment_ids_for_edits(transaction.edit_ids.iter())
1429            .into_iter()
1430            .filter_map(move |fragment_id| {
1431                cursor.seek_forward(&Some(fragment_id), Bias::Left, &None);
1432                let fragment = cursor.item()?;
1433                let start_offset = cursor.start().1;
1434                let end_offset = start_offset + if fragment.visible { fragment.len } else { 0 };
1435                Some(start_offset..end_offset)
1436            });
1437
1438        // combine adjacent ranges
1439        let mut prev_range: Option<Range<usize>> = None;
1440        let disjoint_ranges = offset_ranges
1441            .map(Some)
1442            .chain([None])
1443            .filter_map(move |range| {
1444                if let Some((range, prev_range)) = range.as_ref().zip(prev_range.as_mut()) {
1445                    if prev_range.end == range.start {
1446                        prev_range.end = range.end;
1447                        return None;
1448                    }
1449                }
1450                let result = prev_range.clone();
1451                prev_range = range;
1452                result
1453            });
1454
1455        // convert to the desired text dimension.
1456        let mut position = D::default();
1457        let mut rope_cursor = self.visible_text.cursor(0);
1458        disjoint_ranges.map(move |range| {
1459            position.add_assign(&rope_cursor.summary(range.start));
1460            let start = position.clone();
1461            position.add_assign(&rope_cursor.summary(range.end));
1462            let end = position.clone();
1463            start..end
1464        })
1465    }
1466
1467    pub fn subscribe(&mut self) -> Subscription {
1468        self.subscriptions.subscribe()
1469    }
1470
1471    pub fn wait_for_edits(
1472        &mut self,
1473        edit_ids: impl IntoIterator<Item = clock::Lamport>,
1474    ) -> impl 'static + Future<Output = Result<()>> {
1475        let mut futures = Vec::new();
1476        for edit_id in edit_ids {
1477            if !self.version.observed(edit_id) {
1478                let (tx, rx) = oneshot::channel();
1479                self.edit_id_resolvers.entry(edit_id).or_default().push(tx);
1480                futures.push(rx);
1481            }
1482        }
1483
1484        async move {
1485            for mut future in futures {
1486                if future.recv().await.is_none() {
1487                    Err(anyhow!("gave up waiting for edits"))?;
1488                }
1489            }
1490            Ok(())
1491        }
1492    }
1493
1494    pub fn wait_for_anchors(
1495        &mut self,
1496        anchors: impl IntoIterator<Item = Anchor>,
1497    ) -> impl 'static + Future<Output = Result<()>> {
1498        let mut futures = Vec::new();
1499        for anchor in anchors {
1500            if !self.version.observed(anchor.timestamp)
1501                && anchor != Anchor::MAX
1502                && anchor != Anchor::MIN
1503            {
1504                let (tx, rx) = oneshot::channel();
1505                self.edit_id_resolvers
1506                    .entry(anchor.timestamp)
1507                    .or_default()
1508                    .push(tx);
1509                futures.push(rx);
1510            }
1511        }
1512
1513        async move {
1514            for mut future in futures {
1515                if future.recv().await.is_none() {
1516                    Err(anyhow!("gave up waiting for anchors"))?;
1517                }
1518            }
1519            Ok(())
1520        }
1521    }
1522
1523    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
1524        let mut rx = None;
1525        if !self.snapshot.version.observed_all(&version) {
1526            let channel = oneshot::channel();
1527            self.wait_for_version_txs.push((version, channel.0));
1528            rx = Some(channel.1);
1529        }
1530        async move {
1531            if let Some(mut rx) = rx {
1532                if rx.recv().await.is_none() {
1533                    Err(anyhow!("gave up waiting for version"))?;
1534                }
1535            }
1536            Ok(())
1537        }
1538    }
1539
1540    pub fn give_up_waiting(&mut self) {
1541        self.edit_id_resolvers.clear();
1542        self.wait_for_version_txs.clear();
1543    }
1544
1545    fn resolve_edit(&mut self, edit_id: clock::Lamport) {
1546        for mut tx in self
1547            .edit_id_resolvers
1548            .remove(&edit_id)
1549            .into_iter()
1550            .flatten()
1551        {
1552            tx.try_send(()).ok();
1553        }
1554    }
1555}
1556
1557#[cfg(any(test, feature = "test-support"))]
1558impl Buffer {
1559    pub fn edit_via_marked_text(&mut self, marked_string: &str) {
1560        let edits = self.edits_for_marked_text(marked_string);
1561        self.edit(edits);
1562    }
1563
1564    pub fn edits_for_marked_text(&self, marked_string: &str) -> Vec<(Range<usize>, String)> {
1565        let old_text = self.text();
1566        let (new_text, mut ranges) = util::test::marked_text_ranges(marked_string, false);
1567        if ranges.is_empty() {
1568            ranges.push(0..new_text.len());
1569        }
1570
1571        assert_eq!(
1572            old_text[..ranges[0].start],
1573            new_text[..ranges[0].start],
1574            "invalid edit"
1575        );
1576
1577        let mut delta = 0;
1578        let mut edits = Vec::new();
1579        let mut ranges = ranges.into_iter().peekable();
1580
1581        while let Some(inserted_range) = ranges.next() {
1582            let new_start = inserted_range.start;
1583            let old_start = (new_start as isize - delta) as usize;
1584
1585            let following_text = if let Some(next_range) = ranges.peek() {
1586                &new_text[inserted_range.end..next_range.start]
1587            } else {
1588                &new_text[inserted_range.end..]
1589            };
1590
1591            let inserted_len = inserted_range.len();
1592            let deleted_len = old_text[old_start..]
1593                .find(following_text)
1594                .expect("invalid edit");
1595
1596            let old_range = old_start..old_start + deleted_len;
1597            edits.push((old_range, new_text[inserted_range].to_string()));
1598            delta += inserted_len as isize - deleted_len as isize;
1599        }
1600
1601        assert_eq!(
1602            old_text.len() as isize + delta,
1603            new_text.len() as isize,
1604            "invalid edit"
1605        );
1606
1607        edits
1608    }
1609
1610    pub fn check_invariants(&self) {
1611        // Ensure every fragment is ordered by locator in the fragment tree and corresponds
1612        // to an insertion fragment in the insertions tree.
1613        let mut prev_fragment_id = Locator::min();
1614        for fragment in self.snapshot.fragments.items(&None) {
1615            assert!(fragment.id > prev_fragment_id);
1616            prev_fragment_id = fragment.id.clone();
1617
1618            let insertion_fragment = self
1619                .snapshot
1620                .insertions
1621                .get(
1622                    &InsertionFragmentKey {
1623                        timestamp: fragment.timestamp,
1624                        split_offset: fragment.insertion_offset,
1625                    },
1626                    &(),
1627                )
1628                .unwrap();
1629            assert_eq!(
1630                insertion_fragment.fragment_id, fragment.id,
1631                "fragment: {:?}\ninsertion: {:?}",
1632                fragment, insertion_fragment
1633            );
1634        }
1635
1636        let mut cursor = self.snapshot.fragments.cursor::<Option<&Locator>>();
1637        for insertion_fragment in self.snapshot.insertions.cursor::<()>() {
1638            cursor.seek(&Some(&insertion_fragment.fragment_id), Bias::Left, &None);
1639            let fragment = cursor.item().unwrap();
1640            assert_eq!(insertion_fragment.fragment_id, fragment.id);
1641            assert_eq!(insertion_fragment.split_offset, fragment.insertion_offset);
1642        }
1643
1644        let fragment_summary = self.snapshot.fragments.summary();
1645        assert_eq!(
1646            fragment_summary.text.visible,
1647            self.snapshot.visible_text.len()
1648        );
1649        assert_eq!(
1650            fragment_summary.text.deleted,
1651            self.snapshot.deleted_text.len()
1652        );
1653
1654        assert!(!self.text().contains("\r\n"));
1655    }
1656
1657    pub fn set_group_interval(&mut self, group_interval: Duration) {
1658        self.history.group_interval = group_interval;
1659    }
1660
1661    pub fn random_byte_range(&self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
1662        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
1663        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
1664        start..end
1665    }
1666
1667    pub fn get_random_edits<T>(
1668        &self,
1669        rng: &mut T,
1670        edit_count: usize,
1671    ) -> Vec<(Range<usize>, Arc<str>)>
1672    where
1673        T: rand::Rng,
1674    {
1675        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1676        let mut last_end = None;
1677        for _ in 0..edit_count {
1678            if last_end.map_or(false, |last_end| last_end >= self.len()) {
1679                break;
1680            }
1681            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1682            let range = self.random_byte_range(new_start, rng);
1683            last_end = Some(range.end);
1684
1685            let new_text_len = rng.gen_range(0..10);
1686            let new_text: String = RandomCharIter::new(&mut *rng).take(new_text_len).collect();
1687
1688            edits.push((range, new_text.into()));
1689        }
1690        edits
1691    }
1692
1693    pub fn randomly_edit<T>(
1694        &mut self,
1695        rng: &mut T,
1696        edit_count: usize,
1697    ) -> (Vec<(Range<usize>, Arc<str>)>, Operation)
1698    where
1699        T: rand::Rng,
1700    {
1701        let mut edits = self.get_random_edits(rng, edit_count);
1702        log::info!("mutating buffer {} with {:?}", self.replica_id, edits);
1703
1704        let op = self.edit(edits.iter().cloned());
1705        if let Operation::Edit(edit) = &op {
1706            assert_eq!(edits.len(), edit.new_text.len());
1707            for (edit, new_text) in edits.iter_mut().zip(&edit.new_text) {
1708                edit.1 = new_text.clone();
1709            }
1710        } else {
1711            unreachable!()
1712        }
1713
1714        (edits, op)
1715    }
1716
1717    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng) -> Vec<Operation> {
1718        use rand::prelude::*;
1719
1720        let mut ops = Vec::new();
1721        for _ in 0..rng.gen_range(1..=5) {
1722            if let Some(entry) = self.history.undo_stack.choose(rng) {
1723                let transaction = entry.transaction.clone();
1724                log::info!(
1725                    "undoing buffer {} transaction {:?}",
1726                    self.replica_id,
1727                    transaction
1728                );
1729                ops.push(self.undo_or_redo(transaction).unwrap());
1730            }
1731        }
1732        ops
1733    }
1734}
1735
1736impl Deref for Buffer {
1737    type Target = BufferSnapshot;
1738
1739    fn deref(&self) -> &Self::Target {
1740        &self.snapshot
1741    }
1742}
1743
1744impl BufferSnapshot {
1745    pub fn as_rope(&self) -> &Rope {
1746        &self.visible_text
1747    }
1748
1749    pub fn rope_for_version(&self, version: &clock::Global) -> Rope {
1750        let mut rope = Rope::new();
1751
1752        let mut cursor = self
1753            .fragments
1754            .filter::<_, FragmentTextSummary>(move |summary| {
1755                !version.observed_all(&summary.max_version)
1756            });
1757        cursor.next(&None);
1758
1759        let mut visible_cursor = self.visible_text.cursor(0);
1760        let mut deleted_cursor = self.deleted_text.cursor(0);
1761
1762        while let Some(fragment) = cursor.item() {
1763            if cursor.start().visible > visible_cursor.offset() {
1764                let text = visible_cursor.slice(cursor.start().visible);
1765                rope.append(text);
1766            }
1767
1768            if fragment.was_visible(version, &self.undo_map) {
1769                if fragment.visible {
1770                    let text = visible_cursor.slice(cursor.end(&None).visible);
1771                    rope.append(text);
1772                } else {
1773                    deleted_cursor.seek_forward(cursor.start().deleted);
1774                    let text = deleted_cursor.slice(cursor.end(&None).deleted);
1775                    rope.append(text);
1776                }
1777            } else if fragment.visible {
1778                visible_cursor.seek_forward(cursor.end(&None).visible);
1779            }
1780
1781            cursor.next(&None);
1782        }
1783
1784        if cursor.start().visible > visible_cursor.offset() {
1785            let text = visible_cursor.slice(cursor.start().visible);
1786            rope.append(text);
1787        }
1788
1789        rope
1790    }
1791
1792    pub fn remote_id(&self) -> BufferId {
1793        self.remote_id
1794    }
1795
1796    pub fn replica_id(&self) -> ReplicaId {
1797        self.replica_id
1798    }
1799
1800    pub fn row_count(&self) -> u32 {
1801        self.max_point().row + 1
1802    }
1803
1804    pub fn len(&self) -> usize {
1805        self.visible_text.len()
1806    }
1807
1808    pub fn is_empty(&self) -> bool {
1809        self.len() == 0
1810    }
1811
1812    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
1813        self.chars_at(0)
1814    }
1815
1816    pub fn chars_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = char> + '_ {
1817        self.text_for_range(range).flat_map(str::chars)
1818    }
1819
1820    pub fn reversed_chars_for_range<T: ToOffset>(
1821        &self,
1822        range: Range<T>,
1823    ) -> impl Iterator<Item = char> + '_ {
1824        self.reversed_chunks_in_range(range)
1825            .flat_map(|chunk| chunk.chars().rev())
1826    }
1827
1828    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1829    where
1830        T: ToOffset,
1831    {
1832        let position = position.to_offset(self);
1833        position == self.clip_offset(position, Bias::Left)
1834            && self
1835                .bytes_in_range(position..self.len())
1836                .flatten()
1837                .copied()
1838                .take(needle.len())
1839                .eq(needle.bytes())
1840    }
1841
1842    pub fn common_prefix_at<T>(&self, position: T, needle: &str) -> Range<T>
1843    where
1844        T: ToOffset + TextDimension,
1845    {
1846        let offset = position.to_offset(self);
1847        let common_prefix_len = needle
1848            .char_indices()
1849            .map(|(index, _)| index)
1850            .chain([needle.len()])
1851            .take_while(|&len| len <= offset)
1852            .filter(|&len| {
1853                let left = self
1854                    .chars_for_range(offset - len..offset)
1855                    .flat_map(char::to_lowercase);
1856                let right = needle[..len].chars().flat_map(char::to_lowercase);
1857                left.eq(right)
1858            })
1859            .last()
1860            .unwrap_or(0);
1861        let start_offset = offset - common_prefix_len;
1862        let start = self.text_summary_for_range(0..start_offset);
1863        start..position
1864    }
1865
1866    pub fn text(&self) -> String {
1867        self.visible_text.to_string()
1868    }
1869
1870    pub fn line_ending(&self) -> LineEnding {
1871        self.line_ending
1872    }
1873
1874    pub fn deleted_text(&self) -> String {
1875        self.deleted_text.to_string()
1876    }
1877
1878    pub fn fragments(&self) -> impl Iterator<Item = &Fragment> {
1879        self.fragments.iter()
1880    }
1881
1882    pub fn text_summary(&self) -> TextSummary {
1883        self.visible_text.summary()
1884    }
1885
1886    pub fn max_point(&self) -> Point {
1887        self.visible_text.max_point()
1888    }
1889
1890    pub fn max_point_utf16(&self) -> PointUtf16 {
1891        self.visible_text.max_point_utf16()
1892    }
1893
1894    pub fn point_to_offset(&self, point: Point) -> usize {
1895        self.visible_text.point_to_offset(point)
1896    }
1897
1898    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1899        self.visible_text.point_utf16_to_offset(point)
1900    }
1901
1902    pub fn unclipped_point_utf16_to_offset(&self, point: Unclipped<PointUtf16>) -> usize {
1903        self.visible_text.unclipped_point_utf16_to_offset(point)
1904    }
1905
1906    pub fn unclipped_point_utf16_to_point(&self, point: Unclipped<PointUtf16>) -> Point {
1907        self.visible_text.unclipped_point_utf16_to_point(point)
1908    }
1909
1910    pub fn offset_utf16_to_offset(&self, offset: OffsetUtf16) -> usize {
1911        self.visible_text.offset_utf16_to_offset(offset)
1912    }
1913
1914    pub fn offset_to_offset_utf16(&self, offset: usize) -> OffsetUtf16 {
1915        self.visible_text.offset_to_offset_utf16(offset)
1916    }
1917
1918    pub fn offset_to_point(&self, offset: usize) -> Point {
1919        self.visible_text.offset_to_point(offset)
1920    }
1921
1922    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1923        self.visible_text.offset_to_point_utf16(offset)
1924    }
1925
1926    pub fn point_to_point_utf16(&self, point: Point) -> PointUtf16 {
1927        self.visible_text.point_to_point_utf16(point)
1928    }
1929
1930    pub fn version(&self) -> &clock::Global {
1931        &self.version
1932    }
1933
1934    pub fn chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1935        let offset = position.to_offset(self);
1936        self.visible_text.chars_at(offset)
1937    }
1938
1939    pub fn reversed_chars_at<T: ToOffset>(&self, position: T) -> impl Iterator<Item = char> + '_ {
1940        let offset = position.to_offset(self);
1941        self.visible_text.reversed_chars_at(offset)
1942    }
1943
1944    pub fn reversed_chunks_in_range<T: ToOffset>(&self, range: Range<T>) -> rope::Chunks {
1945        let range = range.start.to_offset(self)..range.end.to_offset(self);
1946        self.visible_text.reversed_chunks_in_range(range)
1947    }
1948
1949    pub fn bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> rope::Bytes<'_> {
1950        let start = range.start.to_offset(self);
1951        let end = range.end.to_offset(self);
1952        self.visible_text.bytes_in_range(start..end)
1953    }
1954
1955    pub fn reversed_bytes_in_range<T: ToOffset>(&self, range: Range<T>) -> rope::Bytes<'_> {
1956        let start = range.start.to_offset(self);
1957        let end = range.end.to_offset(self);
1958        self.visible_text.reversed_bytes_in_range(start..end)
1959    }
1960
1961    pub fn text_for_range<T: ToOffset>(&self, range: Range<T>) -> Chunks<'_> {
1962        let start = range.start.to_offset(self);
1963        let end = range.end.to_offset(self);
1964        self.visible_text.chunks_in_range(start..end)
1965    }
1966
1967    pub fn line_len(&self, row: u32) -> u32 {
1968        let row_start_offset = Point::new(row, 0).to_offset(self);
1969        let row_end_offset = if row >= self.max_point().row {
1970            self.len()
1971        } else {
1972            Point::new(row + 1, 0).to_offset(self) - 1
1973        };
1974        (row_end_offset - row_start_offset) as u32
1975    }
1976
1977    pub fn line_indents_in_row_range(
1978        &self,
1979        row_range: Range<u32>,
1980    ) -> impl Iterator<Item = (u32, LineIndent)> + '_ {
1981        let start = Point::new(row_range.start, 0).to_offset(self);
1982        let end = Point::new(row_range.end, 0).to_offset(self);
1983
1984        let mut lines = self.as_rope().chunks_in_range(start..end).lines();
1985        let mut row = row_range.start;
1986        std::iter::from_fn(move || {
1987            if let Some(line) = lines.next() {
1988                let indent = LineIndent::from(line);
1989                row += 1;
1990                Some((row - 1, indent))
1991            } else {
1992                None
1993            }
1994        })
1995    }
1996
1997    pub fn reversed_line_indents_in_row_range(
1998        &self,
1999        row_range: Range<u32>,
2000    ) -> impl Iterator<Item = (u32, LineIndent)> + '_ {
2001        let start = Point::new(row_range.start, 0).to_offset(self);
2002        let end = Point::new(row_range.end, 0)
2003            .to_offset(self)
2004            .saturating_sub(1);
2005
2006        let mut lines = self.as_rope().reversed_chunks_in_range(start..end).lines();
2007        let mut row = row_range.end;
2008        std::iter::from_fn(move || {
2009            if let Some(line) = lines.next() {
2010                let indent = LineIndent::from(line);
2011                row = row.saturating_sub(1);
2012                Some((row, indent))
2013            } else {
2014                None
2015            }
2016        })
2017    }
2018
2019    pub fn line_indent_for_row(&self, row: u32) -> LineIndent {
2020        LineIndent::from_iter(self.chars_at(Point::new(row, 0)))
2021    }
2022
2023    pub fn is_line_blank(&self, row: u32) -> bool {
2024        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
2025            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
2026    }
2027
2028    pub fn text_summary_for_range<D, O: ToOffset>(&self, range: Range<O>) -> D
2029    where
2030        D: TextDimension,
2031    {
2032        self.visible_text
2033            .cursor(range.start.to_offset(self))
2034            .summary(range.end.to_offset(self))
2035    }
2036
2037    pub fn summaries_for_anchors<'a, D, A>(&'a self, anchors: A) -> impl 'a + Iterator<Item = D>
2038    where
2039        D: 'a + TextDimension,
2040        A: 'a + IntoIterator<Item = &'a Anchor>,
2041    {
2042        let anchors = anchors.into_iter();
2043        self.summaries_for_anchors_with_payload::<D, _, ()>(anchors.map(|a| (a, ())))
2044            .map(|d| d.0)
2045    }
2046
2047    pub fn summaries_for_anchors_with_payload<'a, D, A, T>(
2048        &'a self,
2049        anchors: A,
2050    ) -> impl 'a + Iterator<Item = (D, T)>
2051    where
2052        D: 'a + TextDimension,
2053        A: 'a + IntoIterator<Item = (&'a Anchor, T)>,
2054    {
2055        let anchors = anchors.into_iter();
2056        let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
2057        let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
2058        let mut text_cursor = self.visible_text.cursor(0);
2059        let mut position = D::default();
2060
2061        anchors.map(move |(anchor, payload)| {
2062            if *anchor == Anchor::MIN {
2063                return (D::default(), payload);
2064            } else if *anchor == Anchor::MAX {
2065                return (D::from_text_summary(&self.visible_text.summary()), payload);
2066            }
2067
2068            let anchor_key = InsertionFragmentKey {
2069                timestamp: anchor.timestamp,
2070                split_offset: anchor.offset,
2071            };
2072            insertion_cursor.seek(&anchor_key, anchor.bias, &());
2073            if let Some(insertion) = insertion_cursor.item() {
2074                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
2075                if comparison == Ordering::Greater
2076                    || (anchor.bias == Bias::Left
2077                        && comparison == Ordering::Equal
2078                        && anchor.offset > 0)
2079                {
2080                    insertion_cursor.prev(&());
2081                }
2082            } else {
2083                insertion_cursor.prev(&());
2084            }
2085            let insertion = insertion_cursor.item().expect("invalid insertion");
2086            assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
2087
2088            fragment_cursor.seek_forward(&Some(&insertion.fragment_id), Bias::Left, &None);
2089            let fragment = fragment_cursor.item().unwrap();
2090            let mut fragment_offset = fragment_cursor.start().1;
2091            if fragment.visible {
2092                fragment_offset += anchor.offset - insertion.split_offset;
2093            }
2094
2095            position.add_assign(&text_cursor.summary(fragment_offset));
2096            (position.clone(), payload)
2097        })
2098    }
2099
2100    fn summary_for_anchor<D>(&self, anchor: &Anchor) -> D
2101    where
2102        D: TextDimension,
2103    {
2104        if *anchor == Anchor::MIN {
2105            D::default()
2106        } else if *anchor == Anchor::MAX {
2107            D::from_text_summary(&self.visible_text.summary())
2108        } else {
2109            let anchor_key = InsertionFragmentKey {
2110                timestamp: anchor.timestamp,
2111                split_offset: anchor.offset,
2112            };
2113            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
2114            insertion_cursor.seek(&anchor_key, anchor.bias, &());
2115            if let Some(insertion) = insertion_cursor.item() {
2116                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
2117                if comparison == Ordering::Greater
2118                    || (anchor.bias == Bias::Left
2119                        && comparison == Ordering::Equal
2120                        && anchor.offset > 0)
2121                {
2122                    insertion_cursor.prev(&());
2123                }
2124            } else {
2125                insertion_cursor.prev(&());
2126            }
2127
2128            let Some(insertion) = insertion_cursor
2129                .item()
2130                .filter(|insertion| insertion.timestamp == anchor.timestamp)
2131            else {
2132                panic!(
2133                    "invalid anchor {:?}. buffer id: {}, version: {:?}",
2134                    anchor, self.remote_id, self.version
2135                );
2136            };
2137
2138            let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
2139            fragment_cursor.seek(&Some(&insertion.fragment_id), Bias::Left, &None);
2140            let fragment = fragment_cursor.item().unwrap();
2141            let mut fragment_offset = fragment_cursor.start().1;
2142            if fragment.visible {
2143                fragment_offset += anchor.offset - insertion.split_offset;
2144            }
2145            self.text_summary_for_range(0..fragment_offset)
2146        }
2147    }
2148
2149    fn fragment_id_for_anchor(&self, anchor: &Anchor) -> &Locator {
2150        if *anchor == Anchor::MIN {
2151            Locator::min_ref()
2152        } else if *anchor == Anchor::MAX {
2153            Locator::max_ref()
2154        } else {
2155            let anchor_key = InsertionFragmentKey {
2156                timestamp: anchor.timestamp,
2157                split_offset: anchor.offset,
2158            };
2159            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
2160            insertion_cursor.seek(&anchor_key, anchor.bias, &());
2161            if let Some(insertion) = insertion_cursor.item() {
2162                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
2163                if comparison == Ordering::Greater
2164                    || (anchor.bias == Bias::Left
2165                        && comparison == Ordering::Equal
2166                        && anchor.offset > 0)
2167                {
2168                    insertion_cursor.prev(&());
2169                }
2170            } else {
2171                insertion_cursor.prev(&());
2172            }
2173
2174            let Some(insertion) = insertion_cursor.item().filter(|insertion| {
2175                if cfg!(debug_assertions) {
2176                    insertion.timestamp == anchor.timestamp
2177                } else {
2178                    true
2179                }
2180            }) else {
2181                panic!(
2182                    "invalid anchor {:?}. buffer id: {}, version: {:?}",
2183                    anchor, self.remote_id, self.version
2184                );
2185            };
2186
2187            &insertion.fragment_id
2188        }
2189    }
2190
2191    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
2192        self.anchor_at(position, Bias::Left)
2193    }
2194
2195    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
2196        self.anchor_at(position, Bias::Right)
2197    }
2198
2199    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
2200        self.anchor_at_offset(position.to_offset(self), bias)
2201    }
2202
2203    fn anchor_at_offset(&self, offset: usize, bias: Bias) -> Anchor {
2204        if bias == Bias::Left && offset == 0 {
2205            Anchor::MIN
2206        } else if bias == Bias::Right && offset == self.len() {
2207            Anchor::MAX
2208        } else {
2209            let mut fragment_cursor = self.fragments.cursor::<usize>();
2210            fragment_cursor.seek(&offset, bias, &None);
2211            let fragment = fragment_cursor.item().unwrap();
2212            let overshoot = offset - *fragment_cursor.start();
2213            Anchor {
2214                timestamp: fragment.timestamp,
2215                offset: fragment.insertion_offset + overshoot,
2216                bias,
2217                buffer_id: Some(self.remote_id),
2218            }
2219        }
2220    }
2221
2222    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
2223        *anchor == Anchor::MIN
2224            || *anchor == Anchor::MAX
2225            || (Some(self.remote_id) == anchor.buffer_id && self.version.observed(anchor.timestamp))
2226    }
2227
2228    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
2229        self.visible_text.clip_offset(offset, bias)
2230    }
2231
2232    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
2233        self.visible_text.clip_point(point, bias)
2234    }
2235
2236    pub fn clip_offset_utf16(&self, offset: OffsetUtf16, bias: Bias) -> OffsetUtf16 {
2237        self.visible_text.clip_offset_utf16(offset, bias)
2238    }
2239
2240    pub fn clip_point_utf16(&self, point: Unclipped<PointUtf16>, bias: Bias) -> PointUtf16 {
2241        self.visible_text.clip_point_utf16(point, bias)
2242    }
2243
2244    pub fn edits_since<'a, D>(
2245        &'a self,
2246        since: &'a clock::Global,
2247    ) -> impl 'a + Iterator<Item = Edit<D>>
2248    where
2249        D: TextDimension + Ord,
2250    {
2251        self.edits_since_in_range(since, Anchor::MIN..Anchor::MAX)
2252    }
2253
2254    pub fn anchored_edits_since<'a, D>(
2255        &'a self,
2256        since: &'a clock::Global,
2257    ) -> impl 'a + Iterator<Item = (Edit<D>, Range<Anchor>)>
2258    where
2259        D: TextDimension + Ord,
2260    {
2261        self.anchored_edits_since_in_range(since, Anchor::MIN..Anchor::MAX)
2262    }
2263
2264    pub fn edits_since_in_range<'a, D>(
2265        &'a self,
2266        since: &'a clock::Global,
2267        range: Range<Anchor>,
2268    ) -> impl 'a + Iterator<Item = Edit<D>>
2269    where
2270        D: TextDimension + Ord,
2271    {
2272        self.anchored_edits_since_in_range(since, range)
2273            .map(|item| item.0)
2274    }
2275
2276    pub fn anchored_edits_since_in_range<'a, D>(
2277        &'a self,
2278        since: &'a clock::Global,
2279        range: Range<Anchor>,
2280    ) -> impl 'a + Iterator<Item = (Edit<D>, Range<Anchor>)>
2281    where
2282        D: TextDimension + Ord,
2283    {
2284        let fragments_cursor = if *since == self.version {
2285            None
2286        } else {
2287            let mut cursor = self
2288                .fragments
2289                .filter(move |summary| !since.observed_all(&summary.max_version));
2290            cursor.next(&None);
2291            Some(cursor)
2292        };
2293        let mut cursor = self
2294            .fragments
2295            .cursor::<(Option<&Locator>, FragmentTextSummary)>();
2296
2297        let start_fragment_id = self.fragment_id_for_anchor(&range.start);
2298        cursor.seek(&Some(start_fragment_id), Bias::Left, &None);
2299        let mut visible_start = cursor.start().1.visible;
2300        let mut deleted_start = cursor.start().1.deleted;
2301        if let Some(fragment) = cursor.item() {
2302            let overshoot = range.start.offset - fragment.insertion_offset;
2303            if fragment.visible {
2304                visible_start += overshoot;
2305            } else {
2306                deleted_start += overshoot;
2307            }
2308        }
2309        let end_fragment_id = self.fragment_id_for_anchor(&range.end);
2310
2311        Edits {
2312            visible_cursor: self.visible_text.cursor(visible_start),
2313            deleted_cursor: self.deleted_text.cursor(deleted_start),
2314            fragments_cursor,
2315            undos: &self.undo_map,
2316            since,
2317            old_end: Default::default(),
2318            new_end: Default::default(),
2319            range: (start_fragment_id, range.start.offset)..(end_fragment_id, range.end.offset),
2320            buffer_id: self.remote_id,
2321        }
2322    }
2323
2324    pub fn has_edits_since_in_range(&self, since: &clock::Global, range: Range<Anchor>) -> bool {
2325        if *since != self.version {
2326            let start_fragment_id = self.fragment_id_for_anchor(&range.start);
2327            let end_fragment_id = self.fragment_id_for_anchor(&range.end);
2328            let mut cursor = self
2329                .fragments
2330                .filter::<_, usize>(move |summary| !since.observed_all(&summary.max_version));
2331            cursor.next(&None);
2332            while let Some(fragment) = cursor.item() {
2333                if fragment.id > *end_fragment_id {
2334                    break;
2335                }
2336                if fragment.id > *start_fragment_id {
2337                    let was_visible = fragment.was_visible(since, &self.undo_map);
2338                    let is_visible = fragment.visible;
2339                    if was_visible != is_visible {
2340                        return true;
2341                    }
2342                }
2343                cursor.next(&None);
2344            }
2345        }
2346        false
2347    }
2348
2349    pub fn has_edits_since(&self, since: &clock::Global) -> bool {
2350        if *since != self.version {
2351            let mut cursor = self
2352                .fragments
2353                .filter::<_, usize>(move |summary| !since.observed_all(&summary.max_version));
2354            cursor.next(&None);
2355            while let Some(fragment) = cursor.item() {
2356                let was_visible = fragment.was_visible(since, &self.undo_map);
2357                let is_visible = fragment.visible;
2358                if was_visible != is_visible {
2359                    return true;
2360                }
2361                cursor.next(&None);
2362            }
2363        }
2364        false
2365    }
2366}
2367
2368struct RopeBuilder<'a> {
2369    old_visible_cursor: rope::Cursor<'a>,
2370    old_deleted_cursor: rope::Cursor<'a>,
2371    new_visible: Rope,
2372    new_deleted: Rope,
2373}
2374
2375impl<'a> RopeBuilder<'a> {
2376    fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
2377        Self {
2378            old_visible_cursor,
2379            old_deleted_cursor,
2380            new_visible: Rope::new(),
2381            new_deleted: Rope::new(),
2382        }
2383    }
2384
2385    fn append(&mut self, len: FragmentTextSummary) {
2386        self.push(len.visible, true, true);
2387        self.push(len.deleted, false, false);
2388    }
2389
2390    fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
2391        debug_assert!(fragment.len > 0);
2392        self.push(fragment.len, was_visible, fragment.visible)
2393    }
2394
2395    fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
2396        let text = if was_visible {
2397            self.old_visible_cursor
2398                .slice(self.old_visible_cursor.offset() + len)
2399        } else {
2400            self.old_deleted_cursor
2401                .slice(self.old_deleted_cursor.offset() + len)
2402        };
2403        if is_visible {
2404            self.new_visible.append(text);
2405        } else {
2406            self.new_deleted.append(text);
2407        }
2408    }
2409
2410    fn push_str(&mut self, text: &str) {
2411        self.new_visible.push(text);
2412    }
2413
2414    fn finish(mut self) -> (Rope, Rope) {
2415        self.new_visible.append(self.old_visible_cursor.suffix());
2416        self.new_deleted.append(self.old_deleted_cursor.suffix());
2417        (self.new_visible, self.new_deleted)
2418    }
2419}
2420
2421impl<'a, D: TextDimension + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator for Edits<'a, D, F> {
2422    type Item = (Edit<D>, Range<Anchor>);
2423
2424    fn next(&mut self) -> Option<Self::Item> {
2425        let mut pending_edit: Option<Self::Item> = None;
2426        let cursor = self.fragments_cursor.as_mut()?;
2427
2428        while let Some(fragment) = cursor.item() {
2429            if fragment.id < *self.range.start.0 {
2430                cursor.next(&None);
2431                continue;
2432            } else if fragment.id > *self.range.end.0 {
2433                break;
2434            }
2435
2436            if cursor.start().visible > self.visible_cursor.offset() {
2437                let summary = self.visible_cursor.summary(cursor.start().visible);
2438                self.old_end.add_assign(&summary);
2439                self.new_end.add_assign(&summary);
2440            }
2441
2442            if pending_edit
2443                .as_ref()
2444                .map_or(false, |(change, _)| change.new.end < self.new_end)
2445            {
2446                break;
2447            }
2448
2449            let start_anchor = Anchor {
2450                timestamp: fragment.timestamp,
2451                offset: fragment.insertion_offset,
2452                bias: Bias::Right,
2453                buffer_id: Some(self.buffer_id),
2454            };
2455            let end_anchor = Anchor {
2456                timestamp: fragment.timestamp,
2457                offset: fragment.insertion_offset + fragment.len,
2458                bias: Bias::Left,
2459                buffer_id: Some(self.buffer_id),
2460            };
2461
2462            if !fragment.was_visible(self.since, self.undos) && fragment.visible {
2463                let mut visible_end = cursor.end(&None).visible;
2464                if fragment.id == *self.range.end.0 {
2465                    visible_end = cmp::min(
2466                        visible_end,
2467                        cursor.start().visible + (self.range.end.1 - fragment.insertion_offset),
2468                    );
2469                }
2470
2471                let fragment_summary = self.visible_cursor.summary(visible_end);
2472                let mut new_end = self.new_end.clone();
2473                new_end.add_assign(&fragment_summary);
2474                if let Some((edit, range)) = pending_edit.as_mut() {
2475                    edit.new.end = new_end.clone();
2476                    range.end = end_anchor;
2477                } else {
2478                    pending_edit = Some((
2479                        Edit {
2480                            old: self.old_end.clone()..self.old_end.clone(),
2481                            new: self.new_end.clone()..new_end.clone(),
2482                        },
2483                        start_anchor..end_anchor,
2484                    ));
2485                }
2486
2487                self.new_end = new_end;
2488            } else if fragment.was_visible(self.since, self.undos) && !fragment.visible {
2489                let mut deleted_end = cursor.end(&None).deleted;
2490                if fragment.id == *self.range.end.0 {
2491                    deleted_end = cmp::min(
2492                        deleted_end,
2493                        cursor.start().deleted + (self.range.end.1 - fragment.insertion_offset),
2494                    );
2495                }
2496
2497                if cursor.start().deleted > self.deleted_cursor.offset() {
2498                    self.deleted_cursor.seek_forward(cursor.start().deleted);
2499                }
2500                let fragment_summary = self.deleted_cursor.summary(deleted_end);
2501                let mut old_end = self.old_end.clone();
2502                old_end.add_assign(&fragment_summary);
2503                if let Some((edit, range)) = pending_edit.as_mut() {
2504                    edit.old.end = old_end.clone();
2505                    range.end = end_anchor;
2506                } else {
2507                    pending_edit = Some((
2508                        Edit {
2509                            old: self.old_end.clone()..old_end.clone(),
2510                            new: self.new_end.clone()..self.new_end.clone(),
2511                        },
2512                        start_anchor..end_anchor,
2513                    ));
2514                }
2515
2516                self.old_end = old_end;
2517            }
2518
2519            cursor.next(&None);
2520        }
2521
2522        pending_edit
2523    }
2524}
2525
2526impl Fragment {
2527    fn insertion_slice(&self) -> InsertionSlice {
2528        InsertionSlice {
2529            insertion_id: self.timestamp,
2530            range: self.insertion_offset..self.insertion_offset + self.len,
2531        }
2532    }
2533
2534    fn is_visible(&self, undos: &UndoMap) -> bool {
2535        !undos.is_undone(self.timestamp) && self.deletions.iter().all(|d| undos.is_undone(*d))
2536    }
2537
2538    fn was_visible(&self, version: &clock::Global, undos: &UndoMap) -> bool {
2539        (version.observed(self.timestamp) && !undos.was_undone(self.timestamp, version))
2540            && self
2541                .deletions
2542                .iter()
2543                .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
2544    }
2545}
2546
2547impl sum_tree::Item for Fragment {
2548    type Summary = FragmentSummary;
2549
2550    fn summary(&self) -> Self::Summary {
2551        let mut max_version = clock::Global::new();
2552        max_version.observe(self.timestamp);
2553        for deletion in &self.deletions {
2554            max_version.observe(*deletion);
2555        }
2556        max_version.join(&self.max_undos);
2557
2558        let mut min_insertion_version = clock::Global::new();
2559        min_insertion_version.observe(self.timestamp);
2560        let max_insertion_version = min_insertion_version.clone();
2561        if self.visible {
2562            FragmentSummary {
2563                max_id: self.id.clone(),
2564                text: FragmentTextSummary {
2565                    visible: self.len,
2566                    deleted: 0,
2567                },
2568                max_version,
2569                min_insertion_version,
2570                max_insertion_version,
2571            }
2572        } else {
2573            FragmentSummary {
2574                max_id: self.id.clone(),
2575                text: FragmentTextSummary {
2576                    visible: 0,
2577                    deleted: self.len,
2578                },
2579                max_version,
2580                min_insertion_version,
2581                max_insertion_version,
2582            }
2583        }
2584    }
2585}
2586
2587impl sum_tree::Summary for FragmentSummary {
2588    type Context = Option<clock::Global>;
2589
2590    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2591        self.max_id.assign(&other.max_id);
2592        self.text.visible += &other.text.visible;
2593        self.text.deleted += &other.text.deleted;
2594        self.max_version.join(&other.max_version);
2595        self.min_insertion_version
2596            .meet(&other.min_insertion_version);
2597        self.max_insertion_version
2598            .join(&other.max_insertion_version);
2599    }
2600}
2601
2602impl Default for FragmentSummary {
2603    fn default() -> Self {
2604        FragmentSummary {
2605            max_id: Locator::min(),
2606            text: FragmentTextSummary::default(),
2607            max_version: clock::Global::new(),
2608            min_insertion_version: clock::Global::new(),
2609            max_insertion_version: clock::Global::new(),
2610        }
2611    }
2612}
2613
2614impl sum_tree::Item for InsertionFragment {
2615    type Summary = InsertionFragmentKey;
2616
2617    fn summary(&self) -> Self::Summary {
2618        InsertionFragmentKey {
2619            timestamp: self.timestamp,
2620            split_offset: self.split_offset,
2621        }
2622    }
2623}
2624
2625impl sum_tree::KeyedItem for InsertionFragment {
2626    type Key = InsertionFragmentKey;
2627
2628    fn key(&self) -> Self::Key {
2629        sum_tree::Item::summary(self)
2630    }
2631}
2632
2633impl InsertionFragment {
2634    fn new(fragment: &Fragment) -> Self {
2635        Self {
2636            timestamp: fragment.timestamp,
2637            split_offset: fragment.insertion_offset,
2638            fragment_id: fragment.id.clone(),
2639        }
2640    }
2641
2642    fn insert_new(fragment: &Fragment) -> sum_tree::Edit<Self> {
2643        sum_tree::Edit::Insert(Self::new(fragment))
2644    }
2645}
2646
2647impl sum_tree::Summary for InsertionFragmentKey {
2648    type Context = ();
2649
2650    fn add_summary(&mut self, summary: &Self, _: &()) {
2651        *self = *summary;
2652    }
2653}
2654
2655#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
2656pub struct FullOffset(pub usize);
2657
2658impl ops::AddAssign<usize> for FullOffset {
2659    fn add_assign(&mut self, rhs: usize) {
2660        self.0 += rhs;
2661    }
2662}
2663
2664impl ops::Add<usize> for FullOffset {
2665    type Output = Self;
2666
2667    fn add(mut self, rhs: usize) -> Self::Output {
2668        self += rhs;
2669        self
2670    }
2671}
2672
2673impl ops::Sub for FullOffset {
2674    type Output = usize;
2675
2676    fn sub(self, rhs: Self) -> Self::Output {
2677        self.0 - rhs.0
2678    }
2679}
2680
2681impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2682    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2683        *self += summary.text.visible;
2684    }
2685}
2686
2687impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FullOffset {
2688    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2689        self.0 += summary.text.visible + summary.text.deleted;
2690    }
2691}
2692
2693impl<'a> sum_tree::Dimension<'a, FragmentSummary> for Option<&'a Locator> {
2694    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2695        *self = Some(&summary.max_id);
2696    }
2697}
2698
2699impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, FragmentTextSummary> for usize {
2700    fn cmp(
2701        &self,
2702        cursor_location: &FragmentTextSummary,
2703        _: &Option<clock::Global>,
2704    ) -> cmp::Ordering {
2705        Ord::cmp(self, &cursor_location.visible)
2706    }
2707}
2708
2709#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2710enum VersionedFullOffset {
2711    Offset(FullOffset),
2712    Invalid,
2713}
2714
2715impl VersionedFullOffset {
2716    fn full_offset(&self) -> FullOffset {
2717        if let Self::Offset(position) = self {
2718            *position
2719        } else {
2720            panic!("invalid version")
2721        }
2722    }
2723}
2724
2725impl Default for VersionedFullOffset {
2726    fn default() -> Self {
2727        Self::Offset(Default::default())
2728    }
2729}
2730
2731impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedFullOffset {
2732    fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<clock::Global>) {
2733        if let Self::Offset(offset) = self {
2734            let version = cx.as_ref().unwrap();
2735            if version.observed_all(&summary.max_insertion_version) {
2736                *offset += summary.text.visible + summary.text.deleted;
2737            } else if version.observed_any(&summary.min_insertion_version) {
2738                *self = Self::Invalid;
2739            }
2740        }
2741    }
2742}
2743
2744impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, Self> for VersionedFullOffset {
2745    fn cmp(&self, cursor_position: &Self, _: &Option<clock::Global>) -> cmp::Ordering {
2746        match (self, cursor_position) {
2747            (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2748            (Self::Offset(_), Self::Invalid) => cmp::Ordering::Less,
2749            (Self::Invalid, _) => unreachable!(),
2750        }
2751    }
2752}
2753
2754impl Operation {
2755    fn replica_id(&self) -> ReplicaId {
2756        operation_queue::Operation::lamport_timestamp(self).replica_id
2757    }
2758
2759    pub fn timestamp(&self) -> clock::Lamport {
2760        match self {
2761            Operation::Edit(edit) => edit.timestamp,
2762            Operation::Undo(undo) => undo.timestamp,
2763        }
2764    }
2765
2766    pub fn as_edit(&self) -> Option<&EditOperation> {
2767        match self {
2768            Operation::Edit(edit) => Some(edit),
2769            _ => None,
2770        }
2771    }
2772
2773    pub fn is_edit(&self) -> bool {
2774        matches!(self, Operation::Edit { .. })
2775    }
2776}
2777
2778impl operation_queue::Operation for Operation {
2779    fn lamport_timestamp(&self) -> clock::Lamport {
2780        match self {
2781            Operation::Edit(edit) => edit.timestamp,
2782            Operation::Undo(undo) => undo.timestamp,
2783        }
2784    }
2785}
2786
2787pub trait ToOffset {
2788    fn to_offset(&self, snapshot: &BufferSnapshot) -> usize;
2789}
2790
2791impl ToOffset for Point {
2792    fn to_offset(&self, snapshot: &BufferSnapshot) -> usize {
2793        snapshot.point_to_offset(*self)
2794    }
2795}
2796
2797impl ToOffset for usize {
2798    fn to_offset(&self, snapshot: &BufferSnapshot) -> usize {
2799        assert!(
2800            *self <= snapshot.len(),
2801            "offset {} is out of range, max allowed is {}",
2802            self,
2803            snapshot.len()
2804        );
2805        *self
2806    }
2807}
2808
2809impl ToOffset for Anchor {
2810    fn to_offset(&self, snapshot: &BufferSnapshot) -> usize {
2811        snapshot.summary_for_anchor(self)
2812    }
2813}
2814
2815impl<'a, T: ToOffset> ToOffset for &'a T {
2816    fn to_offset(&self, content: &BufferSnapshot) -> usize {
2817        (*self).to_offset(content)
2818    }
2819}
2820
2821impl ToOffset for PointUtf16 {
2822    fn to_offset(&self, snapshot: &BufferSnapshot) -> usize {
2823        snapshot.point_utf16_to_offset(*self)
2824    }
2825}
2826
2827impl ToOffset for Unclipped<PointUtf16> {
2828    fn to_offset(&self, snapshot: &BufferSnapshot) -> usize {
2829        snapshot.unclipped_point_utf16_to_offset(*self)
2830    }
2831}
2832
2833pub trait ToPoint {
2834    fn to_point(&self, snapshot: &BufferSnapshot) -> Point;
2835}
2836
2837impl ToPoint for Anchor {
2838    fn to_point(&self, snapshot: &BufferSnapshot) -> Point {
2839        snapshot.summary_for_anchor(self)
2840    }
2841}
2842
2843impl ToPoint for usize {
2844    fn to_point(&self, snapshot: &BufferSnapshot) -> Point {
2845        snapshot.offset_to_point(*self)
2846    }
2847}
2848
2849impl ToPoint for Point {
2850    fn to_point(&self, _: &BufferSnapshot) -> Point {
2851        *self
2852    }
2853}
2854
2855impl ToPoint for Unclipped<PointUtf16> {
2856    fn to_point(&self, snapshot: &BufferSnapshot) -> Point {
2857        snapshot.unclipped_point_utf16_to_point(*self)
2858    }
2859}
2860
2861pub trait ToPointUtf16 {
2862    fn to_point_utf16(&self, snapshot: &BufferSnapshot) -> PointUtf16;
2863}
2864
2865impl ToPointUtf16 for Anchor {
2866    fn to_point_utf16(&self, snapshot: &BufferSnapshot) -> PointUtf16 {
2867        snapshot.summary_for_anchor(self)
2868    }
2869}
2870
2871impl ToPointUtf16 for usize {
2872    fn to_point_utf16(&self, snapshot: &BufferSnapshot) -> PointUtf16 {
2873        snapshot.offset_to_point_utf16(*self)
2874    }
2875}
2876
2877impl ToPointUtf16 for PointUtf16 {
2878    fn to_point_utf16(&self, _: &BufferSnapshot) -> PointUtf16 {
2879        *self
2880    }
2881}
2882
2883impl ToPointUtf16 for Point {
2884    fn to_point_utf16(&self, snapshot: &BufferSnapshot) -> PointUtf16 {
2885        snapshot.point_to_point_utf16(*self)
2886    }
2887}
2888
2889pub trait ToOffsetUtf16 {
2890    fn to_offset_utf16(&self, snapshot: &BufferSnapshot) -> OffsetUtf16;
2891}
2892
2893impl ToOffsetUtf16 for Anchor {
2894    fn to_offset_utf16(&self, snapshot: &BufferSnapshot) -> OffsetUtf16 {
2895        snapshot.summary_for_anchor(self)
2896    }
2897}
2898
2899impl ToOffsetUtf16 for usize {
2900    fn to_offset_utf16(&self, snapshot: &BufferSnapshot) -> OffsetUtf16 {
2901        snapshot.offset_to_offset_utf16(*self)
2902    }
2903}
2904
2905impl ToOffsetUtf16 for OffsetUtf16 {
2906    fn to_offset_utf16(&self, _snapshot: &BufferSnapshot) -> OffsetUtf16 {
2907        *self
2908    }
2909}
2910
2911pub trait FromAnchor {
2912    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self;
2913}
2914
2915impl FromAnchor for Point {
2916    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2917        snapshot.summary_for_anchor(anchor)
2918    }
2919}
2920
2921impl FromAnchor for PointUtf16 {
2922    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2923        snapshot.summary_for_anchor(anchor)
2924    }
2925}
2926
2927impl FromAnchor for usize {
2928    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2929        snapshot.summary_for_anchor(anchor)
2930    }
2931}
2932
2933#[derive(Clone, Copy, Debug, PartialEq)]
2934pub enum LineEnding {
2935    Unix,
2936    Windows,
2937}
2938
2939impl Default for LineEnding {
2940    fn default() -> Self {
2941        #[cfg(unix)]
2942        return Self::Unix;
2943
2944        #[cfg(not(unix))]
2945        return Self::Windows;
2946    }
2947}
2948
2949impl LineEnding {
2950    pub fn as_str(&self) -> &'static str {
2951        match self {
2952            LineEnding::Unix => "\n",
2953            LineEnding::Windows => "\r\n",
2954        }
2955    }
2956
2957    pub fn detect(text: &str) -> Self {
2958        let mut max_ix = cmp::min(text.len(), 1000);
2959        while !text.is_char_boundary(max_ix) {
2960            max_ix -= 1;
2961        }
2962
2963        if let Some(ix) = text[..max_ix].find(['\n']) {
2964            if ix > 0 && text.as_bytes()[ix - 1] == b'\r' {
2965                Self::Windows
2966            } else {
2967                Self::Unix
2968            }
2969        } else {
2970            Self::default()
2971        }
2972    }
2973
2974    pub fn normalize(text: &mut String) {
2975        if let Cow::Owned(replaced) = LINE_SEPARATORS_REGEX.replace_all(text, "\n") {
2976            *text = replaced;
2977        }
2978    }
2979
2980    pub fn normalize_arc(text: Arc<str>) -> Arc<str> {
2981        if let Cow::Owned(replaced) = LINE_SEPARATORS_REGEX.replace_all(&text, "\n") {
2982            replaced.into()
2983        } else {
2984            text
2985        }
2986    }
2987}