buffer.rs

   1pub use crate::{
   2    diagnostic_set::DiagnosticSet,
   3    highlight_map::{HighlightId, HighlightMap},
   4    proto, BracketPair, Grammar, Language, LanguageConfig, LanguageRegistry, PLAIN_TEXT,
   5};
   6use crate::{
   7    diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
   8    outline::OutlineItem,
   9    CodeLabel, Outline,
  10};
  11use anyhow::{anyhow, Result};
  12use clock::ReplicaId;
  13use futures::FutureExt as _;
  14use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, MutableAppContext, Task};
  15use lazy_static::lazy_static;
  16use parking_lot::Mutex;
  17use settings::Settings;
  18use similar::{ChangeTag, TextDiff};
  19use smol::future::yield_now;
  20use std::{
  21    any::Any,
  22    cmp::{self, Ordering},
  23    collections::BTreeMap,
  24    ffi::OsStr,
  25    future::Future,
  26    iter::{self, Iterator, Peekable},
  27    mem,
  28    ops::{Deref, DerefMut, Range},
  29    path::{Path, PathBuf},
  30    str,
  31    sync::Arc,
  32    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  33    vec,
  34};
  35use sum_tree::TreeMap;
  36use text::operation_queue::OperationQueue;
  37pub use text::{Buffer as TextBuffer, BufferSnapshot as TextBufferSnapshot, Operation as _, *};
  38use theme::SyntaxTheme;
  39use tree_sitter::{InputEdit, QueryCursor, Tree};
  40use util::TryFutureExt as _;
  41
  42#[cfg(any(test, feature = "test-support"))]
  43pub use {tree_sitter_rust, tree_sitter_typescript};
  44
  45pub use lsp::DiagnosticSeverity;
  46
  47lazy_static! {
  48    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  49}
  50
  51pub struct Buffer {
  52    text: TextBuffer,
  53    file: Option<Arc<dyn File>>,
  54    saved_version: clock::Global,
  55    saved_version_fingerprint: String,
  56    saved_mtime: SystemTime,
  57    transaction_depth: usize,
  58    was_dirty_before_starting_transaction: Option<bool>,
  59    language: Option<Arc<Language>>,
  60    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  61    pending_autoindent: Option<Task<()>>,
  62    sync_parse_timeout: Duration,
  63    syntax_tree: Mutex<Option<SyntaxTree>>,
  64    parsing_in_background: bool,
  65    parse_count: usize,
  66    diagnostics: DiagnosticSet,
  67    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  68    selections_update_count: usize,
  69    diagnostics_update_count: usize,
  70    diagnostics_timestamp: clock::Lamport,
  71    file_update_count: usize,
  72    completion_triggers: Vec<String>,
  73    deferred_ops: OperationQueue<Operation>,
  74}
  75
  76pub struct BufferSnapshot {
  77    text: text::BufferSnapshot,
  78    tree: Option<Tree>,
  79    file: Option<Arc<dyn File>>,
  80    diagnostics: DiagnosticSet,
  81    diagnostics_update_count: usize,
  82    file_update_count: usize,
  83    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  84    selections_update_count: usize,
  85    language: Option<Arc<Language>>,
  86    parse_count: usize,
  87}
  88
  89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
  90pub struct IndentSize {
  91    pub len: u32,
  92    pub kind: IndentKind,
  93}
  94
  95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
  96pub enum IndentKind {
  97    Space,
  98    Tab,
  99}
 100
 101#[derive(Clone, Debug)]
 102struct SelectionSet {
 103    line_mode: bool,
 104    selections: Arc<[Selection<Anchor>]>,
 105    lamport_timestamp: clock::Lamport,
 106}
 107
 108#[derive(Clone, Debug, PartialEq, Eq)]
 109pub struct GroupId {
 110    source: Arc<str>,
 111    id: usize,
 112}
 113
 114#[derive(Clone, Debug, PartialEq, Eq)]
 115pub struct Diagnostic {
 116    pub code: Option<String>,
 117    pub severity: DiagnosticSeverity,
 118    pub message: String,
 119    pub group_id: usize,
 120    pub is_valid: bool,
 121    pub is_primary: bool,
 122    pub is_disk_based: bool,
 123    pub is_unnecessary: bool,
 124}
 125
 126#[derive(Clone, Debug)]
 127pub struct Completion {
 128    pub old_range: Range<Anchor>,
 129    pub new_text: String,
 130    pub label: CodeLabel,
 131    pub lsp_completion: lsp::CompletionItem,
 132}
 133
 134#[derive(Clone, Debug)]
 135pub struct CodeAction {
 136    pub range: Range<Anchor>,
 137    pub lsp_action: lsp::CodeAction,
 138}
 139
 140#[derive(Clone, Debug, PartialEq, Eq)]
 141pub enum Operation {
 142    Buffer(text::Operation),
 143    UpdateDiagnostics {
 144        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 145        lamport_timestamp: clock::Lamport,
 146    },
 147    UpdateSelections {
 148        selections: Arc<[Selection<Anchor>]>,
 149        lamport_timestamp: clock::Lamport,
 150        line_mode: bool,
 151    },
 152    UpdateCompletionTriggers {
 153        triggers: Vec<String>,
 154        lamport_timestamp: clock::Lamport,
 155    },
 156}
 157
 158#[derive(Clone, Debug, PartialEq, Eq)]
 159pub enum Event {
 160    Operation(Operation),
 161    Edited,
 162    DirtyChanged,
 163    Saved,
 164    FileHandleChanged,
 165    Reloaded,
 166    Reparsed,
 167    DiagnosticsUpdated,
 168    Closed,
 169}
 170
 171pub trait File: Send + Sync {
 172    fn as_local(&self) -> Option<&dyn LocalFile>;
 173
 174    fn is_local(&self) -> bool {
 175        self.as_local().is_some()
 176    }
 177
 178    fn mtime(&self) -> SystemTime;
 179
 180    /// Returns the path of this file relative to the worktree's root directory.
 181    fn path(&self) -> &Arc<Path>;
 182
 183    /// Returns the path of this file relative to the worktree's parent directory (this means it
 184    /// includes the name of the worktree's root folder).
 185    fn full_path(&self, cx: &AppContext) -> PathBuf;
 186
 187    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 188    /// of its worktree, then this method will return the name of the worktree itself.
 189    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr;
 190
 191    fn is_deleted(&self) -> bool;
 192
 193    fn save(
 194        &self,
 195        buffer_id: u64,
 196        text: Rope,
 197        version: clock::Global,
 198        line_ending: LineEnding,
 199        cx: &mut MutableAppContext,
 200    ) -> Task<Result<(clock::Global, String, SystemTime)>>;
 201
 202    fn as_any(&self) -> &dyn Any;
 203
 204    fn to_proto(&self) -> rpc::proto::File;
 205}
 206
 207pub trait LocalFile: File {
 208    /// Returns the absolute path of this file.
 209    fn abs_path(&self, cx: &AppContext) -> PathBuf;
 210
 211    fn load(&self, cx: &AppContext) -> Task<Result<String>>;
 212
 213    fn buffer_reloaded(
 214        &self,
 215        buffer_id: u64,
 216        version: &clock::Global,
 217        fingerprint: String,
 218        line_ending: LineEnding,
 219        mtime: SystemTime,
 220        cx: &mut MutableAppContext,
 221    );
 222}
 223
 224pub(crate) struct QueryCursorHandle(Option<QueryCursor>);
 225
 226#[derive(Clone)]
 227struct SyntaxTree {
 228    tree: Tree,
 229    version: clock::Global,
 230}
 231
 232#[derive(Clone, Debug)]
 233pub enum AutoindentMode {
 234    Block { start_columns: Vec<u32> },
 235    Independent,
 236}
 237
 238#[derive(Clone)]
 239struct AutoindentRequest {
 240    before_edit: BufferSnapshot,
 241    entries: Vec<AutoindentRequestEntry>,
 242    indent_size: IndentSize,
 243    is_block_mode: bool,
 244}
 245
 246#[derive(Clone)]
 247struct AutoindentRequestEntry {
 248    /// A range of the buffer whose indentation should be adjusted.
 249    range: Range<Anchor>,
 250    /// Whether or not these lines should be considered brand new, for the
 251    /// purpose of auto-indent. When text is not new, its indentation will
 252    /// only be adjusted if the suggested indentation level has *changed*
 253    /// since the edit was made.
 254    first_line_is_new: bool,
 255    start_column: Option<u32>,
 256}
 257
 258#[derive(Debug)]
 259struct IndentSuggestion {
 260    basis_row: u32,
 261    delta: Ordering,
 262}
 263
 264pub(crate) struct TextProvider<'a>(pub(crate) &'a Rope);
 265
 266struct BufferChunkHighlights<'a> {
 267    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 268    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 269    stack: Vec<(usize, HighlightId)>,
 270    highlight_map: HighlightMap,
 271    _query_cursor: QueryCursorHandle,
 272}
 273
 274pub struct BufferChunks<'a> {
 275    range: Range<usize>,
 276    chunks: rope::Chunks<'a>,
 277    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 278    error_depth: usize,
 279    warning_depth: usize,
 280    information_depth: usize,
 281    hint_depth: usize,
 282    unnecessary_depth: usize,
 283    highlights: Option<BufferChunkHighlights<'a>>,
 284}
 285
 286#[derive(Clone, Copy, Debug, Default)]
 287pub struct Chunk<'a> {
 288    pub text: &'a str,
 289    pub syntax_highlight_id: Option<HighlightId>,
 290    pub highlight_style: Option<HighlightStyle>,
 291    pub diagnostic_severity: Option<DiagnosticSeverity>,
 292    pub is_unnecessary: bool,
 293}
 294
 295pub struct Diff {
 296    base_version: clock::Global,
 297    new_text: Arc<str>,
 298    changes: Vec<(ChangeTag, usize)>,
 299    line_ending: LineEnding,
 300    start_offset: usize,
 301}
 302
 303#[derive(Clone, Copy)]
 304pub(crate) struct DiagnosticEndpoint {
 305    offset: usize,
 306    is_start: bool,
 307    severity: DiagnosticSeverity,
 308    is_unnecessary: bool,
 309}
 310
 311#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
 312pub enum CharKind {
 313    Punctuation,
 314    Whitespace,
 315    Word,
 316}
 317
 318impl CharKind {
 319    pub fn coerce_punctuation(self, treat_punctuation_as_word: bool) -> Self {
 320        if treat_punctuation_as_word && self == CharKind::Punctuation {
 321            CharKind::Word
 322        } else {
 323            self
 324        }
 325    }
 326}
 327
 328impl Buffer {
 329    pub fn new<T: Into<String>>(
 330        replica_id: ReplicaId,
 331        base_text: T,
 332        cx: &mut ModelContext<Self>,
 333    ) -> Self {
 334        Self::build(
 335            TextBuffer::new(replica_id, cx.model_id() as u64, base_text.into()),
 336            None,
 337        )
 338    }
 339
 340    pub fn from_file<T: Into<String>>(
 341        replica_id: ReplicaId,
 342        base_text: T,
 343        file: Arc<dyn File>,
 344        cx: &mut ModelContext<Self>,
 345    ) -> Self {
 346        Self::build(
 347            TextBuffer::new(replica_id, cx.model_id() as u64, base_text.into()),
 348            Some(file),
 349        )
 350    }
 351
 352    pub fn from_proto(
 353        replica_id: ReplicaId,
 354        message: proto::BufferState,
 355        file: Option<Arc<dyn File>>,
 356        cx: &mut ModelContext<Self>,
 357    ) -> Result<Self> {
 358        let buffer = TextBuffer::new(replica_id, message.id, message.base_text);
 359        let mut this = Self::build(buffer, file);
 360        this.text.set_line_ending(proto::deserialize_line_ending(
 361            proto::LineEnding::from_i32(message.line_ending)
 362                .ok_or_else(|| anyhow!("missing line_ending"))?,
 363        ));
 364        let ops = message
 365            .operations
 366            .into_iter()
 367            .map(proto::deserialize_operation)
 368            .collect::<Result<Vec<_>>>()?;
 369        this.apply_ops(ops, cx)?;
 370
 371        for selection_set in message.selections {
 372            let lamport_timestamp = clock::Lamport {
 373                replica_id: selection_set.replica_id as ReplicaId,
 374                value: selection_set.lamport_timestamp,
 375            };
 376            this.remote_selections.insert(
 377                selection_set.replica_id as ReplicaId,
 378                SelectionSet {
 379                    line_mode: selection_set.line_mode,
 380                    selections: proto::deserialize_selections(selection_set.selections),
 381                    lamport_timestamp,
 382                },
 383            );
 384            this.text.lamport_clock.observe(lamport_timestamp);
 385        }
 386        let snapshot = this.snapshot();
 387        let entries = proto::deserialize_diagnostics(message.diagnostics);
 388        this.apply_diagnostic_update(
 389            DiagnosticSet::from_sorted_entries(entries.iter().cloned(), &snapshot),
 390            clock::Lamport {
 391                replica_id: 0,
 392                value: message.diagnostics_timestamp,
 393            },
 394            cx,
 395        );
 396
 397        this.completion_triggers = message.completion_triggers;
 398
 399        Ok(this)
 400    }
 401
 402    pub fn to_proto(&self) -> proto::BufferState {
 403        let mut operations = self
 404            .text
 405            .history()
 406            .map(|op| proto::serialize_operation(&Operation::Buffer(op.clone())))
 407            .chain(self.deferred_ops.iter().map(proto::serialize_operation))
 408            .collect::<Vec<_>>();
 409        operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
 410        proto::BufferState {
 411            id: self.remote_id(),
 412            file: self.file.as_ref().map(|f| f.to_proto()),
 413            base_text: self.base_text().to_string(),
 414            operations,
 415            selections: self
 416                .remote_selections
 417                .iter()
 418                .map(|(replica_id, set)| proto::SelectionSet {
 419                    replica_id: *replica_id as u32,
 420                    selections: proto::serialize_selections(&set.selections),
 421                    lamport_timestamp: set.lamport_timestamp.value,
 422                    line_mode: set.line_mode,
 423                })
 424                .collect(),
 425            diagnostics: proto::serialize_diagnostics(self.diagnostics.iter()),
 426            diagnostics_timestamp: self.diagnostics_timestamp.value,
 427            completion_triggers: self.completion_triggers.clone(),
 428            line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
 429        }
 430    }
 431
 432    pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
 433        self.set_language(Some(language), cx);
 434        self
 435    }
 436
 437    fn build(buffer: TextBuffer, file: Option<Arc<dyn File>>) -> Self {
 438        let saved_mtime;
 439        if let Some(file) = file.as_ref() {
 440            saved_mtime = file.mtime();
 441        } else {
 442            saved_mtime = UNIX_EPOCH;
 443        }
 444
 445        Self {
 446            saved_mtime,
 447            saved_version: buffer.version(),
 448            saved_version_fingerprint: buffer.as_rope().fingerprint(),
 449            transaction_depth: 0,
 450            was_dirty_before_starting_transaction: None,
 451            text: buffer,
 452            file,
 453            syntax_tree: Mutex::new(None),
 454            parsing_in_background: false,
 455            parse_count: 0,
 456            sync_parse_timeout: Duration::from_millis(1),
 457            autoindent_requests: Default::default(),
 458            pending_autoindent: Default::default(),
 459            language: None,
 460            remote_selections: Default::default(),
 461            selections_update_count: 0,
 462            diagnostics: Default::default(),
 463            diagnostics_update_count: 0,
 464            diagnostics_timestamp: Default::default(),
 465            file_update_count: 0,
 466            completion_triggers: Default::default(),
 467            deferred_ops: OperationQueue::new(),
 468        }
 469    }
 470
 471    pub fn snapshot(&self) -> BufferSnapshot {
 472        BufferSnapshot {
 473            text: self.text.snapshot(),
 474            tree: self.syntax_tree(),
 475            file: self.file.clone(),
 476            remote_selections: self.remote_selections.clone(),
 477            diagnostics: self.diagnostics.clone(),
 478            diagnostics_update_count: self.diagnostics_update_count,
 479            file_update_count: self.file_update_count,
 480            language: self.language.clone(),
 481            parse_count: self.parse_count,
 482            selections_update_count: self.selections_update_count,
 483        }
 484    }
 485
 486    pub fn as_text_snapshot(&self) -> &text::BufferSnapshot {
 487        &self.text
 488    }
 489
 490    pub fn text_snapshot(&self) -> text::BufferSnapshot {
 491        self.text.snapshot()
 492    }
 493
 494    pub fn file(&self) -> Option<&dyn File> {
 495        self.file.as_deref()
 496    }
 497
 498    pub fn save(
 499        &mut self,
 500        cx: &mut ModelContext<Self>,
 501    ) -> Task<Result<(clock::Global, String, SystemTime)>> {
 502        let file = if let Some(file) = self.file.as_ref() {
 503            file
 504        } else {
 505            return Task::ready(Err(anyhow!("buffer has no file")));
 506        };
 507        let text = self.as_rope().clone();
 508        let version = self.version();
 509        let save = file.save(
 510            self.remote_id(),
 511            text,
 512            version,
 513            self.line_ending(),
 514            cx.as_mut(),
 515        );
 516        cx.spawn(|this, mut cx| async move {
 517            let (version, fingerprint, mtime) = save.await?;
 518            this.update(&mut cx, |this, cx| {
 519                this.did_save(version.clone(), fingerprint.clone(), mtime, None, cx);
 520            });
 521            Ok((version, fingerprint, mtime))
 522        })
 523    }
 524
 525    pub fn saved_version(&self) -> &clock::Global {
 526        &self.saved_version
 527    }
 528
 529    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
 530        *self.syntax_tree.lock() = None;
 531        self.language = language;
 532        self.reparse(cx);
 533    }
 534
 535    pub fn did_save(
 536        &mut self,
 537        version: clock::Global,
 538        fingerprint: String,
 539        mtime: SystemTime,
 540        new_file: Option<Arc<dyn File>>,
 541        cx: &mut ModelContext<Self>,
 542    ) {
 543        self.saved_version = version;
 544        self.saved_version_fingerprint = fingerprint;
 545        self.saved_mtime = mtime;
 546        if let Some(new_file) = new_file {
 547            self.file = Some(new_file);
 548            self.file_update_count += 1;
 549        }
 550        cx.emit(Event::Saved);
 551        cx.notify();
 552    }
 553
 554    pub fn reload(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Option<Transaction>>> {
 555        cx.spawn(|this, mut cx| async move {
 556            if let Some((new_mtime, new_text)) = this.read_with(&cx, |this, cx| {
 557                let file = this.file.as_ref()?.as_local()?;
 558                Some((file.mtime(), file.load(cx)))
 559            }) {
 560                let new_text = new_text.await?;
 561                let diff = this
 562                    .read_with(&cx, |this, cx| this.diff(new_text, cx))
 563                    .await;
 564                this.update(&mut cx, |this, cx| {
 565                    if let Some(transaction) = this.apply_diff(diff, cx).cloned() {
 566                        this.did_reload(
 567                            this.version(),
 568                            this.as_rope().fingerprint(),
 569                            this.line_ending(),
 570                            new_mtime,
 571                            cx,
 572                        );
 573                        Ok(Some(transaction))
 574                    } else {
 575                        Ok(None)
 576                    }
 577                })
 578            } else {
 579                Ok(None)
 580            }
 581        })
 582    }
 583
 584    pub fn did_reload(
 585        &mut self,
 586        version: clock::Global,
 587        fingerprint: String,
 588        line_ending: LineEnding,
 589        mtime: SystemTime,
 590        cx: &mut ModelContext<Self>,
 591    ) {
 592        self.saved_version = version;
 593        self.saved_version_fingerprint = fingerprint;
 594        self.text.set_line_ending(line_ending);
 595        self.saved_mtime = mtime;
 596        if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
 597            file.buffer_reloaded(
 598                self.remote_id(),
 599                &self.saved_version,
 600                self.saved_version_fingerprint.clone(),
 601                self.line_ending(),
 602                self.saved_mtime,
 603                cx,
 604            );
 605        }
 606        cx.emit(Event::Reloaded);
 607        cx.notify();
 608    }
 609
 610    pub fn file_updated(
 611        &mut self,
 612        new_file: Arc<dyn File>,
 613        cx: &mut ModelContext<Self>,
 614    ) -> Task<()> {
 615        let old_file = if let Some(file) = self.file.as_ref() {
 616            file
 617        } else {
 618            return Task::ready(());
 619        };
 620        let mut file_changed = false;
 621        let mut task = Task::ready(());
 622
 623        if new_file.path() != old_file.path() {
 624            file_changed = true;
 625        }
 626
 627        if new_file.is_deleted() {
 628            if !old_file.is_deleted() {
 629                file_changed = true;
 630                if !self.is_dirty() {
 631                    cx.emit(Event::DirtyChanged);
 632                }
 633            }
 634        } else {
 635            let new_mtime = new_file.mtime();
 636            if new_mtime != old_file.mtime() {
 637                file_changed = true;
 638
 639                if !self.is_dirty() {
 640                    let reload = self.reload(cx).log_err().map(drop);
 641                    task = cx.foreground().spawn(reload);
 642                }
 643            }
 644        }
 645
 646        if file_changed {
 647            self.file_update_count += 1;
 648            cx.emit(Event::FileHandleChanged);
 649            cx.notify();
 650        }
 651        self.file = Some(new_file);
 652        task
 653    }
 654
 655    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 656        cx.emit(Event::Closed);
 657    }
 658
 659    pub fn language(&self) -> Option<&Arc<Language>> {
 660        self.language.as_ref()
 661    }
 662
 663    pub fn parse_count(&self) -> usize {
 664        self.parse_count
 665    }
 666
 667    pub fn selections_update_count(&self) -> usize {
 668        self.selections_update_count
 669    }
 670
 671    pub fn diagnostics_update_count(&self) -> usize {
 672        self.diagnostics_update_count
 673    }
 674
 675    pub fn file_update_count(&self) -> usize {
 676        self.file_update_count
 677    }
 678
 679    pub(crate) fn syntax_tree(&self) -> Option<Tree> {
 680        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 681            self.interpolate_tree(syntax_tree);
 682            Some(syntax_tree.tree.clone())
 683        } else {
 684            None
 685        }
 686    }
 687
 688    #[cfg(any(test, feature = "test-support"))]
 689    pub fn is_parsing(&self) -> bool {
 690        self.parsing_in_background
 691    }
 692
 693    #[cfg(test)]
 694    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 695        self.sync_parse_timeout = timeout;
 696    }
 697
 698    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 699        if self.parsing_in_background {
 700            return false;
 701        }
 702
 703        if let Some(grammar) = self.grammar().cloned() {
 704            let old_tree = self.syntax_tree();
 705            let text = self.as_rope().clone();
 706            let parsed_version = self.version();
 707            let parse_task = cx.background().spawn({
 708                let grammar = grammar.clone();
 709                async move { grammar.parse_text(&text, old_tree) }
 710            });
 711
 712            match cx
 713                .background()
 714                .block_with_timeout(self.sync_parse_timeout, parse_task)
 715            {
 716                Ok(new_tree) => {
 717                    self.did_finish_parsing(new_tree, parsed_version, cx);
 718                    return true;
 719                }
 720                Err(parse_task) => {
 721                    self.parsing_in_background = true;
 722                    cx.spawn(move |this, mut cx| async move {
 723                        let new_tree = parse_task.await;
 724                        this.update(&mut cx, move |this, cx| {
 725                            let grammar_changed = this
 726                                .grammar()
 727                                .map_or(true, |curr_grammar| !Arc::ptr_eq(&grammar, curr_grammar));
 728                            let parse_again =
 729                                this.version.changed_since(&parsed_version) || grammar_changed;
 730                            this.parsing_in_background = false;
 731                            this.did_finish_parsing(new_tree, parsed_version, cx);
 732
 733                            if parse_again && this.reparse(cx) {
 734                                return;
 735                            }
 736                        });
 737                    })
 738                    .detach();
 739                }
 740            }
 741        }
 742        false
 743    }
 744
 745    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 746        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 747            let (bytes, lines) = edit.flatten();
 748            tree.tree.edit(&InputEdit {
 749                start_byte: bytes.new.start,
 750                old_end_byte: bytes.new.start + bytes.old.len(),
 751                new_end_byte: bytes.new.end,
 752                start_position: lines.new.start.to_ts_point(),
 753                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 754                    .to_ts_point(),
 755                new_end_position: lines.new.end.to_ts_point(),
 756            });
 757        }
 758        tree.version = self.version();
 759    }
 760
 761    fn did_finish_parsing(
 762        &mut self,
 763        tree: Tree,
 764        version: clock::Global,
 765        cx: &mut ModelContext<Self>,
 766    ) {
 767        self.parse_count += 1;
 768        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 769        self.request_autoindent(cx);
 770        cx.emit(Event::Reparsed);
 771        cx.notify();
 772    }
 773
 774    pub fn update_diagnostics(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
 775        let lamport_timestamp = self.text.lamport_clock.tick();
 776        let op = Operation::UpdateDiagnostics {
 777            diagnostics: diagnostics.iter().cloned().collect(),
 778            lamport_timestamp,
 779        };
 780        self.apply_diagnostic_update(diagnostics, lamport_timestamp, cx);
 781        self.send_operation(op, cx);
 782    }
 783
 784    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 785        if let Some(indent_sizes) = self.compute_autoindents() {
 786            let indent_sizes = cx.background().spawn(indent_sizes);
 787            match cx
 788                .background()
 789                .block_with_timeout(Duration::from_micros(500), indent_sizes)
 790            {
 791                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
 792                Err(indent_sizes) => {
 793                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 794                        let indent_sizes = indent_sizes.await;
 795                        this.update(&mut cx, |this, cx| {
 796                            this.apply_autoindents(indent_sizes, cx);
 797                        });
 798                    }));
 799                }
 800            }
 801        }
 802    }
 803
 804    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
 805        let max_rows_between_yields = 100;
 806        let snapshot = self.snapshot();
 807        if snapshot.language.is_none()
 808            || snapshot.tree.is_none()
 809            || self.autoindent_requests.is_empty()
 810        {
 811            return None;
 812        }
 813
 814        let autoindent_requests = self.autoindent_requests.clone();
 815        Some(async move {
 816            let mut indent_sizes = BTreeMap::new();
 817            for request in autoindent_requests {
 818                // Resolve each edited range to its row in the current buffer and in the
 819                // buffer before this batch of edits.
 820                let mut row_ranges = Vec::new();
 821                let mut old_to_new_rows = BTreeMap::new();
 822                for entry in &request.entries {
 823                    let position = entry.range.start;
 824                    let new_row = position.to_point(&snapshot).row;
 825                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
 826                    if !entry.first_line_is_new {
 827                        let old_row = position.to_point(&request.before_edit).row;
 828                        old_to_new_rows.insert(old_row, new_row);
 829                    }
 830                    row_ranges.push((new_row..new_end_row, entry.start_column));
 831                }
 832
 833                // Build a map containing the suggested indentation for each of the edited lines
 834                // with respect to the state of the buffer before these edits. This map is keyed
 835                // by the rows for these lines in the current state of the buffer.
 836                let mut old_suggestions = BTreeMap::<u32, IndentSize>::default();
 837                let old_edited_ranges =
 838                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 839                for old_edited_range in old_edited_ranges {
 840                    let suggestions = request
 841                        .before_edit
 842                        .suggest_autoindents(old_edited_range.clone())
 843                        .into_iter()
 844                        .flatten();
 845                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 846                        if let Some(suggestion) = suggestion {
 847                            let suggested_indent = old_to_new_rows
 848                                .get(&suggestion.basis_row)
 849                                .and_then(|from_row| old_suggestions.get(from_row).copied())
 850                                .unwrap_or_else(|| {
 851                                    request
 852                                        .before_edit
 853                                        .indent_size_for_line(suggestion.basis_row)
 854                                })
 855                                .with_delta(suggestion.delta, request.indent_size);
 856                            old_suggestions
 857                                .insert(*old_to_new_rows.get(&old_row).unwrap(), suggested_indent);
 858                        }
 859                    }
 860                    yield_now().await;
 861                }
 862
 863                // In block mode, only compute indentation suggestions for the first line
 864                // of each insertion. Otherwise, compute suggestions for every inserted line.
 865                let new_edited_row_ranges = contiguous_ranges(
 866                    row_ranges.iter().flat_map(|(range, _)| {
 867                        if request.is_block_mode {
 868                            range.start..range.start + 1
 869                        } else {
 870                            range.clone()
 871                        }
 872                    }),
 873                    max_rows_between_yields,
 874                );
 875
 876                // Compute new suggestions for each line, but only include them in the result
 877                // if they differ from the old suggestion for that line.
 878                for new_edited_row_range in new_edited_row_ranges {
 879                    let suggestions = snapshot
 880                        .suggest_autoindents(new_edited_row_range.clone())
 881                        .into_iter()
 882                        .flatten();
 883                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 884                        if let Some(suggestion) = suggestion {
 885                            let suggested_indent = indent_sizes
 886                                .get(&suggestion.basis_row)
 887                                .copied()
 888                                .unwrap_or_else(|| {
 889                                    snapshot.indent_size_for_line(suggestion.basis_row)
 890                                })
 891                                .with_delta(suggestion.delta, request.indent_size);
 892                            if old_suggestions
 893                                .get(&new_row)
 894                                .map_or(true, |old_indentation| {
 895                                    suggested_indent != *old_indentation
 896                                })
 897                            {
 898                                indent_sizes.insert(new_row, suggested_indent);
 899                            }
 900                        }
 901                    }
 902                    yield_now().await;
 903                }
 904
 905                // For each block of inserted text, adjust the indentation of the remaining
 906                // lines of the block by the same amount as the first line was adjusted.
 907                if request.is_block_mode {
 908                    for (row_range, start_column) in
 909                        row_ranges.into_iter().filter_map(|(range, start_column)| {
 910                            if range.len() > 1 {
 911                                Some((range, start_column?))
 912                            } else {
 913                                None
 914                            }
 915                        })
 916                    {
 917                        let new_indent = indent_sizes
 918                            .get(&row_range.start)
 919                            .copied()
 920                            .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
 921                        let delta = new_indent.len as i64 - start_column as i64;
 922                        if delta != 0 {
 923                            for row in row_range.skip(1) {
 924                                indent_sizes.entry(row).or_insert_with(|| {
 925                                    let mut size = snapshot.indent_size_for_line(row);
 926                                    if size.kind == new_indent.kind {
 927                                        if delta > 0 {
 928                                            size.len = size.len + delta as u32;
 929                                        } else if delta < 0 {
 930                                            size.len = size.len.saturating_sub(-delta as u32);
 931                                        }
 932                                    }
 933                                    size
 934                                });
 935                            }
 936                        }
 937                    }
 938                }
 939            }
 940
 941            indent_sizes
 942        })
 943    }
 944
 945    fn apply_autoindents(
 946        &mut self,
 947        indent_sizes: BTreeMap<u32, IndentSize>,
 948        cx: &mut ModelContext<Self>,
 949    ) {
 950        self.autoindent_requests.clear();
 951        self.start_transaction();
 952        for (row, indent_size) in &indent_sizes {
 953            self.set_indent_size_for_line(*row, *indent_size, cx);
 954        }
 955        self.end_transaction(cx);
 956    }
 957
 958    fn set_indent_size_for_line(
 959        &mut self,
 960        row: u32,
 961        size: IndentSize,
 962        cx: &mut ModelContext<Self>,
 963    ) {
 964        let current_size = indent_size_for_line(&self, row);
 965        if size.kind != current_size.kind && current_size.len > 0 {
 966            return;
 967        }
 968
 969        if size.len > current_size.len {
 970            let offset = Point::new(row, 0).to_offset(&*self);
 971            self.edit(
 972                [(
 973                    offset..offset,
 974                    iter::repeat(size.char())
 975                        .take((size.len - current_size.len) as usize)
 976                        .collect::<String>(),
 977                )],
 978                None,
 979                cx,
 980            );
 981        } else if size.len < current_size.len {
 982            self.edit(
 983                [(
 984                    Point::new(row, 0)..Point::new(row, current_size.len - size.len),
 985                    "",
 986                )],
 987                None,
 988                cx,
 989            );
 990        }
 991    }
 992
 993    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
 994        let old_text = self.as_rope().clone();
 995        let base_version = self.version();
 996        cx.background().spawn(async move {
 997            let old_text = old_text.to_string();
 998            let line_ending = LineEnding::detect(&new_text);
 999            LineEnding::normalize(&mut new_text);
1000            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_str())
1001                .iter_all_changes()
1002                .map(|c| (c.tag(), c.value().len()))
1003                .collect::<Vec<_>>();
1004            Diff {
1005                base_version,
1006                new_text: new_text.into(),
1007                changes,
1008                line_ending,
1009                start_offset: 0,
1010            }
1011        })
1012    }
1013
1014    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<&Transaction> {
1015        if self.version == diff.base_version {
1016            self.finalize_last_transaction();
1017            self.start_transaction();
1018            self.text.set_line_ending(diff.line_ending);
1019            let mut offset = diff.start_offset;
1020            for (tag, len) in diff.changes {
1021                let range = offset..(offset + len);
1022                match tag {
1023                    ChangeTag::Equal => offset += len,
1024                    ChangeTag::Delete => {
1025                        self.edit([(range, "")], None, cx);
1026                    }
1027                    ChangeTag::Insert => {
1028                        self.edit(
1029                            [(
1030                                offset..offset,
1031                                &diff.new_text[range.start - diff.start_offset
1032                                    ..range.end - diff.start_offset],
1033                            )],
1034                            None,
1035                            cx,
1036                        );
1037                        offset += len;
1038                    }
1039                }
1040            }
1041            if self.end_transaction(cx).is_some() {
1042                self.finalize_last_transaction()
1043            } else {
1044                None
1045            }
1046        } else {
1047            None
1048        }
1049    }
1050
1051    pub fn is_dirty(&self) -> bool {
1052        self.saved_version_fingerprint != self.as_rope().fingerprint()
1053            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1054    }
1055
1056    pub fn has_conflict(&self) -> bool {
1057        self.saved_version_fingerprint != self.as_rope().fingerprint()
1058            && self
1059                .file
1060                .as_ref()
1061                .map_or(false, |file| file.mtime() > self.saved_mtime)
1062    }
1063
1064    pub fn subscribe(&mut self) -> Subscription {
1065        self.text.subscribe()
1066    }
1067
1068    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1069        self.start_transaction_at(Instant::now())
1070    }
1071
1072    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1073        self.transaction_depth += 1;
1074        if self.was_dirty_before_starting_transaction.is_none() {
1075            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1076        }
1077        self.text.start_transaction_at(now)
1078    }
1079
1080    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1081        self.end_transaction_at(Instant::now(), cx)
1082    }
1083
1084    pub fn end_transaction_at(
1085        &mut self,
1086        now: Instant,
1087        cx: &mut ModelContext<Self>,
1088    ) -> Option<TransactionId> {
1089        assert!(self.transaction_depth > 0);
1090        self.transaction_depth -= 1;
1091        let was_dirty = if self.transaction_depth == 0 {
1092            self.was_dirty_before_starting_transaction.take().unwrap()
1093        } else {
1094            false
1095        };
1096        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1097            self.did_edit(&start_version, was_dirty, cx);
1098            Some(transaction_id)
1099        } else {
1100            None
1101        }
1102    }
1103
1104    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1105        self.text.push_transaction(transaction, now);
1106    }
1107
1108    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1109        self.text.finalize_last_transaction()
1110    }
1111
1112    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1113        self.text.group_until_transaction(transaction_id);
1114    }
1115
1116    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1117        self.text.forget_transaction(transaction_id);
1118    }
1119
1120    pub fn wait_for_edits(
1121        &mut self,
1122        edit_ids: impl IntoIterator<Item = clock::Local>,
1123    ) -> impl Future<Output = ()> {
1124        self.text.wait_for_edits(edit_ids)
1125    }
1126
1127    pub fn wait_for_anchors<'a>(
1128        &mut self,
1129        anchors: impl IntoIterator<Item = &'a Anchor>,
1130    ) -> impl Future<Output = ()> {
1131        self.text.wait_for_anchors(anchors)
1132    }
1133
1134    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1135        self.text.wait_for_version(version)
1136    }
1137
1138    pub fn set_active_selections(
1139        &mut self,
1140        selections: Arc<[Selection<Anchor>]>,
1141        line_mode: bool,
1142        cx: &mut ModelContext<Self>,
1143    ) {
1144        let lamport_timestamp = self.text.lamport_clock.tick();
1145        self.remote_selections.insert(
1146            self.text.replica_id(),
1147            SelectionSet {
1148                selections: selections.clone(),
1149                lamport_timestamp,
1150                line_mode,
1151            },
1152        );
1153        self.send_operation(
1154            Operation::UpdateSelections {
1155                selections,
1156                line_mode,
1157                lamport_timestamp,
1158            },
1159            cx,
1160        );
1161    }
1162
1163    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1164        self.set_active_selections(Arc::from([]), false, cx);
1165    }
1166
1167    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Local>
1168    where
1169        T: Into<Arc<str>>,
1170    {
1171        self.edit([(0..self.len(), text)], None, cx)
1172    }
1173
1174    pub fn edit<I, S, T>(
1175        &mut self,
1176        edits_iter: I,
1177        autoindent_mode: Option<AutoindentMode>,
1178        cx: &mut ModelContext<Self>,
1179    ) -> Option<clock::Local>
1180    where
1181        I: IntoIterator<Item = (Range<S>, T)>,
1182        S: ToOffset,
1183        T: Into<Arc<str>>,
1184    {
1185        // Skip invalid edits and coalesce contiguous ones.
1186        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1187        for (range, new_text) in edits_iter {
1188            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1189            if range.start > range.end {
1190                mem::swap(&mut range.start, &mut range.end);
1191            }
1192            let new_text = new_text.into();
1193            if !new_text.is_empty() || !range.is_empty() {
1194                if let Some((prev_range, prev_text)) = edits.last_mut() {
1195                    if prev_range.end >= range.start {
1196                        prev_range.end = cmp::max(prev_range.end, range.end);
1197                        *prev_text = format!("{prev_text}{new_text}").into();
1198                    } else {
1199                        edits.push((range, new_text));
1200                    }
1201                } else {
1202                    edits.push((range, new_text));
1203                }
1204            }
1205        }
1206        if edits.is_empty() {
1207            return None;
1208        }
1209
1210        self.start_transaction();
1211        self.pending_autoindent.take();
1212        let autoindent_request = autoindent_mode
1213            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1214
1215        let edit_operation = self.text.edit(edits.iter().cloned());
1216        let edit_id = edit_operation.local_timestamp();
1217
1218        if let Some((before_edit, mode)) = autoindent_request {
1219            let language_name = self.language().map(|language| language.name());
1220            let settings = cx.global::<Settings>();
1221            let indent_size = if settings.hard_tabs(language_name.as_deref()) {
1222                IndentSize::tab()
1223            } else {
1224                IndentSize::spaces(settings.tab_size(language_name.as_deref()).get())
1225            };
1226            let (start_columns, is_block_mode) = match mode {
1227                AutoindentMode::Block { start_columns } => (start_columns, true),
1228                AutoindentMode::Independent => (Default::default(), false),
1229            };
1230
1231            let mut delta = 0isize;
1232            let entries = edits
1233                .into_iter()
1234                .enumerate()
1235                .zip(&edit_operation.as_edit().unwrap().new_text)
1236                .map(|((ix, (range, _)), new_text)| {
1237                    let new_text_len = new_text.len();
1238                    let old_start = range.start.to_point(&before_edit);
1239                    let new_start = (delta + range.start as isize) as usize;
1240                    delta += new_text_len as isize - (range.end as isize - range.start as isize);
1241
1242                    let mut range_of_insertion_to_indent = 0..new_text_len;
1243                    let mut first_line_is_new = false;
1244                    let mut start_column = None;
1245
1246                    // When inserting an entire line at the beginning of an existing line,
1247                    // treat the insertion as new.
1248                    if new_text.contains('\n')
1249                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1250                    {
1251                        first_line_is_new = true;
1252                    }
1253
1254                    // When inserting text starting with a newline, avoid auto-indenting the
1255                    // previous line.
1256                    if new_text[range_of_insertion_to_indent.clone()].starts_with('\n') {
1257                        range_of_insertion_to_indent.start += 1;
1258                        first_line_is_new = true;
1259                    }
1260
1261                    // Avoid auto-indenting before the insertion.
1262                    if is_block_mode {
1263                        start_column = start_columns
1264                            .get(ix)
1265                            .map(|start| start + indent_size_for_text(new_text.chars()).len);
1266                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1267                            range_of_insertion_to_indent.end -= 1;
1268                        }
1269                    }
1270
1271                    AutoindentRequestEntry {
1272                        first_line_is_new,
1273                        start_column,
1274                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1275                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1276                    }
1277                })
1278                .collect();
1279
1280            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1281                before_edit,
1282                entries,
1283                indent_size,
1284                is_block_mode,
1285            }));
1286        }
1287
1288        self.end_transaction(cx);
1289        self.send_operation(Operation::Buffer(edit_operation), cx);
1290        Some(edit_id)
1291    }
1292
1293    fn did_edit(
1294        &mut self,
1295        old_version: &clock::Global,
1296        was_dirty: bool,
1297        cx: &mut ModelContext<Self>,
1298    ) {
1299        if self.edits_since::<usize>(old_version).next().is_none() {
1300            return;
1301        }
1302
1303        self.reparse(cx);
1304
1305        cx.emit(Event::Edited);
1306        if was_dirty != self.is_dirty() {
1307            cx.emit(Event::DirtyChanged);
1308        }
1309        cx.notify();
1310    }
1311
1312    fn grammar(&self) -> Option<&Arc<Grammar>> {
1313        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1314    }
1315
1316    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1317        &mut self,
1318        ops: I,
1319        cx: &mut ModelContext<Self>,
1320    ) -> Result<()> {
1321        self.pending_autoindent.take();
1322        let was_dirty = self.is_dirty();
1323        let old_version = self.version.clone();
1324        let mut deferred_ops = Vec::new();
1325        let buffer_ops = ops
1326            .into_iter()
1327            .filter_map(|op| match op {
1328                Operation::Buffer(op) => Some(op),
1329                _ => {
1330                    if self.can_apply_op(&op) {
1331                        self.apply_op(op, cx);
1332                    } else {
1333                        deferred_ops.push(op);
1334                    }
1335                    None
1336                }
1337            })
1338            .collect::<Vec<_>>();
1339        self.text.apply_ops(buffer_ops)?;
1340        self.deferred_ops.insert(deferred_ops);
1341        self.flush_deferred_ops(cx);
1342        self.did_edit(&old_version, was_dirty, cx);
1343        // Notify independently of whether the buffer was edited as the operations could include a
1344        // selection update.
1345        cx.notify();
1346        Ok(())
1347    }
1348
1349    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1350        let mut deferred_ops = Vec::new();
1351        for op in self.deferred_ops.drain().iter().cloned() {
1352            if self.can_apply_op(&op) {
1353                self.apply_op(op, cx);
1354            } else {
1355                deferred_ops.push(op);
1356            }
1357        }
1358        self.deferred_ops.insert(deferred_ops);
1359    }
1360
1361    fn can_apply_op(&self, operation: &Operation) -> bool {
1362        match operation {
1363            Operation::Buffer(_) => {
1364                unreachable!("buffer operations should never be applied at this layer")
1365            }
1366            Operation::UpdateDiagnostics {
1367                diagnostics: diagnostic_set,
1368                ..
1369            } => diagnostic_set.iter().all(|diagnostic| {
1370                self.text.can_resolve(&diagnostic.range.start)
1371                    && self.text.can_resolve(&diagnostic.range.end)
1372            }),
1373            Operation::UpdateSelections { selections, .. } => selections
1374                .iter()
1375                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1376            Operation::UpdateCompletionTriggers { .. } => true,
1377        }
1378    }
1379
1380    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1381        match operation {
1382            Operation::Buffer(_) => {
1383                unreachable!("buffer operations should never be applied at this layer")
1384            }
1385            Operation::UpdateDiagnostics {
1386                diagnostics: diagnostic_set,
1387                lamport_timestamp,
1388            } => {
1389                let snapshot = self.snapshot();
1390                self.apply_diagnostic_update(
1391                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1392                    lamport_timestamp,
1393                    cx,
1394                );
1395            }
1396            Operation::UpdateSelections {
1397                selections,
1398                lamport_timestamp,
1399                line_mode,
1400            } => {
1401                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1402                    if set.lamport_timestamp > lamport_timestamp {
1403                        return;
1404                    }
1405                }
1406
1407                self.remote_selections.insert(
1408                    lamport_timestamp.replica_id,
1409                    SelectionSet {
1410                        selections,
1411                        lamport_timestamp,
1412                        line_mode,
1413                    },
1414                );
1415                self.text.lamport_clock.observe(lamport_timestamp);
1416                self.selections_update_count += 1;
1417            }
1418            Operation::UpdateCompletionTriggers {
1419                triggers,
1420                lamport_timestamp,
1421            } => {
1422                self.completion_triggers = triggers;
1423                self.text.lamport_clock.observe(lamport_timestamp);
1424            }
1425        }
1426    }
1427
1428    fn apply_diagnostic_update(
1429        &mut self,
1430        diagnostics: DiagnosticSet,
1431        lamport_timestamp: clock::Lamport,
1432        cx: &mut ModelContext<Self>,
1433    ) {
1434        if lamport_timestamp > self.diagnostics_timestamp {
1435            self.diagnostics = diagnostics;
1436            self.diagnostics_timestamp = lamport_timestamp;
1437            self.diagnostics_update_count += 1;
1438            self.text.lamport_clock.observe(lamport_timestamp);
1439            cx.notify();
1440            cx.emit(Event::DiagnosticsUpdated);
1441        }
1442    }
1443
1444    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1445        cx.emit(Event::Operation(operation));
1446    }
1447
1448    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1449        self.remote_selections.remove(&replica_id);
1450        cx.notify();
1451    }
1452
1453    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1454        let was_dirty = self.is_dirty();
1455        let old_version = self.version.clone();
1456
1457        if let Some((transaction_id, operation)) = self.text.undo() {
1458            self.send_operation(Operation::Buffer(operation), cx);
1459            self.did_edit(&old_version, was_dirty, cx);
1460            Some(transaction_id)
1461        } else {
1462            None
1463        }
1464    }
1465
1466    pub fn undo_to_transaction(
1467        &mut self,
1468        transaction_id: TransactionId,
1469        cx: &mut ModelContext<Self>,
1470    ) -> bool {
1471        let was_dirty = self.is_dirty();
1472        let old_version = self.version.clone();
1473
1474        let operations = self.text.undo_to_transaction(transaction_id);
1475        let undone = !operations.is_empty();
1476        for operation in operations {
1477            self.send_operation(Operation::Buffer(operation), cx);
1478        }
1479        if undone {
1480            self.did_edit(&old_version, was_dirty, cx)
1481        }
1482        undone
1483    }
1484
1485    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1486        let was_dirty = self.is_dirty();
1487        let old_version = self.version.clone();
1488
1489        if let Some((transaction_id, operation)) = self.text.redo() {
1490            self.send_operation(Operation::Buffer(operation), cx);
1491            self.did_edit(&old_version, was_dirty, cx);
1492            Some(transaction_id)
1493        } else {
1494            None
1495        }
1496    }
1497
1498    pub fn redo_to_transaction(
1499        &mut self,
1500        transaction_id: TransactionId,
1501        cx: &mut ModelContext<Self>,
1502    ) -> bool {
1503        let was_dirty = self.is_dirty();
1504        let old_version = self.version.clone();
1505
1506        let operations = self.text.redo_to_transaction(transaction_id);
1507        let redone = !operations.is_empty();
1508        for operation in operations {
1509            self.send_operation(Operation::Buffer(operation), cx);
1510        }
1511        if redone {
1512            self.did_edit(&old_version, was_dirty, cx)
1513        }
1514        redone
1515    }
1516
1517    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
1518        self.completion_triggers = triggers.clone();
1519        let lamport_timestamp = self.text.lamport_clock.tick();
1520        self.send_operation(
1521            Operation::UpdateCompletionTriggers {
1522                triggers,
1523                lamport_timestamp,
1524            },
1525            cx,
1526        );
1527        cx.notify();
1528    }
1529
1530    pub fn completion_triggers(&self) -> &[String] {
1531        &self.completion_triggers
1532    }
1533}
1534
1535#[cfg(any(test, feature = "test-support"))]
1536impl Buffer {
1537    pub fn set_group_interval(&mut self, group_interval: Duration) {
1538        self.text.set_group_interval(group_interval);
1539    }
1540
1541    pub fn randomly_edit<T>(
1542        &mut self,
1543        rng: &mut T,
1544        old_range_count: usize,
1545        cx: &mut ModelContext<Self>,
1546    ) where
1547        T: rand::Rng,
1548    {
1549        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
1550        let mut last_end = None;
1551        for _ in 0..old_range_count {
1552            if last_end.map_or(false, |last_end| last_end >= self.len()) {
1553                break;
1554            }
1555
1556            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1557            let mut range = self.random_byte_range(new_start, rng);
1558            if rng.gen_bool(0.2) {
1559                mem::swap(&mut range.start, &mut range.end);
1560            }
1561            last_end = Some(range.end);
1562
1563            let new_text_len = rng.gen_range(0..10);
1564            let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1565                .take(new_text_len)
1566                .collect();
1567
1568            edits.push((range, new_text));
1569        }
1570        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
1571        self.edit(edits, None, cx);
1572    }
1573
1574    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1575        let was_dirty = self.is_dirty();
1576        let old_version = self.version.clone();
1577
1578        let ops = self.text.randomly_undo_redo(rng);
1579        if !ops.is_empty() {
1580            for op in ops {
1581                self.send_operation(Operation::Buffer(op), cx);
1582                self.did_edit(&old_version, was_dirty, cx);
1583            }
1584        }
1585    }
1586}
1587
1588impl Entity for Buffer {
1589    type Event = Event;
1590}
1591
1592impl Deref for Buffer {
1593    type Target = TextBuffer;
1594
1595    fn deref(&self) -> &Self::Target {
1596        &self.text
1597    }
1598}
1599
1600impl BufferSnapshot {
1601    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
1602        indent_size_for_line(&self, row)
1603    }
1604
1605    fn suggest_autoindents<'a>(
1606        &'a self,
1607        row_range: Range<u32>,
1608    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + 'a> {
1609        let language = self.language.as_ref()?;
1610        let grammar = language.grammar.as_ref()?;
1611        let config = &language.config;
1612        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1613
1614        // Find the suggested indentation ranges based on the syntax tree.
1615        let indents_query = grammar.indents_query.as_ref()?;
1616        let mut query_cursor = QueryCursorHandle::new();
1617        let indent_capture_ix = indents_query.capture_index_for_name("indent");
1618        let end_capture_ix = indents_query.capture_index_for_name("end");
1619        query_cursor.set_point_range(
1620            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1621                ..Point::new(row_range.end, 0).to_ts_point(),
1622        );
1623
1624        let mut indent_ranges = Vec::<Range<Point>>::new();
1625        for mat in query_cursor.matches(
1626            indents_query,
1627            self.tree.as_ref()?.root_node(),
1628            TextProvider(self.as_rope()),
1629        ) {
1630            let mut start: Option<Point> = None;
1631            let mut end: Option<Point> = None;
1632            for capture in mat.captures {
1633                if Some(capture.index) == indent_capture_ix {
1634                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1635                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1636                } else if Some(capture.index) == end_capture_ix {
1637                    end = Some(Point::from_ts_point(capture.node.start_position().into()));
1638                }
1639            }
1640
1641            if let Some((start, end)) = start.zip(end) {
1642                if start.row == end.row {
1643                    continue;
1644                }
1645
1646                let range = start..end;
1647                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
1648                    Err(ix) => indent_ranges.insert(ix, range),
1649                    Ok(ix) => {
1650                        let prev_range = &mut indent_ranges[ix];
1651                        prev_range.end = prev_range.end.max(range.end);
1652                    }
1653                }
1654            }
1655        }
1656
1657        // Find the suggested indentation increases and decreased based on regexes.
1658        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
1659        self.for_each_line(
1660            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
1661                ..Point::new(row_range.end, 0),
1662            |row, line| {
1663                if config
1664                    .decrease_indent_pattern
1665                    .as_ref()
1666                    .map_or(false, |regex| regex.is_match(line))
1667                {
1668                    indent_change_rows.push((row, Ordering::Less));
1669                }
1670                if config
1671                    .increase_indent_pattern
1672                    .as_ref()
1673                    .map_or(false, |regex| regex.is_match(line))
1674                {
1675                    indent_change_rows.push((row + 1, Ordering::Greater));
1676                }
1677            },
1678        );
1679
1680        let mut indent_changes = indent_change_rows.into_iter().peekable();
1681        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
1682            prev_non_blank_row.unwrap_or(0)
1683        } else {
1684            row_range.start.saturating_sub(1)
1685        };
1686        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
1687        Some(row_range.map(move |row| {
1688            let row_start = Point::new(row, self.indent_size_for_line(row).len);
1689
1690            let mut indent_from_prev_row = false;
1691            let mut outdent_from_prev_row = false;
1692            let mut outdent_to_row = u32::MAX;
1693
1694            while let Some((indent_row, delta)) = indent_changes.peek() {
1695                if *indent_row == row {
1696                    match delta {
1697                        Ordering::Less => outdent_from_prev_row = true,
1698                        Ordering::Greater => indent_from_prev_row = true,
1699                        _ => {}
1700                    }
1701                } else if *indent_row > row {
1702                    break;
1703                }
1704                indent_changes.next();
1705            }
1706
1707            for range in &indent_ranges {
1708                if range.start.row >= row {
1709                    break;
1710                }
1711                if range.start.row == prev_row && range.end > row_start {
1712                    indent_from_prev_row = true;
1713                }
1714                if range.end > prev_row_start && range.end <= row_start {
1715                    outdent_to_row = outdent_to_row.min(range.start.row);
1716                }
1717            }
1718
1719            let suggestion = if outdent_to_row == prev_row
1720                || (outdent_from_prev_row && indent_from_prev_row)
1721            {
1722                Some(IndentSuggestion {
1723                    basis_row: prev_row,
1724                    delta: Ordering::Equal,
1725                })
1726            } else if indent_from_prev_row {
1727                Some(IndentSuggestion {
1728                    basis_row: prev_row,
1729                    delta: Ordering::Greater,
1730                })
1731            } else if outdent_to_row < prev_row {
1732                Some(IndentSuggestion {
1733                    basis_row: outdent_to_row,
1734                    delta: Ordering::Equal,
1735                })
1736            } else if outdent_from_prev_row {
1737                Some(IndentSuggestion {
1738                    basis_row: prev_row,
1739                    delta: Ordering::Less,
1740                })
1741            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
1742            {
1743                Some(IndentSuggestion {
1744                    basis_row: prev_row,
1745                    delta: Ordering::Equal,
1746                })
1747            } else {
1748                None
1749            };
1750
1751            prev_row = row;
1752            prev_row_start = row_start;
1753            suggestion
1754        }))
1755    }
1756
1757    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1758        while row > 0 {
1759            row -= 1;
1760            if !self.is_line_blank(row) {
1761                return Some(row);
1762            }
1763        }
1764        None
1765    }
1766
1767    pub fn chunks<'a, T: ToOffset>(
1768        &'a self,
1769        range: Range<T>,
1770        language_aware: bool,
1771    ) -> BufferChunks<'a> {
1772        let range = range.start.to_offset(self)..range.end.to_offset(self);
1773
1774        let mut tree = None;
1775        let mut diagnostic_endpoints = Vec::new();
1776        if language_aware {
1777            tree = self.tree.as_ref();
1778            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
1779                diagnostic_endpoints.push(DiagnosticEndpoint {
1780                    offset: entry.range.start,
1781                    is_start: true,
1782                    severity: entry.diagnostic.severity,
1783                    is_unnecessary: entry.diagnostic.is_unnecessary,
1784                });
1785                diagnostic_endpoints.push(DiagnosticEndpoint {
1786                    offset: entry.range.end,
1787                    is_start: false,
1788                    severity: entry.diagnostic.severity,
1789                    is_unnecessary: entry.diagnostic.is_unnecessary,
1790                });
1791            }
1792            diagnostic_endpoints
1793                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1794        }
1795
1796        BufferChunks::new(
1797            self.text.as_rope(),
1798            range,
1799            tree,
1800            self.grammar(),
1801            diagnostic_endpoints,
1802        )
1803    }
1804
1805    pub fn for_each_line<'a>(&'a self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
1806        let mut line = String::new();
1807        let mut row = range.start.row;
1808        for chunk in self
1809            .as_rope()
1810            .chunks_in_range(range.to_offset(self))
1811            .chain(["\n"])
1812        {
1813            for (newline_ix, text) in chunk.split('\n').enumerate() {
1814                if newline_ix > 0 {
1815                    callback(row, &line);
1816                    row += 1;
1817                    line.clear();
1818                }
1819                line.push_str(text);
1820            }
1821        }
1822    }
1823
1824    pub fn language(&self) -> Option<&Arc<Language>> {
1825        self.language.as_ref()
1826    }
1827
1828    fn grammar(&self) -> Option<&Arc<Grammar>> {
1829        self.language
1830            .as_ref()
1831            .and_then(|language| language.grammar.as_ref())
1832    }
1833
1834    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1835        let mut start = start.to_offset(self);
1836        let mut end = start;
1837        let mut next_chars = self.chars_at(start).peekable();
1838        let mut prev_chars = self.reversed_chars_at(start).peekable();
1839        let word_kind = cmp::max(
1840            prev_chars.peek().copied().map(char_kind),
1841            next_chars.peek().copied().map(char_kind),
1842        );
1843
1844        for ch in prev_chars {
1845            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1846                start -= ch.len_utf8();
1847            } else {
1848                break;
1849            }
1850        }
1851
1852        for ch in next_chars {
1853            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1854                end += ch.len_utf8();
1855            } else {
1856                break;
1857            }
1858        }
1859
1860        (start..end, word_kind)
1861    }
1862
1863    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1864        let tree = self.tree.as_ref()?;
1865        let range = range.start.to_offset(self)..range.end.to_offset(self);
1866        let mut cursor = tree.root_node().walk();
1867
1868        // Descend to the first leaf that touches the start of the range,
1869        // and if the range is non-empty, extends beyond the start.
1870        while cursor.goto_first_child_for_byte(range.start).is_some() {
1871            if !range.is_empty() && cursor.node().end_byte() == range.start {
1872                cursor.goto_next_sibling();
1873            }
1874        }
1875
1876        // Ascend to the smallest ancestor that strictly contains the range.
1877        loop {
1878            let node_range = cursor.node().byte_range();
1879            if node_range.start <= range.start
1880                && node_range.end >= range.end
1881                && node_range.len() > range.len()
1882            {
1883                break;
1884            }
1885            if !cursor.goto_parent() {
1886                break;
1887            }
1888        }
1889
1890        let left_node = cursor.node();
1891
1892        // For an empty range, try to find another node immediately to the right of the range.
1893        if left_node.end_byte() == range.start {
1894            let mut right_node = None;
1895            while !cursor.goto_next_sibling() {
1896                if !cursor.goto_parent() {
1897                    break;
1898                }
1899            }
1900
1901            while cursor.node().start_byte() == range.start {
1902                right_node = Some(cursor.node());
1903                if !cursor.goto_first_child() {
1904                    break;
1905                }
1906            }
1907
1908            // If there is a candidate node on both sides of the (empty) range, then
1909            // decide between the two by favoring a named node over an anonymous token.
1910            // If both nodes are the same in that regard, favor the right one.
1911            if let Some(right_node) = right_node {
1912                if right_node.is_named() || !left_node.is_named() {
1913                    return Some(right_node.byte_range());
1914                }
1915            }
1916        }
1917
1918        Some(left_node.byte_range())
1919    }
1920
1921    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1922        self.outline_items_containing(0..self.len(), theme)
1923            .map(Outline::new)
1924    }
1925
1926    pub fn symbols_containing<T: ToOffset>(
1927        &self,
1928        position: T,
1929        theme: Option<&SyntaxTheme>,
1930    ) -> Option<Vec<OutlineItem<Anchor>>> {
1931        let position = position.to_offset(&self);
1932        let mut items =
1933            self.outline_items_containing(position.saturating_sub(1)..position + 1, theme)?;
1934        let mut prev_depth = None;
1935        items.retain(|item| {
1936            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
1937            prev_depth = Some(item.depth);
1938            result
1939        });
1940        Some(items)
1941    }
1942
1943    fn outline_items_containing(
1944        &self,
1945        range: Range<usize>,
1946        theme: Option<&SyntaxTheme>,
1947    ) -> Option<Vec<OutlineItem<Anchor>>> {
1948        let tree = self.tree.as_ref()?;
1949        let grammar = self
1950            .language
1951            .as_ref()
1952            .and_then(|language| language.grammar.as_ref())?;
1953
1954        let outline_query = grammar.outline_query.as_ref()?;
1955        let mut cursor = QueryCursorHandle::new();
1956        cursor.set_byte_range(range.clone());
1957        let matches = cursor.matches(
1958            outline_query,
1959            tree.root_node(),
1960            TextProvider(self.as_rope()),
1961        );
1962
1963        let mut chunks = self.chunks(0..self.len(), true);
1964
1965        let item_capture_ix = outline_query.capture_index_for_name("item")?;
1966        let name_capture_ix = outline_query.capture_index_for_name("name")?;
1967        let context_capture_ix = outline_query
1968            .capture_index_for_name("context")
1969            .unwrap_or(u32::MAX);
1970
1971        let mut stack = Vec::<Range<usize>>::new();
1972        let items = matches
1973            .filter_map(|mat| {
1974                let item_node = mat.nodes_for_capture_index(item_capture_ix).next()?;
1975                let item_range = item_node.start_byte()..item_node.end_byte();
1976                if item_range.end < range.start || item_range.start > range.end {
1977                    return None;
1978                }
1979                let mut text = String::new();
1980                let mut name_ranges = Vec::new();
1981                let mut highlight_ranges = Vec::new();
1982
1983                for capture in mat.captures {
1984                    let node_is_name;
1985                    if capture.index == name_capture_ix {
1986                        node_is_name = true;
1987                    } else if capture.index == context_capture_ix {
1988                        node_is_name = false;
1989                    } else {
1990                        continue;
1991                    }
1992
1993                    let range = capture.node.start_byte()..capture.node.end_byte();
1994                    if !text.is_empty() {
1995                        text.push(' ');
1996                    }
1997                    if node_is_name {
1998                        let mut start = text.len();
1999                        let end = start + range.len();
2000
2001                        // When multiple names are captured, then the matcheable text
2002                        // includes the whitespace in between the names.
2003                        if !name_ranges.is_empty() {
2004                            start -= 1;
2005                        }
2006
2007                        name_ranges.push(start..end);
2008                    }
2009
2010                    let mut offset = range.start;
2011                    chunks.seek(offset);
2012                    while let Some(mut chunk) = chunks.next() {
2013                        if chunk.text.len() > range.end - offset {
2014                            chunk.text = &chunk.text[0..(range.end - offset)];
2015                            offset = range.end;
2016                        } else {
2017                            offset += chunk.text.len();
2018                        }
2019                        let style = chunk
2020                            .syntax_highlight_id
2021                            .zip(theme)
2022                            .and_then(|(highlight, theme)| highlight.style(theme));
2023                        if let Some(style) = style {
2024                            let start = text.len();
2025                            let end = start + chunk.text.len();
2026                            highlight_ranges.push((start..end, style));
2027                        }
2028                        text.push_str(chunk.text);
2029                        if offset >= range.end {
2030                            break;
2031                        }
2032                    }
2033                }
2034
2035                while stack.last().map_or(false, |prev_range| {
2036                    prev_range.start > item_range.start || prev_range.end < item_range.end
2037                }) {
2038                    stack.pop();
2039                }
2040                stack.push(item_range.clone());
2041
2042                Some(OutlineItem {
2043                    depth: stack.len() - 1,
2044                    range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2045                    text,
2046                    highlight_ranges,
2047                    name_ranges,
2048                })
2049            })
2050            .collect::<Vec<_>>();
2051        Some(items)
2052    }
2053
2054    pub fn enclosing_bracket_ranges<T: ToOffset>(
2055        &self,
2056        range: Range<T>,
2057    ) -> Option<(Range<usize>, Range<usize>)> {
2058        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
2059        let brackets_query = grammar.brackets_query.as_ref()?;
2060        let open_capture_ix = brackets_query.capture_index_for_name("open")?;
2061        let close_capture_ix = brackets_query.capture_index_for_name("close")?;
2062
2063        // Find bracket pairs that *inclusively* contain the given range.
2064        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
2065        let mut cursor = QueryCursorHandle::new();
2066        let matches = cursor.set_byte_range(range).matches(
2067            &brackets_query,
2068            tree.root_node(),
2069            TextProvider(self.as_rope()),
2070        );
2071
2072        // Get the ranges of the innermost pair of brackets.
2073        matches
2074            .filter_map(|mat| {
2075                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
2076                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
2077                Some((open.byte_range(), close.byte_range()))
2078            })
2079            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
2080    }
2081
2082    pub fn remote_selections_in_range<'a>(
2083        &'a self,
2084        range: Range<Anchor>,
2085    ) -> impl 'a
2086           + Iterator<
2087        Item = (
2088            ReplicaId,
2089            bool,
2090            impl 'a + Iterator<Item = &'a Selection<Anchor>>,
2091        ),
2092    > {
2093        self.remote_selections
2094            .iter()
2095            .filter(|(replica_id, set)| {
2096                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2097            })
2098            .map(move |(replica_id, set)| {
2099                let start_ix = match set.selections.binary_search_by(|probe| {
2100                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
2101                }) {
2102                    Ok(ix) | Err(ix) => ix,
2103                };
2104                let end_ix = match set.selections.binary_search_by(|probe| {
2105                    probe.start.cmp(&range.end, self).then(Ordering::Less)
2106                }) {
2107                    Ok(ix) | Err(ix) => ix,
2108                };
2109
2110                (
2111                    *replica_id,
2112                    set.line_mode,
2113                    set.selections[start_ix..end_ix].iter(),
2114                )
2115            })
2116    }
2117
2118    pub fn diagnostics_in_range<'a, T, O>(
2119        &'a self,
2120        search_range: Range<T>,
2121        reversed: bool,
2122    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2123    where
2124        T: 'a + Clone + ToOffset,
2125        O: 'a + FromAnchor,
2126    {
2127        self.diagnostics
2128            .range(search_range.clone(), self, true, reversed)
2129    }
2130
2131    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2132        let mut groups = Vec::new();
2133        self.diagnostics.groups(&mut groups, self);
2134        groups
2135    }
2136
2137    pub fn diagnostic_group<'a, O>(
2138        &'a self,
2139        group_id: usize,
2140    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2141    where
2142        O: 'a + FromAnchor,
2143    {
2144        self.diagnostics.group(group_id, self)
2145    }
2146
2147    pub fn diagnostics_update_count(&self) -> usize {
2148        self.diagnostics_update_count
2149    }
2150
2151    pub fn parse_count(&self) -> usize {
2152        self.parse_count
2153    }
2154
2155    pub fn selections_update_count(&self) -> usize {
2156        self.selections_update_count
2157    }
2158
2159    pub fn file(&self) -> Option<&dyn File> {
2160        self.file.as_deref()
2161    }
2162
2163    pub fn file_update_count(&self) -> usize {
2164        self.file_update_count
2165    }
2166}
2167
2168pub fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
2169    indent_size_for_text(text.chars_at(Point::new(row, 0)))
2170}
2171
2172pub fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
2173    let mut result = IndentSize::spaces(0);
2174    for c in text {
2175        let kind = match c {
2176            ' ' => IndentKind::Space,
2177            '\t' => IndentKind::Tab,
2178            _ => break,
2179        };
2180        if result.len == 0 {
2181            result.kind = kind;
2182        }
2183        result.len += 1;
2184    }
2185    result
2186}
2187
2188impl Clone for BufferSnapshot {
2189    fn clone(&self) -> Self {
2190        Self {
2191            text: self.text.clone(),
2192            tree: self.tree.clone(),
2193            file: self.file.clone(),
2194            remote_selections: self.remote_selections.clone(),
2195            diagnostics: self.diagnostics.clone(),
2196            selections_update_count: self.selections_update_count,
2197            diagnostics_update_count: self.diagnostics_update_count,
2198            file_update_count: self.file_update_count,
2199            language: self.language.clone(),
2200            parse_count: self.parse_count,
2201        }
2202    }
2203}
2204
2205impl Deref for BufferSnapshot {
2206    type Target = text::BufferSnapshot;
2207
2208    fn deref(&self) -> &Self::Target {
2209        &self.text
2210    }
2211}
2212
2213impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
2214    type I = ByteChunks<'a>;
2215
2216    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
2217        ByteChunks(self.0.chunks_in_range(node.byte_range()))
2218    }
2219}
2220
2221pub(crate) struct ByteChunks<'a>(rope::Chunks<'a>);
2222
2223impl<'a> Iterator for ByteChunks<'a> {
2224    type Item = &'a [u8];
2225
2226    fn next(&mut self) -> Option<Self::Item> {
2227        self.0.next().map(str::as_bytes)
2228    }
2229}
2230
2231unsafe impl<'a> Send for BufferChunks<'a> {}
2232
2233impl<'a> BufferChunks<'a> {
2234    pub(crate) fn new(
2235        text: &'a Rope,
2236        range: Range<usize>,
2237        tree: Option<&'a Tree>,
2238        grammar: Option<&'a Arc<Grammar>>,
2239        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
2240    ) -> Self {
2241        let mut highlights = None;
2242        if let Some((grammar, tree)) = grammar.zip(tree) {
2243            if let Some(highlights_query) = grammar.highlights_query.as_ref() {
2244                let mut query_cursor = QueryCursorHandle::new();
2245
2246                // TODO - add a Tree-sitter API to remove the need for this.
2247                let cursor = unsafe {
2248                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
2249                };
2250                let captures = cursor.set_byte_range(range.clone()).captures(
2251                    highlights_query,
2252                    tree.root_node(),
2253                    TextProvider(text),
2254                );
2255                highlights = Some(BufferChunkHighlights {
2256                    captures,
2257                    next_capture: None,
2258                    stack: Default::default(),
2259                    highlight_map: grammar.highlight_map(),
2260                    _query_cursor: query_cursor,
2261                })
2262            }
2263        }
2264
2265        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2266        let chunks = text.chunks_in_range(range.clone());
2267
2268        BufferChunks {
2269            range,
2270            chunks,
2271            diagnostic_endpoints,
2272            error_depth: 0,
2273            warning_depth: 0,
2274            information_depth: 0,
2275            hint_depth: 0,
2276            unnecessary_depth: 0,
2277            highlights,
2278        }
2279    }
2280
2281    pub fn seek(&mut self, offset: usize) {
2282        self.range.start = offset;
2283        self.chunks.seek(self.range.start);
2284        if let Some(highlights) = self.highlights.as_mut() {
2285            highlights
2286                .stack
2287                .retain(|(end_offset, _)| *end_offset > offset);
2288            if let Some((mat, capture_ix)) = &highlights.next_capture {
2289                let capture = mat.captures[*capture_ix as usize];
2290                if offset >= capture.node.start_byte() {
2291                    let next_capture_end = capture.node.end_byte();
2292                    if offset < next_capture_end {
2293                        highlights.stack.push((
2294                            next_capture_end,
2295                            highlights.highlight_map.get(capture.index),
2296                        ));
2297                    }
2298                    highlights.next_capture.take();
2299                }
2300            }
2301            highlights.captures.set_byte_range(self.range.clone());
2302        }
2303    }
2304
2305    pub fn offset(&self) -> usize {
2306        self.range.start
2307    }
2308
2309    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2310        let depth = match endpoint.severity {
2311            DiagnosticSeverity::ERROR => &mut self.error_depth,
2312            DiagnosticSeverity::WARNING => &mut self.warning_depth,
2313            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2314            DiagnosticSeverity::HINT => &mut self.hint_depth,
2315            _ => return,
2316        };
2317        if endpoint.is_start {
2318            *depth += 1;
2319        } else {
2320            *depth -= 1;
2321        }
2322
2323        if endpoint.is_unnecessary {
2324            if endpoint.is_start {
2325                self.unnecessary_depth += 1;
2326            } else {
2327                self.unnecessary_depth -= 1;
2328            }
2329        }
2330    }
2331
2332    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
2333        if self.error_depth > 0 {
2334            Some(DiagnosticSeverity::ERROR)
2335        } else if self.warning_depth > 0 {
2336            Some(DiagnosticSeverity::WARNING)
2337        } else if self.information_depth > 0 {
2338            Some(DiagnosticSeverity::INFORMATION)
2339        } else if self.hint_depth > 0 {
2340            Some(DiagnosticSeverity::HINT)
2341        } else {
2342            None
2343        }
2344    }
2345
2346    fn current_code_is_unnecessary(&self) -> bool {
2347        self.unnecessary_depth > 0
2348    }
2349}
2350
2351impl<'a> Iterator for BufferChunks<'a> {
2352    type Item = Chunk<'a>;
2353
2354    fn next(&mut self) -> Option<Self::Item> {
2355        let mut next_capture_start = usize::MAX;
2356        let mut next_diagnostic_endpoint = usize::MAX;
2357
2358        if let Some(highlights) = self.highlights.as_mut() {
2359            while let Some((parent_capture_end, _)) = highlights.stack.last() {
2360                if *parent_capture_end <= self.range.start {
2361                    highlights.stack.pop();
2362                } else {
2363                    break;
2364                }
2365            }
2366
2367            if highlights.next_capture.is_none() {
2368                highlights.next_capture = highlights.captures.next();
2369            }
2370
2371            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2372                let capture = mat.captures[*capture_ix as usize];
2373                if self.range.start < capture.node.start_byte() {
2374                    next_capture_start = capture.node.start_byte();
2375                    break;
2376                } else {
2377                    let highlight_id = highlights.highlight_map.get(capture.index);
2378                    highlights
2379                        .stack
2380                        .push((capture.node.end_byte(), highlight_id));
2381                    highlights.next_capture = highlights.captures.next();
2382                }
2383            }
2384        }
2385
2386        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2387            if endpoint.offset <= self.range.start {
2388                self.update_diagnostic_depths(endpoint);
2389                self.diagnostic_endpoints.next();
2390            } else {
2391                next_diagnostic_endpoint = endpoint.offset;
2392                break;
2393            }
2394        }
2395
2396        if let Some(chunk) = self.chunks.peek() {
2397            let chunk_start = self.range.start;
2398            let mut chunk_end = (self.chunks.offset() + chunk.len())
2399                .min(next_capture_start)
2400                .min(next_diagnostic_endpoint);
2401            let mut highlight_id = None;
2402            if let Some(highlights) = self.highlights.as_ref() {
2403                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2404                    chunk_end = chunk_end.min(*parent_capture_end);
2405                    highlight_id = Some(*parent_highlight_id);
2406                }
2407            }
2408
2409            let slice =
2410                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2411            self.range.start = chunk_end;
2412            if self.range.start == self.chunks.offset() + chunk.len() {
2413                self.chunks.next().unwrap();
2414            }
2415
2416            Some(Chunk {
2417                text: slice,
2418                syntax_highlight_id: highlight_id,
2419                highlight_style: None,
2420                diagnostic_severity: self.current_diagnostic_severity(),
2421                is_unnecessary: self.current_code_is_unnecessary(),
2422            })
2423        } else {
2424            None
2425        }
2426    }
2427}
2428
2429impl QueryCursorHandle {
2430    pub(crate) fn new() -> Self {
2431        let mut cursor = QUERY_CURSORS
2432            .lock()
2433            .pop()
2434            .unwrap_or_else(|| QueryCursor::new());
2435        cursor.set_match_limit(64);
2436        QueryCursorHandle(Some(cursor))
2437    }
2438}
2439
2440impl Deref for QueryCursorHandle {
2441    type Target = QueryCursor;
2442
2443    fn deref(&self) -> &Self::Target {
2444        self.0.as_ref().unwrap()
2445    }
2446}
2447
2448impl DerefMut for QueryCursorHandle {
2449    fn deref_mut(&mut self) -> &mut Self::Target {
2450        self.0.as_mut().unwrap()
2451    }
2452}
2453
2454impl Drop for QueryCursorHandle {
2455    fn drop(&mut self) {
2456        let mut cursor = self.0.take().unwrap();
2457        cursor.set_byte_range(0..usize::MAX);
2458        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2459        QUERY_CURSORS.lock().push(cursor)
2460    }
2461}
2462
2463trait ToTreeSitterPoint {
2464    fn to_ts_point(self) -> tree_sitter::Point;
2465    fn from_ts_point(point: tree_sitter::Point) -> Self;
2466}
2467
2468impl ToTreeSitterPoint for Point {
2469    fn to_ts_point(self) -> tree_sitter::Point {
2470        tree_sitter::Point::new(self.row as usize, self.column as usize)
2471    }
2472
2473    fn from_ts_point(point: tree_sitter::Point) -> Self {
2474        Point::new(point.row as u32, point.column as u32)
2475    }
2476}
2477
2478impl operation_queue::Operation for Operation {
2479    fn lamport_timestamp(&self) -> clock::Lamport {
2480        match self {
2481            Operation::Buffer(_) => {
2482                unreachable!("buffer operations should never be deferred at this layer")
2483            }
2484            Operation::UpdateDiagnostics {
2485                lamport_timestamp, ..
2486            }
2487            | Operation::UpdateSelections {
2488                lamport_timestamp, ..
2489            }
2490            | Operation::UpdateCompletionTriggers {
2491                lamport_timestamp, ..
2492            } => *lamport_timestamp,
2493        }
2494    }
2495}
2496
2497impl Default for Diagnostic {
2498    fn default() -> Self {
2499        Self {
2500            code: None,
2501            severity: DiagnosticSeverity::ERROR,
2502            message: Default::default(),
2503            group_id: 0,
2504            is_primary: false,
2505            is_valid: true,
2506            is_disk_based: false,
2507            is_unnecessary: false,
2508        }
2509    }
2510}
2511
2512impl IndentSize {
2513    pub fn spaces(len: u32) -> Self {
2514        Self {
2515            len,
2516            kind: IndentKind::Space,
2517        }
2518    }
2519
2520    pub fn tab() -> Self {
2521        Self {
2522            len: 1,
2523            kind: IndentKind::Tab,
2524        }
2525    }
2526
2527    pub fn chars(&self) -> impl Iterator<Item = char> {
2528        iter::repeat(self.char()).take(self.len as usize)
2529    }
2530
2531    pub fn char(&self) -> char {
2532        match self.kind {
2533            IndentKind::Space => ' ',
2534            IndentKind::Tab => '\t',
2535        }
2536    }
2537
2538    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
2539        match direction {
2540            Ordering::Less => {
2541                if self.kind == size.kind && self.len >= size.len {
2542                    self.len -= size.len;
2543                }
2544            }
2545            Ordering::Equal => {}
2546            Ordering::Greater => {
2547                if self.len == 0 {
2548                    self = size;
2549                } else if self.kind == size.kind {
2550                    self.len += size.len;
2551                }
2552            }
2553        }
2554        self
2555    }
2556}
2557
2558impl Completion {
2559    pub fn sort_key(&self) -> (usize, &str) {
2560        let kind_key = match self.lsp_completion.kind {
2561            Some(lsp::CompletionItemKind::VARIABLE) => 0,
2562            _ => 1,
2563        };
2564        (kind_key, &self.label.text[self.label.filter_range.clone()])
2565    }
2566
2567    pub fn is_snippet(&self) -> bool {
2568        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
2569    }
2570}
2571
2572pub fn contiguous_ranges(
2573    values: impl Iterator<Item = u32>,
2574    max_len: usize,
2575) -> impl Iterator<Item = Range<u32>> {
2576    let mut values = values.into_iter();
2577    let mut current_range: Option<Range<u32>> = None;
2578    std::iter::from_fn(move || loop {
2579        if let Some(value) = values.next() {
2580            if let Some(range) = &mut current_range {
2581                if value == range.end && range.len() < max_len {
2582                    range.end += 1;
2583                    continue;
2584                }
2585            }
2586
2587            let prev_range = current_range.clone();
2588            current_range = Some(value..(value + 1));
2589            if prev_range.is_some() {
2590                return prev_range;
2591            }
2592        } else {
2593            return current_range.take();
2594        }
2595    })
2596}
2597
2598pub fn char_kind(c: char) -> CharKind {
2599    if c.is_whitespace() {
2600        CharKind::Whitespace
2601    } else if c.is_alphanumeric() || c == '_' {
2602        CharKind::Word
2603    } else {
2604        CharKind::Punctuation
2605    }
2606}