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