buffer.rs

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