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