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                                return;
 742                            }
 743                        });
 744                    })
 745                    .detach();
 746                }
 747            }
 748        }
 749        false
 750    }
 751
 752    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 753        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 754            let (bytes, lines) = edit.flatten();
 755            tree.tree.edit(&InputEdit {
 756                start_byte: bytes.new.start,
 757                old_end_byte: bytes.new.start + bytes.old.len(),
 758                new_end_byte: bytes.new.end,
 759                start_position: lines.new.start.to_ts_point(),
 760                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 761                    .to_ts_point(),
 762                new_end_position: lines.new.end.to_ts_point(),
 763            });
 764        }
 765        tree.version = self.version();
 766    }
 767
 768    fn did_finish_parsing(
 769        &mut self,
 770        tree: Tree,
 771        version: clock::Global,
 772        cx: &mut ModelContext<Self>,
 773    ) {
 774        self.parse_count += 1;
 775        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 776        self.request_autoindent(cx);
 777        cx.emit(Event::Reparsed);
 778        cx.notify();
 779    }
 780
 781    pub fn update_diagnostics(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
 782        let lamport_timestamp = self.text.lamport_clock.tick();
 783        let op = Operation::UpdateDiagnostics {
 784            diagnostics: diagnostics.iter().cloned().collect(),
 785            lamport_timestamp,
 786        };
 787        self.apply_diagnostic_update(diagnostics, lamport_timestamp, cx);
 788        self.send_operation(op, cx);
 789    }
 790
 791    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 792        if let Some(indent_sizes) = self.compute_autoindents() {
 793            let indent_sizes = cx.background().spawn(indent_sizes);
 794            match cx
 795                .background()
 796                .block_with_timeout(Duration::from_micros(500), indent_sizes)
 797            {
 798                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
 799                Err(indent_sizes) => {
 800                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 801                        let indent_sizes = indent_sizes.await;
 802                        this.update(&mut cx, |this, cx| {
 803                            this.apply_autoindents(indent_sizes, cx);
 804                        });
 805                    }));
 806                }
 807            }
 808        }
 809    }
 810
 811    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
 812        let max_rows_between_yields = 100;
 813        let snapshot = self.snapshot();
 814        if snapshot.language.is_none()
 815            || snapshot.tree.is_none()
 816            || self.autoindent_requests.is_empty()
 817        {
 818            return None;
 819        }
 820
 821        let autoindent_requests = self.autoindent_requests.clone();
 822        Some(async move {
 823            let mut indent_sizes = BTreeMap::new();
 824            for request in autoindent_requests {
 825                // Resolve each edited range to its row in the current buffer and in the
 826                // buffer before this batch of edits.
 827                let mut row_ranges = Vec::new();
 828                let mut old_to_new_rows = BTreeMap::new();
 829                for entry in &request.entries {
 830                    let position = entry.range.start;
 831                    let new_row = position.to_point(&snapshot).row;
 832                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
 833                    if !entry.first_line_is_new {
 834                        let old_row = position.to_point(&request.before_edit).row;
 835                        old_to_new_rows.insert(old_row, new_row);
 836                    }
 837                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
 838                }
 839
 840                // Build a map containing the suggested indentation for each of the edited lines
 841                // with respect to the state of the buffer before these edits. This map is keyed
 842                // by the rows for these lines in the current state of the buffer.
 843                let mut old_suggestions = BTreeMap::<u32, IndentSize>::default();
 844                let old_edited_ranges =
 845                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 846                for old_edited_range in old_edited_ranges {
 847                    let suggestions = request
 848                        .before_edit
 849                        .suggest_autoindents(old_edited_range.clone())
 850                        .into_iter()
 851                        .flatten();
 852                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 853                        if let Some(suggestion) = suggestion {
 854                            let suggested_indent = old_to_new_rows
 855                                .get(&suggestion.basis_row)
 856                                .and_then(|from_row| old_suggestions.get(from_row).copied())
 857                                .unwrap_or_else(|| {
 858                                    request
 859                                        .before_edit
 860                                        .indent_size_for_line(suggestion.basis_row)
 861                                })
 862                                .with_delta(suggestion.delta, request.indent_size);
 863                            old_suggestions
 864                                .insert(*old_to_new_rows.get(&old_row).unwrap(), suggested_indent);
 865                        }
 866                    }
 867                    yield_now().await;
 868                }
 869
 870                // In block mode, only compute indentation suggestions for the first line
 871                // of each insertion. Otherwise, compute suggestions for every inserted line.
 872                let new_edited_row_ranges = contiguous_ranges(
 873                    row_ranges.iter().flat_map(|(range, _)| {
 874                        if request.is_block_mode {
 875                            range.start..range.start + 1
 876                        } else {
 877                            range.clone()
 878                        }
 879                    }),
 880                    max_rows_between_yields,
 881                );
 882
 883                // Compute new suggestions for each line, but only include them in the result
 884                // if they differ from the old suggestion for that line.
 885                for new_edited_row_range in new_edited_row_ranges {
 886                    let suggestions = snapshot
 887                        .suggest_autoindents(new_edited_row_range.clone())
 888                        .into_iter()
 889                        .flatten();
 890                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 891                        if let Some(suggestion) = suggestion {
 892                            let suggested_indent = indent_sizes
 893                                .get(&suggestion.basis_row)
 894                                .copied()
 895                                .unwrap_or_else(|| {
 896                                    snapshot.indent_size_for_line(suggestion.basis_row)
 897                                })
 898                                .with_delta(suggestion.delta, request.indent_size);
 899                            if old_suggestions
 900                                .get(&new_row)
 901                                .map_or(true, |old_indentation| {
 902                                    suggested_indent != *old_indentation
 903                                })
 904                            {
 905                                indent_sizes.insert(new_row, suggested_indent);
 906                            }
 907                        }
 908                    }
 909                    yield_now().await;
 910                }
 911
 912                // For each block of inserted text, adjust the indentation of the remaining
 913                // lines of the block by the same amount as the first line was adjusted.
 914                if request.is_block_mode {
 915                    for (row_range, original_indent_column) in
 916                        row_ranges
 917                            .into_iter()
 918                            .filter_map(|(range, original_indent_column)| {
 919                                if range.len() > 1 {
 920                                    Some((range, original_indent_column?))
 921                                } else {
 922                                    None
 923                                }
 924                            })
 925                    {
 926                        let new_indent = indent_sizes
 927                            .get(&row_range.start)
 928                            .copied()
 929                            .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
 930                        let delta = new_indent.len as i64 - original_indent_column as i64;
 931                        if delta != 0 {
 932                            for row in row_range.skip(1) {
 933                                indent_sizes.entry(row).or_insert_with(|| {
 934                                    let mut size = snapshot.indent_size_for_line(row);
 935                                    if size.kind == new_indent.kind {
 936                                        if delta > 0 {
 937                                            size.len = size.len + delta as u32;
 938                                        } else if delta < 0 {
 939                                            size.len = size.len.saturating_sub(-delta as u32);
 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        if new_size.len > current_size.len {
 982            let point = Point::new(row, 0);
 983            Some((
 984                point..point,
 985                iter::repeat(new_size.char())
 986                    .take((new_size.len - current_size.len) as usize)
 987                    .collect::<String>(),
 988            ))
 989        } else if new_size.len < current_size.len {
 990            Some((
 991                Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
 992                String::new(),
 993            ))
 994        } else {
 995            None
 996        }
 997    }
 998
 999    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1000        let old_text = self.as_rope().clone();
1001        let base_version = self.version();
1002        cx.background().spawn(async move {
1003            let old_text = old_text.to_string();
1004            let line_ending = LineEnding::detect(&new_text);
1005            LineEnding::normalize(&mut new_text);
1006            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_str())
1007                .iter_all_changes()
1008                .map(|c| (c.tag(), c.value().len()))
1009                .collect::<Vec<_>>();
1010            Diff {
1011                base_version,
1012                new_text: new_text.into(),
1013                changes,
1014                line_ending,
1015                start_offset: 0,
1016            }
1017        })
1018    }
1019
1020    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<&Transaction> {
1021        if self.version == diff.base_version {
1022            self.finalize_last_transaction();
1023            self.start_transaction();
1024            self.text.set_line_ending(diff.line_ending);
1025            let mut offset = diff.start_offset;
1026            for (tag, len) in diff.changes {
1027                let range = offset..(offset + len);
1028                match tag {
1029                    ChangeTag::Equal => offset += len,
1030                    ChangeTag::Delete => {
1031                        self.edit([(range, "")], None, cx);
1032                    }
1033                    ChangeTag::Insert => {
1034                        self.edit(
1035                            [(
1036                                offset..offset,
1037                                &diff.new_text[range.start - diff.start_offset
1038                                    ..range.end - diff.start_offset],
1039                            )],
1040                            None,
1041                            cx,
1042                        );
1043                        offset += len;
1044                    }
1045                }
1046            }
1047            if self.end_transaction(cx).is_some() {
1048                self.finalize_last_transaction()
1049            } else {
1050                None
1051            }
1052        } else {
1053            None
1054        }
1055    }
1056
1057    pub fn is_dirty(&self) -> bool {
1058        self.saved_version_fingerprint != self.as_rope().fingerprint()
1059            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1060    }
1061
1062    pub fn has_conflict(&self) -> bool {
1063        self.saved_version_fingerprint != self.as_rope().fingerprint()
1064            && self
1065                .file
1066                .as_ref()
1067                .map_or(false, |file| file.mtime() > self.saved_mtime)
1068    }
1069
1070    pub fn subscribe(&mut self) -> Subscription {
1071        self.text.subscribe()
1072    }
1073
1074    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1075        self.start_transaction_at(Instant::now())
1076    }
1077
1078    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1079        self.transaction_depth += 1;
1080        if self.was_dirty_before_starting_transaction.is_none() {
1081            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1082        }
1083        self.text.start_transaction_at(now)
1084    }
1085
1086    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1087        self.end_transaction_at(Instant::now(), cx)
1088    }
1089
1090    pub fn end_transaction_at(
1091        &mut self,
1092        now: Instant,
1093        cx: &mut ModelContext<Self>,
1094    ) -> Option<TransactionId> {
1095        assert!(self.transaction_depth > 0);
1096        self.transaction_depth -= 1;
1097        let was_dirty = if self.transaction_depth == 0 {
1098            self.was_dirty_before_starting_transaction.take().unwrap()
1099        } else {
1100            false
1101        };
1102        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1103            self.did_edit(&start_version, was_dirty, cx);
1104            Some(transaction_id)
1105        } else {
1106            None
1107        }
1108    }
1109
1110    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1111        self.text.push_transaction(transaction, now);
1112    }
1113
1114    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1115        self.text.finalize_last_transaction()
1116    }
1117
1118    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1119        self.text.group_until_transaction(transaction_id);
1120    }
1121
1122    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1123        self.text.forget_transaction(transaction_id);
1124    }
1125
1126    pub fn wait_for_edits(
1127        &mut self,
1128        edit_ids: impl IntoIterator<Item = clock::Local>,
1129    ) -> impl Future<Output = ()> {
1130        self.text.wait_for_edits(edit_ids)
1131    }
1132
1133    pub fn wait_for_anchors<'a>(
1134        &mut self,
1135        anchors: impl IntoIterator<Item = &'a Anchor>,
1136    ) -> impl Future<Output = ()> {
1137        self.text.wait_for_anchors(anchors)
1138    }
1139
1140    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1141        self.text.wait_for_version(version)
1142    }
1143
1144    pub fn set_active_selections(
1145        &mut self,
1146        selections: Arc<[Selection<Anchor>]>,
1147        line_mode: bool,
1148        cx: &mut ModelContext<Self>,
1149    ) {
1150        let lamport_timestamp = self.text.lamport_clock.tick();
1151        self.remote_selections.insert(
1152            self.text.replica_id(),
1153            SelectionSet {
1154                selections: selections.clone(),
1155                lamport_timestamp,
1156                line_mode,
1157            },
1158        );
1159        self.send_operation(
1160            Operation::UpdateSelections {
1161                selections,
1162                line_mode,
1163                lamport_timestamp,
1164            },
1165            cx,
1166        );
1167    }
1168
1169    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1170        self.set_active_selections(Arc::from([]), false, cx);
1171    }
1172
1173    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Local>
1174    where
1175        T: Into<Arc<str>>,
1176    {
1177        self.edit([(0..self.len(), text)], None, cx)
1178    }
1179
1180    pub fn edit<I, S, T>(
1181        &mut self,
1182        edits_iter: I,
1183        autoindent_mode: Option<AutoindentMode>,
1184        cx: &mut ModelContext<Self>,
1185    ) -> Option<clock::Local>
1186    where
1187        I: IntoIterator<Item = (Range<S>, T)>,
1188        S: ToOffset,
1189        T: Into<Arc<str>>,
1190    {
1191        // Skip invalid edits and coalesce contiguous ones.
1192        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1193        for (range, new_text) in edits_iter {
1194            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1195            if range.start > range.end {
1196                mem::swap(&mut range.start, &mut range.end);
1197            }
1198            let new_text = new_text.into();
1199            if !new_text.is_empty() || !range.is_empty() {
1200                if let Some((prev_range, prev_text)) = edits.last_mut() {
1201                    if prev_range.end >= range.start {
1202                        prev_range.end = cmp::max(prev_range.end, range.end);
1203                        *prev_text = format!("{prev_text}{new_text}").into();
1204                    } else {
1205                        edits.push((range, new_text));
1206                    }
1207                } else {
1208                    edits.push((range, new_text));
1209                }
1210            }
1211        }
1212        if edits.is_empty() {
1213            return None;
1214        }
1215
1216        self.start_transaction();
1217        self.pending_autoindent.take();
1218        let autoindent_request = autoindent_mode
1219            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1220
1221        let edit_operation = self.text.edit(edits.iter().cloned());
1222        let edit_id = edit_operation.local_timestamp();
1223
1224        if let Some((before_edit, mode)) = autoindent_request {
1225            let indent_size = before_edit.single_indent_size(cx);
1226            let (start_columns, is_block_mode) = match mode {
1227                AutoindentMode::Block {
1228                    original_indent_columns: start_columns,
1229                } => (start_columns, true),
1230                AutoindentMode::EachLine => (Default::default(), false),
1231            };
1232
1233            let mut delta = 0isize;
1234            let entries = edits
1235                .into_iter()
1236                .enumerate()
1237                .zip(&edit_operation.as_edit().unwrap().new_text)
1238                .map(|((ix, (range, _)), new_text)| {
1239                    let new_text_len = new_text.len();
1240                    let old_start = range.start.to_point(&before_edit);
1241                    let new_start = (delta + range.start as isize) as usize;
1242                    delta += new_text_len as isize - (range.end as isize - range.start as isize);
1243
1244                    let mut range_of_insertion_to_indent = 0..new_text_len;
1245                    let mut first_line_is_new = false;
1246                    let mut start_column = None;
1247
1248                    // When inserting an entire line at the beginning of an existing line,
1249                    // treat the insertion as new.
1250                    if new_text.contains('\n')
1251                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1252                    {
1253                        first_line_is_new = true;
1254                    }
1255
1256                    // When inserting text starting with a newline, avoid auto-indenting the
1257                    // previous line.
1258                    if new_text[range_of_insertion_to_indent.clone()].starts_with('\n') {
1259                        range_of_insertion_to_indent.start += 1;
1260                        first_line_is_new = true;
1261                    }
1262
1263                    // Avoid auto-indenting after the insertion.
1264                    if is_block_mode {
1265                        start_column = start_columns.get(ix).copied();
1266                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1267                            range_of_insertion_to_indent.end -= 1;
1268                        }
1269                    }
1270
1271                    AutoindentRequestEntry {
1272                        first_line_is_new,
1273                        original_indent_column: start_column,
1274                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1275                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1276                    }
1277                })
1278                .collect();
1279
1280            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1281                before_edit,
1282                entries,
1283                indent_size,
1284                is_block_mode,
1285            }));
1286        }
1287
1288        self.end_transaction(cx);
1289        self.send_operation(Operation::Buffer(edit_operation), cx);
1290        Some(edit_id)
1291    }
1292
1293    fn did_edit(
1294        &mut self,
1295        old_version: &clock::Global,
1296        was_dirty: bool,
1297        cx: &mut ModelContext<Self>,
1298    ) {
1299        if self.edits_since::<usize>(old_version).next().is_none() {
1300            return;
1301        }
1302
1303        self.reparse(cx);
1304
1305        cx.emit(Event::Edited);
1306        if was_dirty != self.is_dirty() {
1307            cx.emit(Event::DirtyChanged);
1308        }
1309        cx.notify();
1310    }
1311
1312    fn grammar(&self) -> Option<&Arc<Grammar>> {
1313        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1314    }
1315
1316    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1317        &mut self,
1318        ops: I,
1319        cx: &mut ModelContext<Self>,
1320    ) -> Result<()> {
1321        self.pending_autoindent.take();
1322        let was_dirty = self.is_dirty();
1323        let old_version = self.version.clone();
1324        let mut deferred_ops = Vec::new();
1325        let buffer_ops = ops
1326            .into_iter()
1327            .filter_map(|op| match op {
1328                Operation::Buffer(op) => Some(op),
1329                _ => {
1330                    if self.can_apply_op(&op) {
1331                        self.apply_op(op, cx);
1332                    } else {
1333                        deferred_ops.push(op);
1334                    }
1335                    None
1336                }
1337            })
1338            .collect::<Vec<_>>();
1339        self.text.apply_ops(buffer_ops)?;
1340        self.deferred_ops.insert(deferred_ops);
1341        self.flush_deferred_ops(cx);
1342        self.did_edit(&old_version, was_dirty, cx);
1343        // Notify independently of whether the buffer was edited as the operations could include a
1344        // selection update.
1345        cx.notify();
1346        Ok(())
1347    }
1348
1349    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1350        let mut deferred_ops = Vec::new();
1351        for op in self.deferred_ops.drain().iter().cloned() {
1352            if self.can_apply_op(&op) {
1353                self.apply_op(op, cx);
1354            } else {
1355                deferred_ops.push(op);
1356            }
1357        }
1358        self.deferred_ops.insert(deferred_ops);
1359    }
1360
1361    fn can_apply_op(&self, operation: &Operation) -> bool {
1362        match operation {
1363            Operation::Buffer(_) => {
1364                unreachable!("buffer operations should never be applied at this layer")
1365            }
1366            Operation::UpdateDiagnostics {
1367                diagnostics: diagnostic_set,
1368                ..
1369            } => diagnostic_set.iter().all(|diagnostic| {
1370                self.text.can_resolve(&diagnostic.range.start)
1371                    && self.text.can_resolve(&diagnostic.range.end)
1372            }),
1373            Operation::UpdateSelections { selections, .. } => selections
1374                .iter()
1375                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1376            Operation::UpdateCompletionTriggers { .. } => true,
1377        }
1378    }
1379
1380    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1381        match operation {
1382            Operation::Buffer(_) => {
1383                unreachable!("buffer operations should never be applied at this layer")
1384            }
1385            Operation::UpdateDiagnostics {
1386                diagnostics: diagnostic_set,
1387                lamport_timestamp,
1388            } => {
1389                let snapshot = self.snapshot();
1390                self.apply_diagnostic_update(
1391                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1392                    lamport_timestamp,
1393                    cx,
1394                );
1395            }
1396            Operation::UpdateSelections {
1397                selections,
1398                lamport_timestamp,
1399                line_mode,
1400            } => {
1401                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1402                    if set.lamport_timestamp > lamport_timestamp {
1403                        return;
1404                    }
1405                }
1406
1407                self.remote_selections.insert(
1408                    lamport_timestamp.replica_id,
1409                    SelectionSet {
1410                        selections,
1411                        lamport_timestamp,
1412                        line_mode,
1413                    },
1414                );
1415                self.text.lamport_clock.observe(lamport_timestamp);
1416                self.selections_update_count += 1;
1417            }
1418            Operation::UpdateCompletionTriggers {
1419                triggers,
1420                lamport_timestamp,
1421            } => {
1422                self.completion_triggers = triggers;
1423                self.text.lamport_clock.observe(lamport_timestamp);
1424            }
1425        }
1426    }
1427
1428    fn apply_diagnostic_update(
1429        &mut self,
1430        diagnostics: DiagnosticSet,
1431        lamport_timestamp: clock::Lamport,
1432        cx: &mut ModelContext<Self>,
1433    ) {
1434        if lamport_timestamp > self.diagnostics_timestamp {
1435            self.diagnostics = diagnostics;
1436            self.diagnostics_timestamp = lamport_timestamp;
1437            self.diagnostics_update_count += 1;
1438            self.text.lamport_clock.observe(lamport_timestamp);
1439            cx.notify();
1440            cx.emit(Event::DiagnosticsUpdated);
1441        }
1442    }
1443
1444    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1445        cx.emit(Event::Operation(operation));
1446    }
1447
1448    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1449        self.remote_selections.remove(&replica_id);
1450        cx.notify();
1451    }
1452
1453    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1454        let was_dirty = self.is_dirty();
1455        let old_version = self.version.clone();
1456
1457        if let Some((transaction_id, operation)) = self.text.undo() {
1458            self.send_operation(Operation::Buffer(operation), cx);
1459            self.did_edit(&old_version, was_dirty, cx);
1460            Some(transaction_id)
1461        } else {
1462            None
1463        }
1464    }
1465
1466    pub fn undo_to_transaction(
1467        &mut self,
1468        transaction_id: TransactionId,
1469        cx: &mut ModelContext<Self>,
1470    ) -> bool {
1471        let was_dirty = self.is_dirty();
1472        let old_version = self.version.clone();
1473
1474        let operations = self.text.undo_to_transaction(transaction_id);
1475        let undone = !operations.is_empty();
1476        for operation in operations {
1477            self.send_operation(Operation::Buffer(operation), cx);
1478        }
1479        if undone {
1480            self.did_edit(&old_version, was_dirty, cx)
1481        }
1482        undone
1483    }
1484
1485    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1486        let was_dirty = self.is_dirty();
1487        let old_version = self.version.clone();
1488
1489        if let Some((transaction_id, operation)) = self.text.redo() {
1490            self.send_operation(Operation::Buffer(operation), cx);
1491            self.did_edit(&old_version, was_dirty, cx);
1492            Some(transaction_id)
1493        } else {
1494            None
1495        }
1496    }
1497
1498    pub fn redo_to_transaction(
1499        &mut self,
1500        transaction_id: TransactionId,
1501        cx: &mut ModelContext<Self>,
1502    ) -> bool {
1503        let was_dirty = self.is_dirty();
1504        let old_version = self.version.clone();
1505
1506        let operations = self.text.redo_to_transaction(transaction_id);
1507        let redone = !operations.is_empty();
1508        for operation in operations {
1509            self.send_operation(Operation::Buffer(operation), cx);
1510        }
1511        if redone {
1512            self.did_edit(&old_version, was_dirty, cx)
1513        }
1514        redone
1515    }
1516
1517    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
1518        self.completion_triggers = triggers.clone();
1519        let lamport_timestamp = self.text.lamport_clock.tick();
1520        self.send_operation(
1521            Operation::UpdateCompletionTriggers {
1522                triggers,
1523                lamport_timestamp,
1524            },
1525            cx,
1526        );
1527        cx.notify();
1528    }
1529
1530    pub fn completion_triggers(&self) -> &[String] {
1531        &self.completion_triggers
1532    }
1533}
1534
1535#[cfg(any(test, feature = "test-support"))]
1536impl Buffer {
1537    pub fn set_group_interval(&mut self, group_interval: Duration) {
1538        self.text.set_group_interval(group_interval);
1539    }
1540
1541    pub fn randomly_edit<T>(
1542        &mut self,
1543        rng: &mut T,
1544        old_range_count: usize,
1545        cx: &mut ModelContext<Self>,
1546    ) where
1547        T: rand::Rng,
1548    {
1549        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
1550        let mut last_end = None;
1551        for _ in 0..old_range_count {
1552            if last_end.map_or(false, |last_end| last_end >= self.len()) {
1553                break;
1554            }
1555
1556            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1557            let mut range = self.random_byte_range(new_start, rng);
1558            if rng.gen_bool(0.2) {
1559                mem::swap(&mut range.start, &mut range.end);
1560            }
1561            last_end = Some(range.end);
1562
1563            let new_text_len = rng.gen_range(0..10);
1564            let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1565                .take(new_text_len)
1566                .collect();
1567
1568            edits.push((range, new_text));
1569        }
1570        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
1571        self.edit(edits, None, cx);
1572    }
1573
1574    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1575        let was_dirty = self.is_dirty();
1576        let old_version = self.version.clone();
1577
1578        let ops = self.text.randomly_undo_redo(rng);
1579        if !ops.is_empty() {
1580            for op in ops {
1581                self.send_operation(Operation::Buffer(op), cx);
1582                self.did_edit(&old_version, was_dirty, cx);
1583            }
1584        }
1585    }
1586}
1587
1588impl Entity for Buffer {
1589    type Event = Event;
1590}
1591
1592impl Deref for Buffer {
1593    type Target = TextBuffer;
1594
1595    fn deref(&self) -> &Self::Target {
1596        &self.text
1597    }
1598}
1599
1600impl BufferSnapshot {
1601    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
1602        indent_size_for_line(&self, row)
1603    }
1604
1605    pub fn single_indent_size(&self, cx: &AppContext) -> IndentSize {
1606        let language_name = self.language().map(|language| language.name());
1607        let settings = cx.global::<Settings>();
1608        if settings.hard_tabs(language_name.as_deref()) {
1609            IndentSize::tab()
1610        } else {
1611            IndentSize::spaces(settings.tab_size(language_name.as_deref()).get())
1612        }
1613    }
1614
1615    pub fn suggested_indents(
1616        &self,
1617        rows: impl Iterator<Item = u32>,
1618        single_indent_size: IndentSize,
1619    ) -> BTreeMap<u32, IndentSize> {
1620        let mut result = BTreeMap::new();
1621
1622        for row_range in contiguous_ranges(rows, 10) {
1623            let suggestions = match self.suggest_autoindents(row_range.clone()) {
1624                Some(suggestions) => suggestions,
1625                _ => break,
1626            };
1627
1628            for (row, suggestion) in row_range.zip(suggestions) {
1629                let indent_size = if let Some(suggestion) = suggestion {
1630                    result
1631                        .get(&suggestion.basis_row)
1632                        .copied()
1633                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
1634                        .with_delta(suggestion.delta, single_indent_size)
1635                } else {
1636                    self.indent_size_for_line(row)
1637                };
1638
1639                result.insert(row, indent_size);
1640            }
1641        }
1642
1643        result
1644    }
1645
1646    fn suggest_autoindents<'a>(
1647        &'a self,
1648        row_range: Range<u32>,
1649    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + 'a> {
1650        let language = self.language.as_ref()?;
1651        let grammar = language.grammar.as_ref()?;
1652        let config = &language.config;
1653        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1654
1655        // Find the suggested indentation ranges based on the syntax tree.
1656        let indents_query = grammar.indents_query.as_ref()?;
1657        let mut query_cursor = QueryCursorHandle::new();
1658        let indent_capture_ix = indents_query.capture_index_for_name("indent");
1659        let end_capture_ix = indents_query.capture_index_for_name("end");
1660        query_cursor.set_point_range(
1661            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1662                ..Point::new(row_range.end, 0).to_ts_point(),
1663        );
1664
1665        let mut indent_ranges = Vec::<Range<Point>>::new();
1666        for mat in query_cursor.matches(
1667            indents_query,
1668            self.tree.as_ref()?.root_node(),
1669            TextProvider(self.as_rope()),
1670        ) {
1671            let mut start: Option<Point> = None;
1672            let mut end: Option<Point> = None;
1673            for capture in mat.captures {
1674                if Some(capture.index) == indent_capture_ix {
1675                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1676                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1677                } else if Some(capture.index) == end_capture_ix {
1678                    end = Some(Point::from_ts_point(capture.node.start_position().into()));
1679                }
1680            }
1681
1682            if let Some((start, end)) = start.zip(end) {
1683                if start.row == end.row {
1684                    continue;
1685                }
1686
1687                let range = start..end;
1688                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
1689                    Err(ix) => indent_ranges.insert(ix, range),
1690                    Ok(ix) => {
1691                        let prev_range = &mut indent_ranges[ix];
1692                        prev_range.end = prev_range.end.max(range.end);
1693                    }
1694                }
1695            }
1696        }
1697
1698        // Find the suggested indentation increases and decreased based on regexes.
1699        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
1700        self.for_each_line(
1701            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
1702                ..Point::new(row_range.end, 0),
1703            |row, line| {
1704                if config
1705                    .decrease_indent_pattern
1706                    .as_ref()
1707                    .map_or(false, |regex| regex.is_match(line))
1708                {
1709                    indent_change_rows.push((row, Ordering::Less));
1710                }
1711                if config
1712                    .increase_indent_pattern
1713                    .as_ref()
1714                    .map_or(false, |regex| regex.is_match(line))
1715                {
1716                    indent_change_rows.push((row + 1, Ordering::Greater));
1717                }
1718            },
1719        );
1720
1721        let mut indent_changes = indent_change_rows.into_iter().peekable();
1722        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
1723            prev_non_blank_row.unwrap_or(0)
1724        } else {
1725            row_range.start.saturating_sub(1)
1726        };
1727        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
1728        Some(row_range.map(move |row| {
1729            let row_start = Point::new(row, self.indent_size_for_line(row).len);
1730
1731            let mut indent_from_prev_row = false;
1732            let mut outdent_from_prev_row = false;
1733            let mut outdent_to_row = u32::MAX;
1734
1735            while let Some((indent_row, delta)) = indent_changes.peek() {
1736                if *indent_row == row {
1737                    match delta {
1738                        Ordering::Less => outdent_from_prev_row = true,
1739                        Ordering::Greater => indent_from_prev_row = true,
1740                        _ => {}
1741                    }
1742                } else if *indent_row > row {
1743                    break;
1744                }
1745                indent_changes.next();
1746            }
1747
1748            for range in &indent_ranges {
1749                if range.start.row >= row {
1750                    break;
1751                }
1752                if range.start.row == prev_row && range.end > row_start {
1753                    indent_from_prev_row = true;
1754                }
1755                if range.end > prev_row_start && range.end <= row_start {
1756                    outdent_to_row = outdent_to_row.min(range.start.row);
1757                }
1758            }
1759
1760            let suggestion = if outdent_to_row == prev_row
1761                || (outdent_from_prev_row && indent_from_prev_row)
1762            {
1763                Some(IndentSuggestion {
1764                    basis_row: prev_row,
1765                    delta: Ordering::Equal,
1766                })
1767            } else if indent_from_prev_row {
1768                Some(IndentSuggestion {
1769                    basis_row: prev_row,
1770                    delta: Ordering::Greater,
1771                })
1772            } else if outdent_to_row < prev_row {
1773                Some(IndentSuggestion {
1774                    basis_row: outdent_to_row,
1775                    delta: Ordering::Equal,
1776                })
1777            } else if outdent_from_prev_row {
1778                Some(IndentSuggestion {
1779                    basis_row: prev_row,
1780                    delta: Ordering::Less,
1781                })
1782            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
1783            {
1784                Some(IndentSuggestion {
1785                    basis_row: prev_row,
1786                    delta: Ordering::Equal,
1787                })
1788            } else {
1789                None
1790            };
1791
1792            prev_row = row;
1793            prev_row_start = row_start;
1794            suggestion
1795        }))
1796    }
1797
1798    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1799        while row > 0 {
1800            row -= 1;
1801            if !self.is_line_blank(row) {
1802                return Some(row);
1803            }
1804        }
1805        None
1806    }
1807
1808    pub fn chunks<'a, T: ToOffset>(
1809        &'a self,
1810        range: Range<T>,
1811        language_aware: bool,
1812    ) -> BufferChunks<'a> {
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<'a>(&'a 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                    while let Some(mut chunk) = chunks.next() {
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    pub fn remote_selections_in_range<'a>(
2124        &'a self,
2125        range: Range<Anchor>,
2126    ) -> impl 'a
2127           + Iterator<
2128        Item = (
2129            ReplicaId,
2130            bool,
2131            impl 'a + Iterator<Item = &'a 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
2169            .range(search_range.clone(), self, true, reversed)
2170    }
2171
2172    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2173        let mut groups = Vec::new();
2174        self.diagnostics.groups(&mut groups, self);
2175        groups
2176    }
2177
2178    pub fn diagnostic_group<'a, O>(
2179        &'a self,
2180        group_id: usize,
2181    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2182    where
2183        O: 'a + FromAnchor,
2184    {
2185        self.diagnostics.group(group_id, self)
2186    }
2187
2188    pub fn diagnostics_update_count(&self) -> usize {
2189        self.diagnostics_update_count
2190    }
2191
2192    pub fn parse_count(&self) -> usize {
2193        self.parse_count
2194    }
2195
2196    pub fn selections_update_count(&self) -> usize {
2197        self.selections_update_count
2198    }
2199
2200    pub fn file(&self) -> Option<&dyn File> {
2201        self.file.as_deref()
2202    }
2203
2204    pub fn file_update_count(&self) -> usize {
2205        self.file_update_count
2206    }
2207}
2208
2209pub fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
2210    indent_size_for_text(text.chars_at(Point::new(row, 0)))
2211}
2212
2213pub fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
2214    let mut result = IndentSize::spaces(0);
2215    for c in text {
2216        let kind = match c {
2217            ' ' => IndentKind::Space,
2218            '\t' => IndentKind::Tab,
2219            _ => break,
2220        };
2221        if result.len == 0 {
2222            result.kind = kind;
2223        }
2224        result.len += 1;
2225    }
2226    result
2227}
2228
2229impl Clone for BufferSnapshot {
2230    fn clone(&self) -> Self {
2231        Self {
2232            text: self.text.clone(),
2233            tree: self.tree.clone(),
2234            file: self.file.clone(),
2235            remote_selections: self.remote_selections.clone(),
2236            diagnostics: self.diagnostics.clone(),
2237            selections_update_count: self.selections_update_count,
2238            diagnostics_update_count: self.diagnostics_update_count,
2239            file_update_count: self.file_update_count,
2240            language: self.language.clone(),
2241            parse_count: self.parse_count,
2242        }
2243    }
2244}
2245
2246impl Deref for BufferSnapshot {
2247    type Target = text::BufferSnapshot;
2248
2249    fn deref(&self) -> &Self::Target {
2250        &self.text
2251    }
2252}
2253
2254impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
2255    type I = ByteChunks<'a>;
2256
2257    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
2258        ByteChunks(self.0.chunks_in_range(node.byte_range()))
2259    }
2260}
2261
2262pub(crate) struct ByteChunks<'a>(rope::Chunks<'a>);
2263
2264impl<'a> Iterator for ByteChunks<'a> {
2265    type Item = &'a [u8];
2266
2267    fn next(&mut self) -> Option<Self::Item> {
2268        self.0.next().map(str::as_bytes)
2269    }
2270}
2271
2272unsafe impl<'a> Send for BufferChunks<'a> {}
2273
2274impl<'a> BufferChunks<'a> {
2275    pub(crate) fn new(
2276        text: &'a Rope,
2277        range: Range<usize>,
2278        tree: Option<&'a Tree>,
2279        grammar: Option<&'a Arc<Grammar>>,
2280        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
2281    ) -> Self {
2282        let mut highlights = None;
2283        if let Some((grammar, tree)) = grammar.zip(tree) {
2284            if let Some(highlights_query) = grammar.highlights_query.as_ref() {
2285                let mut query_cursor = QueryCursorHandle::new();
2286
2287                // TODO - add a Tree-sitter API to remove the need for this.
2288                let cursor = unsafe {
2289                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
2290                };
2291                let captures = cursor.set_byte_range(range.clone()).captures(
2292                    highlights_query,
2293                    tree.root_node(),
2294                    TextProvider(text),
2295                );
2296                highlights = Some(BufferChunkHighlights {
2297                    captures,
2298                    next_capture: None,
2299                    stack: Default::default(),
2300                    highlight_map: grammar.highlight_map(),
2301                    _query_cursor: query_cursor,
2302                })
2303            }
2304        }
2305
2306        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2307        let chunks = text.chunks_in_range(range.clone());
2308
2309        BufferChunks {
2310            range,
2311            chunks,
2312            diagnostic_endpoints,
2313            error_depth: 0,
2314            warning_depth: 0,
2315            information_depth: 0,
2316            hint_depth: 0,
2317            unnecessary_depth: 0,
2318            highlights,
2319        }
2320    }
2321
2322    pub fn seek(&mut self, offset: usize) {
2323        self.range.start = offset;
2324        self.chunks.seek(self.range.start);
2325        if let Some(highlights) = self.highlights.as_mut() {
2326            highlights
2327                .stack
2328                .retain(|(end_offset, _)| *end_offset > offset);
2329            if let Some((mat, capture_ix)) = &highlights.next_capture {
2330                let capture = mat.captures[*capture_ix as usize];
2331                if offset >= capture.node.start_byte() {
2332                    let next_capture_end = capture.node.end_byte();
2333                    if offset < next_capture_end {
2334                        highlights.stack.push((
2335                            next_capture_end,
2336                            highlights.highlight_map.get(capture.index),
2337                        ));
2338                    }
2339                    highlights.next_capture.take();
2340                }
2341            }
2342            highlights.captures.set_byte_range(self.range.clone());
2343        }
2344    }
2345
2346    pub fn offset(&self) -> usize {
2347        self.range.start
2348    }
2349
2350    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2351        let depth = match endpoint.severity {
2352            DiagnosticSeverity::ERROR => &mut self.error_depth,
2353            DiagnosticSeverity::WARNING => &mut self.warning_depth,
2354            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2355            DiagnosticSeverity::HINT => &mut self.hint_depth,
2356            _ => return,
2357        };
2358        if endpoint.is_start {
2359            *depth += 1;
2360        } else {
2361            *depth -= 1;
2362        }
2363
2364        if endpoint.is_unnecessary {
2365            if endpoint.is_start {
2366                self.unnecessary_depth += 1;
2367            } else {
2368                self.unnecessary_depth -= 1;
2369            }
2370        }
2371    }
2372
2373    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
2374        if self.error_depth > 0 {
2375            Some(DiagnosticSeverity::ERROR)
2376        } else if self.warning_depth > 0 {
2377            Some(DiagnosticSeverity::WARNING)
2378        } else if self.information_depth > 0 {
2379            Some(DiagnosticSeverity::INFORMATION)
2380        } else if self.hint_depth > 0 {
2381            Some(DiagnosticSeverity::HINT)
2382        } else {
2383            None
2384        }
2385    }
2386
2387    fn current_code_is_unnecessary(&self) -> bool {
2388        self.unnecessary_depth > 0
2389    }
2390}
2391
2392impl<'a> Iterator for BufferChunks<'a> {
2393    type Item = Chunk<'a>;
2394
2395    fn next(&mut self) -> Option<Self::Item> {
2396        let mut next_capture_start = usize::MAX;
2397        let mut next_diagnostic_endpoint = usize::MAX;
2398
2399        if let Some(highlights) = self.highlights.as_mut() {
2400            while let Some((parent_capture_end, _)) = highlights.stack.last() {
2401                if *parent_capture_end <= self.range.start {
2402                    highlights.stack.pop();
2403                } else {
2404                    break;
2405                }
2406            }
2407
2408            if highlights.next_capture.is_none() {
2409                highlights.next_capture = highlights.captures.next();
2410            }
2411
2412            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2413                let capture = mat.captures[*capture_ix as usize];
2414                if self.range.start < capture.node.start_byte() {
2415                    next_capture_start = capture.node.start_byte();
2416                    break;
2417                } else {
2418                    let highlight_id = highlights.highlight_map.get(capture.index);
2419                    highlights
2420                        .stack
2421                        .push((capture.node.end_byte(), highlight_id));
2422                    highlights.next_capture = highlights.captures.next();
2423                }
2424            }
2425        }
2426
2427        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2428            if endpoint.offset <= self.range.start {
2429                self.update_diagnostic_depths(endpoint);
2430                self.diagnostic_endpoints.next();
2431            } else {
2432                next_diagnostic_endpoint = endpoint.offset;
2433                break;
2434            }
2435        }
2436
2437        if let Some(chunk) = self.chunks.peek() {
2438            let chunk_start = self.range.start;
2439            let mut chunk_end = (self.chunks.offset() + chunk.len())
2440                .min(next_capture_start)
2441                .min(next_diagnostic_endpoint);
2442            let mut highlight_id = None;
2443            if let Some(highlights) = self.highlights.as_ref() {
2444                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2445                    chunk_end = chunk_end.min(*parent_capture_end);
2446                    highlight_id = Some(*parent_highlight_id);
2447                }
2448            }
2449
2450            let slice =
2451                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2452            self.range.start = chunk_end;
2453            if self.range.start == self.chunks.offset() + chunk.len() {
2454                self.chunks.next().unwrap();
2455            }
2456
2457            Some(Chunk {
2458                text: slice,
2459                syntax_highlight_id: highlight_id,
2460                highlight_style: None,
2461                diagnostic_severity: self.current_diagnostic_severity(),
2462                is_unnecessary: self.current_code_is_unnecessary(),
2463            })
2464        } else {
2465            None
2466        }
2467    }
2468}
2469
2470impl QueryCursorHandle {
2471    pub(crate) fn new() -> Self {
2472        let mut cursor = QUERY_CURSORS
2473            .lock()
2474            .pop()
2475            .unwrap_or_else(|| QueryCursor::new());
2476        cursor.set_match_limit(64);
2477        QueryCursorHandle(Some(cursor))
2478    }
2479}
2480
2481impl Deref for QueryCursorHandle {
2482    type Target = QueryCursor;
2483
2484    fn deref(&self) -> &Self::Target {
2485        self.0.as_ref().unwrap()
2486    }
2487}
2488
2489impl DerefMut for QueryCursorHandle {
2490    fn deref_mut(&mut self) -> &mut Self::Target {
2491        self.0.as_mut().unwrap()
2492    }
2493}
2494
2495impl Drop for QueryCursorHandle {
2496    fn drop(&mut self) {
2497        let mut cursor = self.0.take().unwrap();
2498        cursor.set_byte_range(0..usize::MAX);
2499        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2500        QUERY_CURSORS.lock().push(cursor)
2501    }
2502}
2503
2504trait ToTreeSitterPoint {
2505    fn to_ts_point(self) -> tree_sitter::Point;
2506    fn from_ts_point(point: tree_sitter::Point) -> Self;
2507}
2508
2509impl ToTreeSitterPoint for Point {
2510    fn to_ts_point(self) -> tree_sitter::Point {
2511        tree_sitter::Point::new(self.row as usize, self.column as usize)
2512    }
2513
2514    fn from_ts_point(point: tree_sitter::Point) -> Self {
2515        Point::new(point.row as u32, point.column as u32)
2516    }
2517}
2518
2519impl operation_queue::Operation for Operation {
2520    fn lamport_timestamp(&self) -> clock::Lamport {
2521        match self {
2522            Operation::Buffer(_) => {
2523                unreachable!("buffer operations should never be deferred at this layer")
2524            }
2525            Operation::UpdateDiagnostics {
2526                lamport_timestamp, ..
2527            }
2528            | Operation::UpdateSelections {
2529                lamport_timestamp, ..
2530            }
2531            | Operation::UpdateCompletionTriggers {
2532                lamport_timestamp, ..
2533            } => *lamport_timestamp,
2534        }
2535    }
2536}
2537
2538impl Default for Diagnostic {
2539    fn default() -> Self {
2540        Self {
2541            code: None,
2542            severity: DiagnosticSeverity::ERROR,
2543            message: Default::default(),
2544            group_id: 0,
2545            is_primary: false,
2546            is_valid: true,
2547            is_disk_based: false,
2548            is_unnecessary: false,
2549        }
2550    }
2551}
2552
2553impl IndentSize {
2554    pub fn spaces(len: u32) -> Self {
2555        Self {
2556            len,
2557            kind: IndentKind::Space,
2558        }
2559    }
2560
2561    pub fn tab() -> Self {
2562        Self {
2563            len: 1,
2564            kind: IndentKind::Tab,
2565        }
2566    }
2567
2568    pub fn chars(&self) -> impl Iterator<Item = char> {
2569        iter::repeat(self.char()).take(self.len as usize)
2570    }
2571
2572    pub fn char(&self) -> char {
2573        match self.kind {
2574            IndentKind::Space => ' ',
2575            IndentKind::Tab => '\t',
2576        }
2577    }
2578
2579    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
2580        match direction {
2581            Ordering::Less => {
2582                if self.kind == size.kind && self.len >= size.len {
2583                    self.len -= size.len;
2584                }
2585            }
2586            Ordering::Equal => {}
2587            Ordering::Greater => {
2588                if self.len == 0 {
2589                    self = size;
2590                } else if self.kind == size.kind {
2591                    self.len += size.len;
2592                }
2593            }
2594        }
2595        self
2596    }
2597}
2598
2599impl Completion {
2600    pub fn sort_key(&self) -> (usize, &str) {
2601        let kind_key = match self.lsp_completion.kind {
2602            Some(lsp::CompletionItemKind::VARIABLE) => 0,
2603            _ => 1,
2604        };
2605        (kind_key, &self.label.text[self.label.filter_range.clone()])
2606    }
2607
2608    pub fn is_snippet(&self) -> bool {
2609        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
2610    }
2611}
2612
2613pub fn contiguous_ranges(
2614    values: impl Iterator<Item = u32>,
2615    max_len: usize,
2616) -> impl Iterator<Item = Range<u32>> {
2617    let mut values = values.into_iter();
2618    let mut current_range: Option<Range<u32>> = None;
2619    std::iter::from_fn(move || loop {
2620        if let Some(value) = values.next() {
2621            if let Some(range) = &mut current_range {
2622                if value == range.end && range.len() < max_len {
2623                    range.end += 1;
2624                    continue;
2625                }
2626            }
2627
2628            let prev_range = current_range.clone();
2629            current_range = Some(value..(value + 1));
2630            if prev_range.is_some() {
2631                return prev_range;
2632            }
2633        } else {
2634            return current_range.take();
2635        }
2636    })
2637}
2638
2639pub fn char_kind(c: char) -> CharKind {
2640    if c.is_whitespace() {
2641        CharKind::Whitespace
2642    } else if c.is_alphanumeric() || c == '_' {
2643        CharKind::Word
2644    } else {
2645        CharKind::Punctuation
2646    }
2647}