buffer.rs

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