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        self.start_transaction();
 961        for (row, indent_size) in &indent_sizes {
 962            self.set_indent_size_for_line(*row, *indent_size, cx);
 963        }
 964        self.end_transaction(cx);
 965    }
 966
 967    fn set_indent_size_for_line(
 968        &mut self,
 969        row: u32,
 970        size: IndentSize,
 971        cx: &mut ModelContext<Self>,
 972    ) {
 973        let current_size = indent_size_for_line(&self, row);
 974        if size.kind != current_size.kind && current_size.len > 0 {
 975            return;
 976        }
 977
 978        if size.len > current_size.len {
 979            let offset = Point::new(row, 0).to_offset(&*self);
 980            self.edit(
 981                [(
 982                    offset..offset,
 983                    iter::repeat(size.char())
 984                        .take((size.len - current_size.len) as usize)
 985                        .collect::<String>(),
 986                )],
 987                None,
 988                cx,
 989            );
 990        } else if size.len < current_size.len {
 991            self.edit(
 992                [(
 993                    Point::new(row, 0)..Point::new(row, current_size.len - size.len),
 994                    "",
 995                )],
 996                None,
 997                cx,
 998            );
 999        }
1000    }
1001
1002    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
1003        let old_text = self.as_rope().clone();
1004        let base_version = self.version();
1005        cx.background().spawn(async move {
1006            let old_text = old_text.to_string();
1007            let line_ending = LineEnding::detect(&new_text);
1008            LineEnding::normalize(&mut new_text);
1009            let changes = TextDiff::from_chars(old_text.as_str(), new_text.as_str())
1010                .iter_all_changes()
1011                .map(|c| (c.tag(), c.value().len()))
1012                .collect::<Vec<_>>();
1013            Diff {
1014                base_version,
1015                new_text: new_text.into(),
1016                changes,
1017                line_ending,
1018                start_offset: 0,
1019            }
1020        })
1021    }
1022
1023    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<&Transaction> {
1024        if self.version == diff.base_version {
1025            self.finalize_last_transaction();
1026            self.start_transaction();
1027            self.text.set_line_ending(diff.line_ending);
1028            let mut offset = diff.start_offset;
1029            for (tag, len) in diff.changes {
1030                let range = offset..(offset + len);
1031                match tag {
1032                    ChangeTag::Equal => offset += len,
1033                    ChangeTag::Delete => {
1034                        self.edit([(range, "")], None, cx);
1035                    }
1036                    ChangeTag::Insert => {
1037                        self.edit(
1038                            [(
1039                                offset..offset,
1040                                &diff.new_text[range.start - diff.start_offset
1041                                    ..range.end - diff.start_offset],
1042                            )],
1043                            None,
1044                            cx,
1045                        );
1046                        offset += len;
1047                    }
1048                }
1049            }
1050            if self.end_transaction(cx).is_some() {
1051                self.finalize_last_transaction()
1052            } else {
1053                None
1054            }
1055        } else {
1056            None
1057        }
1058    }
1059
1060    pub fn is_dirty(&self) -> bool {
1061        self.saved_version_fingerprint != self.as_rope().fingerprint()
1062            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1063    }
1064
1065    pub fn has_conflict(&self) -> bool {
1066        self.saved_version_fingerprint != self.as_rope().fingerprint()
1067            && self
1068                .file
1069                .as_ref()
1070                .map_or(false, |file| file.mtime() > self.saved_mtime)
1071    }
1072
1073    pub fn subscribe(&mut self) -> Subscription {
1074        self.text.subscribe()
1075    }
1076
1077    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1078        self.start_transaction_at(Instant::now())
1079    }
1080
1081    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1082        self.transaction_depth += 1;
1083        if self.was_dirty_before_starting_transaction.is_none() {
1084            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1085        }
1086        self.text.start_transaction_at(now)
1087    }
1088
1089    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1090        self.end_transaction_at(Instant::now(), cx)
1091    }
1092
1093    pub fn end_transaction_at(
1094        &mut self,
1095        now: Instant,
1096        cx: &mut ModelContext<Self>,
1097    ) -> Option<TransactionId> {
1098        assert!(self.transaction_depth > 0);
1099        self.transaction_depth -= 1;
1100        let was_dirty = if self.transaction_depth == 0 {
1101            self.was_dirty_before_starting_transaction.take().unwrap()
1102        } else {
1103            false
1104        };
1105        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1106            self.did_edit(&start_version, was_dirty, cx);
1107            Some(transaction_id)
1108        } else {
1109            None
1110        }
1111    }
1112
1113    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1114        self.text.push_transaction(transaction, now);
1115    }
1116
1117    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1118        self.text.finalize_last_transaction()
1119    }
1120
1121    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1122        self.text.group_until_transaction(transaction_id);
1123    }
1124
1125    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1126        self.text.forget_transaction(transaction_id);
1127    }
1128
1129    pub fn wait_for_edits(
1130        &mut self,
1131        edit_ids: impl IntoIterator<Item = clock::Local>,
1132    ) -> impl Future<Output = ()> {
1133        self.text.wait_for_edits(edit_ids)
1134    }
1135
1136    pub fn wait_for_anchors<'a>(
1137        &mut self,
1138        anchors: impl IntoIterator<Item = &'a Anchor>,
1139    ) -> impl Future<Output = ()> {
1140        self.text.wait_for_anchors(anchors)
1141    }
1142
1143    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1144        self.text.wait_for_version(version)
1145    }
1146
1147    pub fn set_active_selections(
1148        &mut self,
1149        selections: Arc<[Selection<Anchor>]>,
1150        line_mode: bool,
1151        cx: &mut ModelContext<Self>,
1152    ) {
1153        let lamport_timestamp = self.text.lamport_clock.tick();
1154        self.remote_selections.insert(
1155            self.text.replica_id(),
1156            SelectionSet {
1157                selections: selections.clone(),
1158                lamport_timestamp,
1159                line_mode,
1160            },
1161        );
1162        self.send_operation(
1163            Operation::UpdateSelections {
1164                selections,
1165                line_mode,
1166                lamport_timestamp,
1167            },
1168            cx,
1169        );
1170    }
1171
1172    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1173        self.set_active_selections(Arc::from([]), false, cx);
1174    }
1175
1176    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Local>
1177    where
1178        T: Into<Arc<str>>,
1179    {
1180        self.edit([(0..self.len(), text)], None, cx)
1181    }
1182
1183    pub fn edit<I, S, T>(
1184        &mut self,
1185        edits_iter: I,
1186        autoindent_mode: Option<AutoindentMode>,
1187        cx: &mut ModelContext<Self>,
1188    ) -> Option<clock::Local>
1189    where
1190        I: IntoIterator<Item = (Range<S>, T)>,
1191        S: ToOffset,
1192        T: Into<Arc<str>>,
1193    {
1194        // Skip invalid edits and coalesce contiguous ones.
1195        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1196        for (range, new_text) in edits_iter {
1197            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1198            if range.start > range.end {
1199                mem::swap(&mut range.start, &mut range.end);
1200            }
1201            let new_text = new_text.into();
1202            if !new_text.is_empty() || !range.is_empty() {
1203                if let Some((prev_range, prev_text)) = edits.last_mut() {
1204                    if prev_range.end >= range.start {
1205                        prev_range.end = cmp::max(prev_range.end, range.end);
1206                        *prev_text = format!("{prev_text}{new_text}").into();
1207                    } else {
1208                        edits.push((range, new_text));
1209                    }
1210                } else {
1211                    edits.push((range, new_text));
1212                }
1213            }
1214        }
1215        if edits.is_empty() {
1216            return None;
1217        }
1218
1219        self.start_transaction();
1220        self.pending_autoindent.take();
1221        let autoindent_request = autoindent_mode
1222            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1223
1224        let edit_operation = self.text.edit(edits.iter().cloned());
1225        let edit_id = edit_operation.local_timestamp();
1226
1227        if let Some((before_edit, mode)) = autoindent_request {
1228            let language_name = self.language().map(|language| language.name());
1229            let settings = cx.global::<Settings>();
1230            let indent_size = if settings.hard_tabs(language_name.as_deref()) {
1231                IndentSize::tab()
1232            } else {
1233                IndentSize::spaces(settings.tab_size(language_name.as_deref()).get())
1234            };
1235            let (start_columns, is_block_mode) = match mode {
1236                AutoindentMode::Block {
1237                    original_indent_columns: start_columns,
1238                } => (start_columns, true),
1239                AutoindentMode::EachLine => (Default::default(), false),
1240            };
1241
1242            let mut delta = 0isize;
1243            let entries = edits
1244                .into_iter()
1245                .enumerate()
1246                .zip(&edit_operation.as_edit().unwrap().new_text)
1247                .map(|((ix, (range, _)), new_text)| {
1248                    let new_text_len = new_text.len();
1249                    let old_start = range.start.to_point(&before_edit);
1250                    let new_start = (delta + range.start as isize) as usize;
1251                    delta += new_text_len as isize - (range.end as isize - range.start as isize);
1252
1253                    let mut range_of_insertion_to_indent = 0..new_text_len;
1254                    let mut first_line_is_new = false;
1255                    let mut start_column = None;
1256
1257                    // When inserting an entire line at the beginning of an existing line,
1258                    // treat the insertion as new.
1259                    if new_text.contains('\n')
1260                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1261                    {
1262                        first_line_is_new = true;
1263                    }
1264
1265                    // When inserting text starting with a newline, avoid auto-indenting the
1266                    // previous line.
1267                    if new_text[range_of_insertion_to_indent.clone()].starts_with('\n') {
1268                        range_of_insertion_to_indent.start += 1;
1269                        first_line_is_new = true;
1270                    }
1271
1272                    // Avoid auto-indenting before the insertion.
1273                    if is_block_mode {
1274                        start_column = start_columns.get(ix).copied();
1275                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1276                            range_of_insertion_to_indent.end -= 1;
1277                        }
1278                    }
1279
1280                    AutoindentRequestEntry {
1281                        first_line_is_new,
1282                        original_indent_column: start_column,
1283                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1284                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1285                    }
1286                })
1287                .collect();
1288
1289            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1290                before_edit,
1291                entries,
1292                indent_size,
1293                is_block_mode,
1294            }));
1295        }
1296
1297        self.end_transaction(cx);
1298        self.send_operation(Operation::Buffer(edit_operation), cx);
1299        Some(edit_id)
1300    }
1301
1302    fn did_edit(
1303        &mut self,
1304        old_version: &clock::Global,
1305        was_dirty: bool,
1306        cx: &mut ModelContext<Self>,
1307    ) {
1308        if self.edits_since::<usize>(old_version).next().is_none() {
1309            return;
1310        }
1311
1312        self.reparse(cx);
1313
1314        cx.emit(Event::Edited);
1315        if was_dirty != self.is_dirty() {
1316            cx.emit(Event::DirtyChanged);
1317        }
1318        cx.notify();
1319    }
1320
1321    fn grammar(&self) -> Option<&Arc<Grammar>> {
1322        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1323    }
1324
1325    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1326        &mut self,
1327        ops: I,
1328        cx: &mut ModelContext<Self>,
1329    ) -> Result<()> {
1330        self.pending_autoindent.take();
1331        let was_dirty = self.is_dirty();
1332        let old_version = self.version.clone();
1333        let mut deferred_ops = Vec::new();
1334        let buffer_ops = ops
1335            .into_iter()
1336            .filter_map(|op| match op {
1337                Operation::Buffer(op) => Some(op),
1338                _ => {
1339                    if self.can_apply_op(&op) {
1340                        self.apply_op(op, cx);
1341                    } else {
1342                        deferred_ops.push(op);
1343                    }
1344                    None
1345                }
1346            })
1347            .collect::<Vec<_>>();
1348        self.text.apply_ops(buffer_ops)?;
1349        self.deferred_ops.insert(deferred_ops);
1350        self.flush_deferred_ops(cx);
1351        self.did_edit(&old_version, was_dirty, cx);
1352        // Notify independently of whether the buffer was edited as the operations could include a
1353        // selection update.
1354        cx.notify();
1355        Ok(())
1356    }
1357
1358    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1359        let mut deferred_ops = Vec::new();
1360        for op in self.deferred_ops.drain().iter().cloned() {
1361            if self.can_apply_op(&op) {
1362                self.apply_op(op, cx);
1363            } else {
1364                deferred_ops.push(op);
1365            }
1366        }
1367        self.deferred_ops.insert(deferred_ops);
1368    }
1369
1370    fn can_apply_op(&self, operation: &Operation) -> bool {
1371        match operation {
1372            Operation::Buffer(_) => {
1373                unreachable!("buffer operations should never be applied at this layer")
1374            }
1375            Operation::UpdateDiagnostics {
1376                diagnostics: diagnostic_set,
1377                ..
1378            } => diagnostic_set.iter().all(|diagnostic| {
1379                self.text.can_resolve(&diagnostic.range.start)
1380                    && self.text.can_resolve(&diagnostic.range.end)
1381            }),
1382            Operation::UpdateSelections { selections, .. } => selections
1383                .iter()
1384                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1385            Operation::UpdateCompletionTriggers { .. } => true,
1386        }
1387    }
1388
1389    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1390        match operation {
1391            Operation::Buffer(_) => {
1392                unreachable!("buffer operations should never be applied at this layer")
1393            }
1394            Operation::UpdateDiagnostics {
1395                diagnostics: diagnostic_set,
1396                lamport_timestamp,
1397            } => {
1398                let snapshot = self.snapshot();
1399                self.apply_diagnostic_update(
1400                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1401                    lamport_timestamp,
1402                    cx,
1403                );
1404            }
1405            Operation::UpdateSelections {
1406                selections,
1407                lamport_timestamp,
1408                line_mode,
1409            } => {
1410                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1411                    if set.lamport_timestamp > lamport_timestamp {
1412                        return;
1413                    }
1414                }
1415
1416                self.remote_selections.insert(
1417                    lamport_timestamp.replica_id,
1418                    SelectionSet {
1419                        selections,
1420                        lamport_timestamp,
1421                        line_mode,
1422                    },
1423                );
1424                self.text.lamport_clock.observe(lamport_timestamp);
1425                self.selections_update_count += 1;
1426            }
1427            Operation::UpdateCompletionTriggers {
1428                triggers,
1429                lamport_timestamp,
1430            } => {
1431                self.completion_triggers = triggers;
1432                self.text.lamport_clock.observe(lamport_timestamp);
1433            }
1434        }
1435    }
1436
1437    fn apply_diagnostic_update(
1438        &mut self,
1439        diagnostics: DiagnosticSet,
1440        lamport_timestamp: clock::Lamport,
1441        cx: &mut ModelContext<Self>,
1442    ) {
1443        if lamport_timestamp > self.diagnostics_timestamp {
1444            self.diagnostics = diagnostics;
1445            self.diagnostics_timestamp = lamport_timestamp;
1446            self.diagnostics_update_count += 1;
1447            self.text.lamport_clock.observe(lamport_timestamp);
1448            cx.notify();
1449            cx.emit(Event::DiagnosticsUpdated);
1450        }
1451    }
1452
1453    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1454        cx.emit(Event::Operation(operation));
1455    }
1456
1457    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1458        self.remote_selections.remove(&replica_id);
1459        cx.notify();
1460    }
1461
1462    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1463        let was_dirty = self.is_dirty();
1464        let old_version = self.version.clone();
1465
1466        if let Some((transaction_id, operation)) = self.text.undo() {
1467            self.send_operation(Operation::Buffer(operation), cx);
1468            self.did_edit(&old_version, was_dirty, cx);
1469            Some(transaction_id)
1470        } else {
1471            None
1472        }
1473    }
1474
1475    pub fn undo_to_transaction(
1476        &mut self,
1477        transaction_id: TransactionId,
1478        cx: &mut ModelContext<Self>,
1479    ) -> bool {
1480        let was_dirty = self.is_dirty();
1481        let old_version = self.version.clone();
1482
1483        let operations = self.text.undo_to_transaction(transaction_id);
1484        let undone = !operations.is_empty();
1485        for operation in operations {
1486            self.send_operation(Operation::Buffer(operation), cx);
1487        }
1488        if undone {
1489            self.did_edit(&old_version, was_dirty, cx)
1490        }
1491        undone
1492    }
1493
1494    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1495        let was_dirty = self.is_dirty();
1496        let old_version = self.version.clone();
1497
1498        if let Some((transaction_id, operation)) = self.text.redo() {
1499            self.send_operation(Operation::Buffer(operation), cx);
1500            self.did_edit(&old_version, was_dirty, cx);
1501            Some(transaction_id)
1502        } else {
1503            None
1504        }
1505    }
1506
1507    pub fn redo_to_transaction(
1508        &mut self,
1509        transaction_id: TransactionId,
1510        cx: &mut ModelContext<Self>,
1511    ) -> bool {
1512        let was_dirty = self.is_dirty();
1513        let old_version = self.version.clone();
1514
1515        let operations = self.text.redo_to_transaction(transaction_id);
1516        let redone = !operations.is_empty();
1517        for operation in operations {
1518            self.send_operation(Operation::Buffer(operation), cx);
1519        }
1520        if redone {
1521            self.did_edit(&old_version, was_dirty, cx)
1522        }
1523        redone
1524    }
1525
1526    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
1527        self.completion_triggers = triggers.clone();
1528        let lamport_timestamp = self.text.lamport_clock.tick();
1529        self.send_operation(
1530            Operation::UpdateCompletionTriggers {
1531                triggers,
1532                lamport_timestamp,
1533            },
1534            cx,
1535        );
1536        cx.notify();
1537    }
1538
1539    pub fn completion_triggers(&self) -> &[String] {
1540        &self.completion_triggers
1541    }
1542}
1543
1544#[cfg(any(test, feature = "test-support"))]
1545impl Buffer {
1546    pub fn set_group_interval(&mut self, group_interval: Duration) {
1547        self.text.set_group_interval(group_interval);
1548    }
1549
1550    pub fn randomly_edit<T>(
1551        &mut self,
1552        rng: &mut T,
1553        old_range_count: usize,
1554        cx: &mut ModelContext<Self>,
1555    ) where
1556        T: rand::Rng,
1557    {
1558        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
1559        let mut last_end = None;
1560        for _ in 0..old_range_count {
1561            if last_end.map_or(false, |last_end| last_end >= self.len()) {
1562                break;
1563            }
1564
1565            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1566            let mut range = self.random_byte_range(new_start, rng);
1567            if rng.gen_bool(0.2) {
1568                mem::swap(&mut range.start, &mut range.end);
1569            }
1570            last_end = Some(range.end);
1571
1572            let new_text_len = rng.gen_range(0..10);
1573            let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1574                .take(new_text_len)
1575                .collect();
1576
1577            edits.push((range, new_text));
1578        }
1579        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
1580        self.edit(edits, None, cx);
1581    }
1582
1583    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1584        let was_dirty = self.is_dirty();
1585        let old_version = self.version.clone();
1586
1587        let ops = self.text.randomly_undo_redo(rng);
1588        if !ops.is_empty() {
1589            for op in ops {
1590                self.send_operation(Operation::Buffer(op), cx);
1591                self.did_edit(&old_version, was_dirty, cx);
1592            }
1593        }
1594    }
1595}
1596
1597impl Entity for Buffer {
1598    type Event = Event;
1599}
1600
1601impl Deref for Buffer {
1602    type Target = TextBuffer;
1603
1604    fn deref(&self) -> &Self::Target {
1605        &self.text
1606    }
1607}
1608
1609impl BufferSnapshot {
1610    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
1611        indent_size_for_line(&self, row)
1612    }
1613
1614    fn suggest_autoindents<'a>(
1615        &'a self,
1616        row_range: Range<u32>,
1617    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + 'a> {
1618        let language = self.language.as_ref()?;
1619        let grammar = language.grammar.as_ref()?;
1620        let config = &language.config;
1621        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1622
1623        // Find the suggested indentation ranges based on the syntax tree.
1624        let indents_query = grammar.indents_query.as_ref()?;
1625        let mut query_cursor = QueryCursorHandle::new();
1626        let indent_capture_ix = indents_query.capture_index_for_name("indent");
1627        let end_capture_ix = indents_query.capture_index_for_name("end");
1628        query_cursor.set_point_range(
1629            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1630                ..Point::new(row_range.end, 0).to_ts_point(),
1631        );
1632
1633        let mut indent_ranges = Vec::<Range<Point>>::new();
1634        for mat in query_cursor.matches(
1635            indents_query,
1636            self.tree.as_ref()?.root_node(),
1637            TextProvider(self.as_rope()),
1638        ) {
1639            let mut start: Option<Point> = None;
1640            let mut end: Option<Point> = None;
1641            for capture in mat.captures {
1642                if Some(capture.index) == indent_capture_ix {
1643                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1644                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1645                } else if Some(capture.index) == end_capture_ix {
1646                    end = Some(Point::from_ts_point(capture.node.start_position().into()));
1647                }
1648            }
1649
1650            if let Some((start, end)) = start.zip(end) {
1651                if start.row == end.row {
1652                    continue;
1653                }
1654
1655                let range = start..end;
1656                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
1657                    Err(ix) => indent_ranges.insert(ix, range),
1658                    Ok(ix) => {
1659                        let prev_range = &mut indent_ranges[ix];
1660                        prev_range.end = prev_range.end.max(range.end);
1661                    }
1662                }
1663            }
1664        }
1665
1666        // Find the suggested indentation increases and decreased based on regexes.
1667        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
1668        self.for_each_line(
1669            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
1670                ..Point::new(row_range.end, 0),
1671            |row, line| {
1672                if config
1673                    .decrease_indent_pattern
1674                    .as_ref()
1675                    .map_or(false, |regex| regex.is_match(line))
1676                {
1677                    indent_change_rows.push((row, Ordering::Less));
1678                }
1679                if config
1680                    .increase_indent_pattern
1681                    .as_ref()
1682                    .map_or(false, |regex| regex.is_match(line))
1683                {
1684                    indent_change_rows.push((row + 1, Ordering::Greater));
1685                }
1686            },
1687        );
1688
1689        let mut indent_changes = indent_change_rows.into_iter().peekable();
1690        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
1691            prev_non_blank_row.unwrap_or(0)
1692        } else {
1693            row_range.start.saturating_sub(1)
1694        };
1695        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
1696        Some(row_range.map(move |row| {
1697            let row_start = Point::new(row, self.indent_size_for_line(row).len);
1698
1699            let mut indent_from_prev_row = false;
1700            let mut outdent_from_prev_row = false;
1701            let mut outdent_to_row = u32::MAX;
1702
1703            while let Some((indent_row, delta)) = indent_changes.peek() {
1704                if *indent_row == row {
1705                    match delta {
1706                        Ordering::Less => outdent_from_prev_row = true,
1707                        Ordering::Greater => indent_from_prev_row = true,
1708                        _ => {}
1709                    }
1710                } else if *indent_row > row {
1711                    break;
1712                }
1713                indent_changes.next();
1714            }
1715
1716            for range in &indent_ranges {
1717                if range.start.row >= row {
1718                    break;
1719                }
1720                if range.start.row == prev_row && range.end > row_start {
1721                    indent_from_prev_row = true;
1722                }
1723                if range.end > prev_row_start && range.end <= row_start {
1724                    outdent_to_row = outdent_to_row.min(range.start.row);
1725                }
1726            }
1727
1728            let suggestion = if outdent_to_row == prev_row
1729                || (outdent_from_prev_row && indent_from_prev_row)
1730            {
1731                Some(IndentSuggestion {
1732                    basis_row: prev_row,
1733                    delta: Ordering::Equal,
1734                })
1735            } else if indent_from_prev_row {
1736                Some(IndentSuggestion {
1737                    basis_row: prev_row,
1738                    delta: Ordering::Greater,
1739                })
1740            } else if outdent_to_row < prev_row {
1741                Some(IndentSuggestion {
1742                    basis_row: outdent_to_row,
1743                    delta: Ordering::Equal,
1744                })
1745            } else if outdent_from_prev_row {
1746                Some(IndentSuggestion {
1747                    basis_row: prev_row,
1748                    delta: Ordering::Less,
1749                })
1750            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
1751            {
1752                Some(IndentSuggestion {
1753                    basis_row: prev_row,
1754                    delta: Ordering::Equal,
1755                })
1756            } else {
1757                None
1758            };
1759
1760            prev_row = row;
1761            prev_row_start = row_start;
1762            suggestion
1763        }))
1764    }
1765
1766    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1767        while row > 0 {
1768            row -= 1;
1769            if !self.is_line_blank(row) {
1770                return Some(row);
1771            }
1772        }
1773        None
1774    }
1775
1776    pub fn chunks<'a, T: ToOffset>(
1777        &'a self,
1778        range: Range<T>,
1779        language_aware: bool,
1780    ) -> BufferChunks<'a> {
1781        let range = range.start.to_offset(self)..range.end.to_offset(self);
1782
1783        let mut tree = None;
1784        let mut diagnostic_endpoints = Vec::new();
1785        if language_aware {
1786            tree = self.tree.as_ref();
1787            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
1788                diagnostic_endpoints.push(DiagnosticEndpoint {
1789                    offset: entry.range.start,
1790                    is_start: true,
1791                    severity: entry.diagnostic.severity,
1792                    is_unnecessary: entry.diagnostic.is_unnecessary,
1793                });
1794                diagnostic_endpoints.push(DiagnosticEndpoint {
1795                    offset: entry.range.end,
1796                    is_start: false,
1797                    severity: entry.diagnostic.severity,
1798                    is_unnecessary: entry.diagnostic.is_unnecessary,
1799                });
1800            }
1801            diagnostic_endpoints
1802                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1803        }
1804
1805        BufferChunks::new(
1806            self.text.as_rope(),
1807            range,
1808            tree,
1809            self.grammar(),
1810            diagnostic_endpoints,
1811        )
1812    }
1813
1814    pub fn for_each_line<'a>(&'a self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
1815        let mut line = String::new();
1816        let mut row = range.start.row;
1817        for chunk in self
1818            .as_rope()
1819            .chunks_in_range(range.to_offset(self))
1820            .chain(["\n"])
1821        {
1822            for (newline_ix, text) in chunk.split('\n').enumerate() {
1823                if newline_ix > 0 {
1824                    callback(row, &line);
1825                    row += 1;
1826                    line.clear();
1827                }
1828                line.push_str(text);
1829            }
1830        }
1831    }
1832
1833    pub fn language(&self) -> Option<&Arc<Language>> {
1834        self.language.as_ref()
1835    }
1836
1837    fn grammar(&self) -> Option<&Arc<Grammar>> {
1838        self.language
1839            .as_ref()
1840            .and_then(|language| language.grammar.as_ref())
1841    }
1842
1843    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1844        let mut start = start.to_offset(self);
1845        let mut end = start;
1846        let mut next_chars = self.chars_at(start).peekable();
1847        let mut prev_chars = self.reversed_chars_at(start).peekable();
1848        let word_kind = cmp::max(
1849            prev_chars.peek().copied().map(char_kind),
1850            next_chars.peek().copied().map(char_kind),
1851        );
1852
1853        for ch in prev_chars {
1854            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1855                start -= ch.len_utf8();
1856            } else {
1857                break;
1858            }
1859        }
1860
1861        for ch in next_chars {
1862            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1863                end += ch.len_utf8();
1864            } else {
1865                break;
1866            }
1867        }
1868
1869        (start..end, word_kind)
1870    }
1871
1872    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1873        let tree = self.tree.as_ref()?;
1874        let range = range.start.to_offset(self)..range.end.to_offset(self);
1875        let mut cursor = tree.root_node().walk();
1876
1877        // Descend to the first leaf that touches the start of the range,
1878        // and if the range is non-empty, extends beyond the start.
1879        while cursor.goto_first_child_for_byte(range.start).is_some() {
1880            if !range.is_empty() && cursor.node().end_byte() == range.start {
1881                cursor.goto_next_sibling();
1882            }
1883        }
1884
1885        // Ascend to the smallest ancestor that strictly contains the range.
1886        loop {
1887            let node_range = cursor.node().byte_range();
1888            if node_range.start <= range.start
1889                && node_range.end >= range.end
1890                && node_range.len() > range.len()
1891            {
1892                break;
1893            }
1894            if !cursor.goto_parent() {
1895                break;
1896            }
1897        }
1898
1899        let left_node = cursor.node();
1900
1901        // For an empty range, try to find another node immediately to the right of the range.
1902        if left_node.end_byte() == range.start {
1903            let mut right_node = None;
1904            while !cursor.goto_next_sibling() {
1905                if !cursor.goto_parent() {
1906                    break;
1907                }
1908            }
1909
1910            while cursor.node().start_byte() == range.start {
1911                right_node = Some(cursor.node());
1912                if !cursor.goto_first_child() {
1913                    break;
1914                }
1915            }
1916
1917            // If there is a candidate node on both sides of the (empty) range, then
1918            // decide between the two by favoring a named node over an anonymous token.
1919            // If both nodes are the same in that regard, favor the right one.
1920            if let Some(right_node) = right_node {
1921                if right_node.is_named() || !left_node.is_named() {
1922                    return Some(right_node.byte_range());
1923                }
1924            }
1925        }
1926
1927        Some(left_node.byte_range())
1928    }
1929
1930    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1931        self.outline_items_containing(0..self.len(), theme)
1932            .map(Outline::new)
1933    }
1934
1935    pub fn symbols_containing<T: ToOffset>(
1936        &self,
1937        position: T,
1938        theme: Option<&SyntaxTheme>,
1939    ) -> Option<Vec<OutlineItem<Anchor>>> {
1940        let position = position.to_offset(&self);
1941        let mut items =
1942            self.outline_items_containing(position.saturating_sub(1)..position + 1, theme)?;
1943        let mut prev_depth = None;
1944        items.retain(|item| {
1945            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
1946            prev_depth = Some(item.depth);
1947            result
1948        });
1949        Some(items)
1950    }
1951
1952    fn outline_items_containing(
1953        &self,
1954        range: Range<usize>,
1955        theme: Option<&SyntaxTheme>,
1956    ) -> Option<Vec<OutlineItem<Anchor>>> {
1957        let tree = self.tree.as_ref()?;
1958        let grammar = self
1959            .language
1960            .as_ref()
1961            .and_then(|language| language.grammar.as_ref())?;
1962
1963        let outline_query = grammar.outline_query.as_ref()?;
1964        let mut cursor = QueryCursorHandle::new();
1965        cursor.set_byte_range(range.clone());
1966        let matches = cursor.matches(
1967            outline_query,
1968            tree.root_node(),
1969            TextProvider(self.as_rope()),
1970        );
1971
1972        let mut chunks = self.chunks(0..self.len(), true);
1973
1974        let item_capture_ix = outline_query.capture_index_for_name("item")?;
1975        let name_capture_ix = outline_query.capture_index_for_name("name")?;
1976        let context_capture_ix = outline_query
1977            .capture_index_for_name("context")
1978            .unwrap_or(u32::MAX);
1979
1980        let mut stack = Vec::<Range<usize>>::new();
1981        let items = matches
1982            .filter_map(|mat| {
1983                let item_node = mat.nodes_for_capture_index(item_capture_ix).next()?;
1984                let item_range = item_node.start_byte()..item_node.end_byte();
1985                if item_range.end < range.start || item_range.start > range.end {
1986                    return None;
1987                }
1988                let mut text = String::new();
1989                let mut name_ranges = Vec::new();
1990                let mut highlight_ranges = Vec::new();
1991
1992                for capture in mat.captures {
1993                    let node_is_name;
1994                    if capture.index == name_capture_ix {
1995                        node_is_name = true;
1996                    } else if capture.index == context_capture_ix {
1997                        node_is_name = false;
1998                    } else {
1999                        continue;
2000                    }
2001
2002                    let range = capture.node.start_byte()..capture.node.end_byte();
2003                    if !text.is_empty() {
2004                        text.push(' ');
2005                    }
2006                    if node_is_name {
2007                        let mut start = text.len();
2008                        let end = start + range.len();
2009
2010                        // When multiple names are captured, then the matcheable text
2011                        // includes the whitespace in between the names.
2012                        if !name_ranges.is_empty() {
2013                            start -= 1;
2014                        }
2015
2016                        name_ranges.push(start..end);
2017                    }
2018
2019                    let mut offset = range.start;
2020                    chunks.seek(offset);
2021                    while let Some(mut chunk) = chunks.next() {
2022                        if chunk.text.len() > range.end - offset {
2023                            chunk.text = &chunk.text[0..(range.end - offset)];
2024                            offset = range.end;
2025                        } else {
2026                            offset += chunk.text.len();
2027                        }
2028                        let style = chunk
2029                            .syntax_highlight_id
2030                            .zip(theme)
2031                            .and_then(|(highlight, theme)| highlight.style(theme));
2032                        if let Some(style) = style {
2033                            let start = text.len();
2034                            let end = start + chunk.text.len();
2035                            highlight_ranges.push((start..end, style));
2036                        }
2037                        text.push_str(chunk.text);
2038                        if offset >= range.end {
2039                            break;
2040                        }
2041                    }
2042                }
2043
2044                while stack.last().map_or(false, |prev_range| {
2045                    prev_range.start > item_range.start || prev_range.end < item_range.end
2046                }) {
2047                    stack.pop();
2048                }
2049                stack.push(item_range.clone());
2050
2051                Some(OutlineItem {
2052                    depth: stack.len() - 1,
2053                    range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2054                    text,
2055                    highlight_ranges,
2056                    name_ranges,
2057                })
2058            })
2059            .collect::<Vec<_>>();
2060        Some(items)
2061    }
2062
2063    pub fn enclosing_bracket_ranges<T: ToOffset>(
2064        &self,
2065        range: Range<T>,
2066    ) -> Option<(Range<usize>, Range<usize>)> {
2067        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
2068        let brackets_query = grammar.brackets_query.as_ref()?;
2069        let open_capture_ix = brackets_query.capture_index_for_name("open")?;
2070        let close_capture_ix = brackets_query.capture_index_for_name("close")?;
2071
2072        // Find bracket pairs that *inclusively* contain the given range.
2073        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
2074        let mut cursor = QueryCursorHandle::new();
2075        let matches = cursor.set_byte_range(range).matches(
2076            &brackets_query,
2077            tree.root_node(),
2078            TextProvider(self.as_rope()),
2079        );
2080
2081        // Get the ranges of the innermost pair of brackets.
2082        matches
2083            .filter_map(|mat| {
2084                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
2085                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
2086                Some((open.byte_range(), close.byte_range()))
2087            })
2088            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
2089    }
2090
2091    pub fn remote_selections_in_range<'a>(
2092        &'a self,
2093        range: Range<Anchor>,
2094    ) -> impl 'a
2095           + Iterator<
2096        Item = (
2097            ReplicaId,
2098            bool,
2099            impl 'a + Iterator<Item = &'a Selection<Anchor>>,
2100        ),
2101    > {
2102        self.remote_selections
2103            .iter()
2104            .filter(|(replica_id, set)| {
2105                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2106            })
2107            .map(move |(replica_id, set)| {
2108                let start_ix = match set.selections.binary_search_by(|probe| {
2109                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
2110                }) {
2111                    Ok(ix) | Err(ix) => ix,
2112                };
2113                let end_ix = match set.selections.binary_search_by(|probe| {
2114                    probe.start.cmp(&range.end, self).then(Ordering::Less)
2115                }) {
2116                    Ok(ix) | Err(ix) => ix,
2117                };
2118
2119                (
2120                    *replica_id,
2121                    set.line_mode,
2122                    set.selections[start_ix..end_ix].iter(),
2123                )
2124            })
2125    }
2126
2127    pub fn diagnostics_in_range<'a, T, O>(
2128        &'a self,
2129        search_range: Range<T>,
2130        reversed: bool,
2131    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2132    where
2133        T: 'a + Clone + ToOffset,
2134        O: 'a + FromAnchor,
2135    {
2136        self.diagnostics
2137            .range(search_range.clone(), self, true, reversed)
2138    }
2139
2140    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2141        let mut groups = Vec::new();
2142        self.diagnostics.groups(&mut groups, self);
2143        groups
2144    }
2145
2146    pub fn diagnostic_group<'a, O>(
2147        &'a self,
2148        group_id: usize,
2149    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2150    where
2151        O: 'a + FromAnchor,
2152    {
2153        self.diagnostics.group(group_id, self)
2154    }
2155
2156    pub fn diagnostics_update_count(&self) -> usize {
2157        self.diagnostics_update_count
2158    }
2159
2160    pub fn parse_count(&self) -> usize {
2161        self.parse_count
2162    }
2163
2164    pub fn selections_update_count(&self) -> usize {
2165        self.selections_update_count
2166    }
2167
2168    pub fn file(&self) -> Option<&dyn File> {
2169        self.file.as_deref()
2170    }
2171
2172    pub fn file_update_count(&self) -> usize {
2173        self.file_update_count
2174    }
2175}
2176
2177pub fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
2178    indent_size_for_text(text.chars_at(Point::new(row, 0)))
2179}
2180
2181pub fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
2182    let mut result = IndentSize::spaces(0);
2183    for c in text {
2184        let kind = match c {
2185            ' ' => IndentKind::Space,
2186            '\t' => IndentKind::Tab,
2187            _ => break,
2188        };
2189        if result.len == 0 {
2190            result.kind = kind;
2191        }
2192        result.len += 1;
2193    }
2194    result
2195}
2196
2197impl Clone for BufferSnapshot {
2198    fn clone(&self) -> Self {
2199        Self {
2200            text: self.text.clone(),
2201            tree: self.tree.clone(),
2202            file: self.file.clone(),
2203            remote_selections: self.remote_selections.clone(),
2204            diagnostics: self.diagnostics.clone(),
2205            selections_update_count: self.selections_update_count,
2206            diagnostics_update_count: self.diagnostics_update_count,
2207            file_update_count: self.file_update_count,
2208            language: self.language.clone(),
2209            parse_count: self.parse_count,
2210        }
2211    }
2212}
2213
2214impl Deref for BufferSnapshot {
2215    type Target = text::BufferSnapshot;
2216
2217    fn deref(&self) -> &Self::Target {
2218        &self.text
2219    }
2220}
2221
2222impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
2223    type I = ByteChunks<'a>;
2224
2225    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
2226        ByteChunks(self.0.chunks_in_range(node.byte_range()))
2227    }
2228}
2229
2230pub(crate) struct ByteChunks<'a>(rope::Chunks<'a>);
2231
2232impl<'a> Iterator for ByteChunks<'a> {
2233    type Item = &'a [u8];
2234
2235    fn next(&mut self) -> Option<Self::Item> {
2236        self.0.next().map(str::as_bytes)
2237    }
2238}
2239
2240unsafe impl<'a> Send for BufferChunks<'a> {}
2241
2242impl<'a> BufferChunks<'a> {
2243    pub(crate) fn new(
2244        text: &'a Rope,
2245        range: Range<usize>,
2246        tree: Option<&'a Tree>,
2247        grammar: Option<&'a Arc<Grammar>>,
2248        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
2249    ) -> Self {
2250        let mut highlights = None;
2251        if let Some((grammar, tree)) = grammar.zip(tree) {
2252            if let Some(highlights_query) = grammar.highlights_query.as_ref() {
2253                let mut query_cursor = QueryCursorHandle::new();
2254
2255                // TODO - add a Tree-sitter API to remove the need for this.
2256                let cursor = unsafe {
2257                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
2258                };
2259                let captures = cursor.set_byte_range(range.clone()).captures(
2260                    highlights_query,
2261                    tree.root_node(),
2262                    TextProvider(text),
2263                );
2264                highlights = Some(BufferChunkHighlights {
2265                    captures,
2266                    next_capture: None,
2267                    stack: Default::default(),
2268                    highlight_map: grammar.highlight_map(),
2269                    _query_cursor: query_cursor,
2270                })
2271            }
2272        }
2273
2274        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2275        let chunks = text.chunks_in_range(range.clone());
2276
2277        BufferChunks {
2278            range,
2279            chunks,
2280            diagnostic_endpoints,
2281            error_depth: 0,
2282            warning_depth: 0,
2283            information_depth: 0,
2284            hint_depth: 0,
2285            unnecessary_depth: 0,
2286            highlights,
2287        }
2288    }
2289
2290    pub fn seek(&mut self, offset: usize) {
2291        self.range.start = offset;
2292        self.chunks.seek(self.range.start);
2293        if let Some(highlights) = self.highlights.as_mut() {
2294            highlights
2295                .stack
2296                .retain(|(end_offset, _)| *end_offset > offset);
2297            if let Some((mat, capture_ix)) = &highlights.next_capture {
2298                let capture = mat.captures[*capture_ix as usize];
2299                if offset >= capture.node.start_byte() {
2300                    let next_capture_end = capture.node.end_byte();
2301                    if offset < next_capture_end {
2302                        highlights.stack.push((
2303                            next_capture_end,
2304                            highlights.highlight_map.get(capture.index),
2305                        ));
2306                    }
2307                    highlights.next_capture.take();
2308                }
2309            }
2310            highlights.captures.set_byte_range(self.range.clone());
2311        }
2312    }
2313
2314    pub fn offset(&self) -> usize {
2315        self.range.start
2316    }
2317
2318    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2319        let depth = match endpoint.severity {
2320            DiagnosticSeverity::ERROR => &mut self.error_depth,
2321            DiagnosticSeverity::WARNING => &mut self.warning_depth,
2322            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2323            DiagnosticSeverity::HINT => &mut self.hint_depth,
2324            _ => return,
2325        };
2326        if endpoint.is_start {
2327            *depth += 1;
2328        } else {
2329            *depth -= 1;
2330        }
2331
2332        if endpoint.is_unnecessary {
2333            if endpoint.is_start {
2334                self.unnecessary_depth += 1;
2335            } else {
2336                self.unnecessary_depth -= 1;
2337            }
2338        }
2339    }
2340
2341    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
2342        if self.error_depth > 0 {
2343            Some(DiagnosticSeverity::ERROR)
2344        } else if self.warning_depth > 0 {
2345            Some(DiagnosticSeverity::WARNING)
2346        } else if self.information_depth > 0 {
2347            Some(DiagnosticSeverity::INFORMATION)
2348        } else if self.hint_depth > 0 {
2349            Some(DiagnosticSeverity::HINT)
2350        } else {
2351            None
2352        }
2353    }
2354
2355    fn current_code_is_unnecessary(&self) -> bool {
2356        self.unnecessary_depth > 0
2357    }
2358}
2359
2360impl<'a> Iterator for BufferChunks<'a> {
2361    type Item = Chunk<'a>;
2362
2363    fn next(&mut self) -> Option<Self::Item> {
2364        let mut next_capture_start = usize::MAX;
2365        let mut next_diagnostic_endpoint = usize::MAX;
2366
2367        if let Some(highlights) = self.highlights.as_mut() {
2368            while let Some((parent_capture_end, _)) = highlights.stack.last() {
2369                if *parent_capture_end <= self.range.start {
2370                    highlights.stack.pop();
2371                } else {
2372                    break;
2373                }
2374            }
2375
2376            if highlights.next_capture.is_none() {
2377                highlights.next_capture = highlights.captures.next();
2378            }
2379
2380            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2381                let capture = mat.captures[*capture_ix as usize];
2382                if self.range.start < capture.node.start_byte() {
2383                    next_capture_start = capture.node.start_byte();
2384                    break;
2385                } else {
2386                    let highlight_id = highlights.highlight_map.get(capture.index);
2387                    highlights
2388                        .stack
2389                        .push((capture.node.end_byte(), highlight_id));
2390                    highlights.next_capture = highlights.captures.next();
2391                }
2392            }
2393        }
2394
2395        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2396            if endpoint.offset <= self.range.start {
2397                self.update_diagnostic_depths(endpoint);
2398                self.diagnostic_endpoints.next();
2399            } else {
2400                next_diagnostic_endpoint = endpoint.offset;
2401                break;
2402            }
2403        }
2404
2405        if let Some(chunk) = self.chunks.peek() {
2406            let chunk_start = self.range.start;
2407            let mut chunk_end = (self.chunks.offset() + chunk.len())
2408                .min(next_capture_start)
2409                .min(next_diagnostic_endpoint);
2410            let mut highlight_id = None;
2411            if let Some(highlights) = self.highlights.as_ref() {
2412                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2413                    chunk_end = chunk_end.min(*parent_capture_end);
2414                    highlight_id = Some(*parent_highlight_id);
2415                }
2416            }
2417
2418            let slice =
2419                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2420            self.range.start = chunk_end;
2421            if self.range.start == self.chunks.offset() + chunk.len() {
2422                self.chunks.next().unwrap();
2423            }
2424
2425            Some(Chunk {
2426                text: slice,
2427                syntax_highlight_id: highlight_id,
2428                highlight_style: None,
2429                diagnostic_severity: self.current_diagnostic_severity(),
2430                is_unnecessary: self.current_code_is_unnecessary(),
2431            })
2432        } else {
2433            None
2434        }
2435    }
2436}
2437
2438impl QueryCursorHandle {
2439    pub(crate) fn new() -> Self {
2440        let mut cursor = QUERY_CURSORS
2441            .lock()
2442            .pop()
2443            .unwrap_or_else(|| QueryCursor::new());
2444        cursor.set_match_limit(64);
2445        QueryCursorHandle(Some(cursor))
2446    }
2447}
2448
2449impl Deref for QueryCursorHandle {
2450    type Target = QueryCursor;
2451
2452    fn deref(&self) -> &Self::Target {
2453        self.0.as_ref().unwrap()
2454    }
2455}
2456
2457impl DerefMut for QueryCursorHandle {
2458    fn deref_mut(&mut self) -> &mut Self::Target {
2459        self.0.as_mut().unwrap()
2460    }
2461}
2462
2463impl Drop for QueryCursorHandle {
2464    fn drop(&mut self) {
2465        let mut cursor = self.0.take().unwrap();
2466        cursor.set_byte_range(0..usize::MAX);
2467        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2468        QUERY_CURSORS.lock().push(cursor)
2469    }
2470}
2471
2472trait ToTreeSitterPoint {
2473    fn to_ts_point(self) -> tree_sitter::Point;
2474    fn from_ts_point(point: tree_sitter::Point) -> Self;
2475}
2476
2477impl ToTreeSitterPoint for Point {
2478    fn to_ts_point(self) -> tree_sitter::Point {
2479        tree_sitter::Point::new(self.row as usize, self.column as usize)
2480    }
2481
2482    fn from_ts_point(point: tree_sitter::Point) -> Self {
2483        Point::new(point.row as u32, point.column as u32)
2484    }
2485}
2486
2487impl operation_queue::Operation for Operation {
2488    fn lamport_timestamp(&self) -> clock::Lamport {
2489        match self {
2490            Operation::Buffer(_) => {
2491                unreachable!("buffer operations should never be deferred at this layer")
2492            }
2493            Operation::UpdateDiagnostics {
2494                lamport_timestamp, ..
2495            }
2496            | Operation::UpdateSelections {
2497                lamport_timestamp, ..
2498            }
2499            | Operation::UpdateCompletionTriggers {
2500                lamport_timestamp, ..
2501            } => *lamport_timestamp,
2502        }
2503    }
2504}
2505
2506impl Default for Diagnostic {
2507    fn default() -> Self {
2508        Self {
2509            code: None,
2510            severity: DiagnosticSeverity::ERROR,
2511            message: Default::default(),
2512            group_id: 0,
2513            is_primary: false,
2514            is_valid: true,
2515            is_disk_based: false,
2516            is_unnecessary: false,
2517        }
2518    }
2519}
2520
2521impl IndentSize {
2522    pub fn spaces(len: u32) -> Self {
2523        Self {
2524            len,
2525            kind: IndentKind::Space,
2526        }
2527    }
2528
2529    pub fn tab() -> Self {
2530        Self {
2531            len: 1,
2532            kind: IndentKind::Tab,
2533        }
2534    }
2535
2536    pub fn chars(&self) -> impl Iterator<Item = char> {
2537        iter::repeat(self.char()).take(self.len as usize)
2538    }
2539
2540    pub fn char(&self) -> char {
2541        match self.kind {
2542            IndentKind::Space => ' ',
2543            IndentKind::Tab => '\t',
2544        }
2545    }
2546
2547    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
2548        match direction {
2549            Ordering::Less => {
2550                if self.kind == size.kind && self.len >= size.len {
2551                    self.len -= size.len;
2552                }
2553            }
2554            Ordering::Equal => {}
2555            Ordering::Greater => {
2556                if self.len == 0 {
2557                    self = size;
2558                } else if self.kind == size.kind {
2559                    self.len += size.len;
2560                }
2561            }
2562        }
2563        self
2564    }
2565}
2566
2567impl Completion {
2568    pub fn sort_key(&self) -> (usize, &str) {
2569        let kind_key = match self.lsp_completion.kind {
2570            Some(lsp::CompletionItemKind::VARIABLE) => 0,
2571            _ => 1,
2572        };
2573        (kind_key, &self.label.text[self.label.filter_range.clone()])
2574    }
2575
2576    pub fn is_snippet(&self) -> bool {
2577        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
2578    }
2579}
2580
2581pub fn contiguous_ranges(
2582    values: impl Iterator<Item = u32>,
2583    max_len: usize,
2584) -> impl Iterator<Item = Range<u32>> {
2585    let mut values = values.into_iter();
2586    let mut current_range: Option<Range<u32>> = None;
2587    std::iter::from_fn(move || loop {
2588        if let Some(value) = values.next() {
2589            if let Some(range) = &mut current_range {
2590                if value == range.end && range.len() < max_len {
2591                    range.end += 1;
2592                    continue;
2593                }
2594            }
2595
2596            let prev_range = current_range.clone();
2597            current_range = Some(value..(value + 1));
2598            if prev_range.is_some() {
2599                return prev_range;
2600            }
2601        } else {
2602            return current_range.take();
2603        }
2604    })
2605}
2606
2607pub fn char_kind(c: char) -> CharKind {
2608    if c.is_whitespace() {
2609        CharKind::Whitespace
2610    } else if c.is_alphanumeric() || c == '_' {
2611        CharKind::Word
2612    } else {
2613        CharKind::Punctuation
2614    }
2615}