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