buffer.rs

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