buffer.rs

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