buffer.rs

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