buffer.rs

   1use crate::diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
   2pub use crate::{
   3    diagnostic_set::DiagnosticSet,
   4    highlight_map::{HighlightId, HighlightMap},
   5    proto, BracketPair, Grammar, Language, LanguageConfig, LanguageRegistry, LanguageServerConfig,
   6    PLAIN_TEXT,
   7};
   8use anyhow::{anyhow, Result};
   9use clock::ReplicaId;
  10use futures::FutureExt as _;
  11use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, MutableAppContext, Task};
  12use lazy_static::lazy_static;
  13use lsp::LanguageServer;
  14use parking_lot::Mutex;
  15use postage::{prelude::Stream, sink::Sink, watch};
  16use similar::{ChangeTag, TextDiff};
  17use smol::future::yield_now;
  18use std::{
  19    any::Any,
  20    cell::RefCell,
  21    cmp::{self, Ordering},
  22    collections::{BTreeMap, HashMap},
  23    ffi::OsString,
  24    future::Future,
  25    iter::{Iterator, Peekable},
  26    ops::{Deref, DerefMut, Range, Sub},
  27    path::{Path, PathBuf},
  28    str,
  29    sync::Arc,
  30    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  31    vec,
  32};
  33use sum_tree::TreeMap;
  34use text::{operation_queue::OperationQueue, rope::TextDimension};
  35pub use text::{Buffer as TextBuffer, Operation as _, *};
  36use theme::SyntaxTheme;
  37use tree_sitter::{InputEdit, Parser, QueryCursor, Tree};
  38use util::{post_inc, TryFutureExt as _};
  39
  40#[cfg(any(test, feature = "test-support"))]
  41pub use tree_sitter_rust;
  42
  43pub use lsp::DiagnosticSeverity;
  44
  45thread_local! {
  46    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  47}
  48
  49lazy_static! {
  50    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  51}
  52
  53// TODO - Make this configurable
  54const INDENT_SIZE: u32 = 4;
  55
  56pub struct Buffer {
  57    text: TextBuffer,
  58    file: Option<Box<dyn File>>,
  59    saved_version: clock::Global,
  60    saved_mtime: SystemTime,
  61    language: Option<Arc<Language>>,
  62    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  63    pending_autoindent: Option<Task<()>>,
  64    sync_parse_timeout: Duration,
  65    syntax_tree: Mutex<Option<SyntaxTree>>,
  66    parsing_in_background: bool,
  67    parse_count: usize,
  68    remote_selections: TreeMap<ReplicaId, Arc<[Selection<Anchor>]>>,
  69    selections_update_count: usize,
  70    diagnostic_sets: Vec<DiagnosticSet>,
  71    diagnostics_update_count: usize,
  72    language_server: Option<LanguageServerState>,
  73    deferred_ops: OperationQueue<Operation>,
  74    #[cfg(test)]
  75    pub(crate) operations: Vec<Operation>,
  76}
  77
  78pub struct BufferSnapshot {
  79    text: text::BufferSnapshot,
  80    tree: Option<Tree>,
  81    diagnostic_sets: Vec<DiagnosticSet>,
  82    diagnostics_update_count: usize,
  83    remote_selections: TreeMap<ReplicaId, Arc<[Selection<Anchor>]>>,
  84    selections_update_count: usize,
  85    is_parsing: bool,
  86    language: Option<Arc<Language>>,
  87    parse_count: usize,
  88}
  89
  90#[derive(Clone, Debug, PartialEq, Eq)]
  91pub struct GroupId {
  92    source: Arc<str>,
  93    id: usize,
  94}
  95
  96#[derive(Clone, Debug, PartialEq, Eq)]
  97pub struct Diagnostic {
  98    pub code: Option<String>,
  99    pub severity: DiagnosticSeverity,
 100    pub message: String,
 101    pub group_id: usize,
 102    pub is_valid: bool,
 103    pub is_primary: bool,
 104    pub is_disk_based: bool,
 105}
 106
 107struct LanguageServerState {
 108    server: Arc<LanguageServer>,
 109    latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
 110    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
 111    next_version: usize,
 112    _maintain_server: Task<Option<()>>,
 113}
 114
 115#[derive(Clone)]
 116struct LanguageServerSnapshot {
 117    buffer_snapshot: text::BufferSnapshot,
 118    version: usize,
 119    path: Arc<Path>,
 120}
 121
 122#[derive(Clone, Debug)]
 123pub enum Operation {
 124    Buffer(text::Operation),
 125    UpdateDiagnostics {
 126        provider_name: String,
 127        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 128        lamport_timestamp: clock::Lamport,
 129    },
 130    UpdateSelections {
 131        replica_id: ReplicaId,
 132        selections: Arc<[Selection<Anchor>]>,
 133        lamport_timestamp: clock::Lamport,
 134    },
 135    RemoveSelections {
 136        replica_id: ReplicaId,
 137        lamport_timestamp: clock::Lamport,
 138    },
 139}
 140
 141#[derive(Clone, Debug, Eq, PartialEq)]
 142pub enum Event {
 143    Edited,
 144    Dirtied,
 145    Saved,
 146    FileHandleChanged,
 147    Reloaded,
 148    Reparsed,
 149    DiagnosticsUpdated,
 150    Closed,
 151}
 152
 153pub trait File {
 154    fn mtime(&self) -> SystemTime;
 155
 156    /// Returns the path of this file relative to the worktree's root directory.
 157    fn path(&self) -> &Arc<Path>;
 158
 159    /// Returns the absolute path of this file.
 160    fn abs_path(&self) -> Option<PathBuf>;
 161
 162    /// Returns the path of this file relative to the worktree's parent directory (this means it
 163    /// includes the name of the worktree's root folder).
 164    fn full_path(&self) -> PathBuf;
 165
 166    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 167    /// of its worktree, then this method will return the name of the worktree itself.
 168    fn file_name(&self) -> Option<OsString>;
 169
 170    fn is_deleted(&self) -> bool;
 171
 172    fn save(
 173        &self,
 174        buffer_id: u64,
 175        text: Rope,
 176        version: clock::Global,
 177        cx: &mut MutableAppContext,
 178    ) -> Task<Result<(clock::Global, SystemTime)>>;
 179
 180    fn load_local(&self, cx: &AppContext) -> Option<Task<Result<String>>>;
 181
 182    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
 183
 184    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
 185
 186    fn as_any(&self) -> &dyn Any;
 187}
 188
 189struct QueryCursorHandle(Option<QueryCursor>);
 190
 191#[derive(Clone)]
 192struct SyntaxTree {
 193    tree: Tree,
 194    version: clock::Global,
 195}
 196
 197#[derive(Clone)]
 198struct AutoindentRequest {
 199    before_edit: BufferSnapshot,
 200    edited: Vec<Anchor>,
 201    inserted: Option<Vec<Range<Anchor>>>,
 202}
 203
 204#[derive(Debug)]
 205struct IndentSuggestion {
 206    basis_row: u32,
 207    indent: bool,
 208}
 209
 210struct TextProvider<'a>(&'a Rope);
 211
 212struct BufferChunkHighlights<'a> {
 213    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 214    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 215    stack: Vec<(usize, HighlightId)>,
 216    highlight_map: HighlightMap,
 217    theme: &'a SyntaxTheme,
 218    _query_cursor: QueryCursorHandle,
 219}
 220
 221pub struct BufferChunks<'a> {
 222    range: Range<usize>,
 223    chunks: rope::Chunks<'a>,
 224    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 225    error_depth: usize,
 226    warning_depth: usize,
 227    information_depth: usize,
 228    hint_depth: usize,
 229    highlights: Option<BufferChunkHighlights<'a>>,
 230}
 231
 232#[derive(Clone, Copy, Debug, Default)]
 233pub struct Chunk<'a> {
 234    pub text: &'a str,
 235    pub highlight_style: Option<HighlightStyle>,
 236    pub diagnostic: Option<DiagnosticSeverity>,
 237}
 238
 239pub(crate) struct Diff {
 240    base_version: clock::Global,
 241    new_text: Arc<str>,
 242    changes: Vec<(ChangeTag, usize)>,
 243}
 244
 245#[derive(Clone, Copy)]
 246struct DiagnosticEndpoint {
 247    offset: usize,
 248    is_start: bool,
 249    severity: DiagnosticSeverity,
 250}
 251
 252impl Buffer {
 253    pub fn new<T: Into<Arc<str>>>(
 254        replica_id: ReplicaId,
 255        base_text: T,
 256        cx: &mut ModelContext<Self>,
 257    ) -> Self {
 258        Self::build(
 259            TextBuffer::new(
 260                replica_id,
 261                cx.model_id() as u64,
 262                History::new(base_text.into()),
 263            ),
 264            None,
 265        )
 266    }
 267
 268    pub fn from_file<T: Into<Arc<str>>>(
 269        replica_id: ReplicaId,
 270        base_text: T,
 271        file: Box<dyn File>,
 272        cx: &mut ModelContext<Self>,
 273    ) -> Self {
 274        Self::build(
 275            TextBuffer::new(
 276                replica_id,
 277                cx.model_id() as u64,
 278                History::new(base_text.into()),
 279            ),
 280            Some(file),
 281        )
 282    }
 283
 284    pub fn from_proto(
 285        replica_id: ReplicaId,
 286        message: proto::Buffer,
 287        file: Option<Box<dyn File>>,
 288        cx: &mut ModelContext<Self>,
 289    ) -> Result<Self> {
 290        let fragments_len = message.fragments.len();
 291        let buffer = TextBuffer::from_parts(
 292            replica_id,
 293            message.id,
 294            &message.visible_text,
 295            &message.deleted_text,
 296            message
 297                .undo_map
 298                .into_iter()
 299                .map(proto::deserialize_undo_map_entry),
 300            message
 301                .fragments
 302                .into_iter()
 303                .enumerate()
 304                .map(|(i, fragment)| {
 305                    proto::deserialize_buffer_fragment(fragment, i, fragments_len)
 306                }),
 307            message.lamport_timestamp,
 308            From::from(message.version),
 309        );
 310        let mut this = Self::build(buffer, file);
 311        for selection_set in message.selections {
 312            this.remote_selections.insert(
 313                selection_set.replica_id as ReplicaId,
 314                proto::deserialize_selections(selection_set.selections),
 315            );
 316        }
 317        let snapshot = this.snapshot();
 318        for diagnostic_set in message.diagnostic_sets {
 319            let (provider_name, entries) = proto::deserialize_diagnostic_set(diagnostic_set);
 320            this.apply_diagnostic_update(
 321                DiagnosticSet::from_sorted_entries(
 322                    provider_name,
 323                    entries.into_iter().cloned(),
 324                    &snapshot,
 325                ),
 326                cx,
 327            );
 328        }
 329
 330        let deferred_ops = message
 331            .deferred_operations
 332            .into_iter()
 333            .map(proto::deserialize_operation)
 334            .collect::<Result<Vec<_>>>()?;
 335        this.apply_ops(deferred_ops, cx)?;
 336
 337        Ok(this)
 338    }
 339
 340    pub fn to_proto(&self) -> proto::Buffer {
 341        proto::Buffer {
 342            id: self.remote_id(),
 343            visible_text: self.text.text(),
 344            deleted_text: self.text.deleted_text(),
 345            undo_map: self
 346                .text
 347                .undo_history()
 348                .map(proto::serialize_undo_map_entry)
 349                .collect(),
 350            version: From::from(&self.version),
 351            lamport_timestamp: self.lamport_clock.value,
 352            fragments: self
 353                .text
 354                .fragments()
 355                .map(proto::serialize_buffer_fragment)
 356                .collect(),
 357            selections: self
 358                .remote_selections
 359                .iter()
 360                .map(|(replica_id, selections)| proto::SelectionSet {
 361                    replica_id: *replica_id as u32,
 362                    selections: proto::serialize_selections(selections),
 363                })
 364                .collect(),
 365            diagnostic_sets: self
 366                .diagnostic_sets
 367                .iter()
 368                .map(|set| {
 369                    proto::serialize_diagnostic_set(set.provider_name().to_string(), set.iter())
 370                })
 371                .collect(),
 372            deferred_operations: self
 373                .deferred_ops
 374                .iter()
 375                .map(proto::serialize_operation)
 376                .chain(
 377                    self.text
 378                        .deferred_ops()
 379                        .map(|op| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 380                )
 381                .collect(),
 382        }
 383    }
 384
 385    pub fn with_language(
 386        mut self,
 387        language: Option<Arc<Language>>,
 388        language_server: Option<Arc<LanguageServer>>,
 389        cx: &mut ModelContext<Self>,
 390    ) -> Self {
 391        self.set_language(language, language_server, cx);
 392        self
 393    }
 394
 395    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 396        let saved_mtime;
 397        if let Some(file) = file.as_ref() {
 398            saved_mtime = file.mtime();
 399        } else {
 400            saved_mtime = UNIX_EPOCH;
 401        }
 402
 403        Self {
 404            saved_mtime,
 405            saved_version: buffer.version(),
 406            text: buffer,
 407            file,
 408            syntax_tree: Mutex::new(None),
 409            parsing_in_background: false,
 410            parse_count: 0,
 411            sync_parse_timeout: Duration::from_millis(1),
 412            autoindent_requests: Default::default(),
 413            pending_autoindent: Default::default(),
 414            language: None,
 415            remote_selections: Default::default(),
 416            selections_update_count: 0,
 417            diagnostic_sets: Default::default(),
 418            diagnostics_update_count: 0,
 419            language_server: None,
 420            deferred_ops: OperationQueue::new(),
 421            #[cfg(test)]
 422            operations: Default::default(),
 423        }
 424    }
 425
 426    pub fn snapshot(&self) -> BufferSnapshot {
 427        BufferSnapshot {
 428            text: self.text.snapshot(),
 429            tree: self.syntax_tree(),
 430            remote_selections: self.remote_selections.clone(),
 431            diagnostic_sets: self.diagnostic_sets.clone(),
 432            diagnostics_update_count: self.diagnostics_update_count,
 433            is_parsing: self.parsing_in_background,
 434            language: self.language.clone(),
 435            parse_count: self.parse_count,
 436            selections_update_count: self.selections_update_count,
 437        }
 438    }
 439
 440    pub fn file(&self) -> Option<&dyn File> {
 441        self.file.as_deref()
 442    }
 443
 444    pub fn save(
 445        &mut self,
 446        cx: &mut ModelContext<Self>,
 447    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 448        let file = self
 449            .file
 450            .as_ref()
 451            .ok_or_else(|| anyhow!("buffer has no file"))?;
 452        let text = self.as_rope().clone();
 453        let version = self.version();
 454        let save = file.save(self.remote_id(), text, version, cx.as_mut());
 455        Ok(cx.spawn(|this, mut cx| async move {
 456            let (version, mtime) = save.await?;
 457            this.update(&mut cx, |this, cx| {
 458                this.did_save(version.clone(), mtime, None, cx);
 459            });
 460            Ok((version, mtime))
 461        }))
 462    }
 463
 464    pub fn set_language(
 465        &mut self,
 466        language: Option<Arc<Language>>,
 467        language_server: Option<Arc<lsp::LanguageServer>>,
 468        cx: &mut ModelContext<Self>,
 469    ) {
 470        self.language = language;
 471        self.language_server = if let Some(server) = language_server {
 472            let (latest_snapshot_tx, mut latest_snapshot_rx) = watch::channel();
 473            Some(LanguageServerState {
 474                latest_snapshot: latest_snapshot_tx,
 475                pending_snapshots: Default::default(),
 476                next_version: 0,
 477                server: server.clone(),
 478                _maintain_server: cx.background().spawn(
 479                    async move {
 480                        let mut prev_snapshot: Option<LanguageServerSnapshot> = None;
 481                        while let Some(snapshot) = latest_snapshot_rx.recv().await {
 482                            if let Some(snapshot) = snapshot {
 483                                let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
 484                                if let Some(prev_snapshot) = prev_snapshot {
 485                                    let changes = lsp::DidChangeTextDocumentParams {
 486                                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 487                                            uri,
 488                                            snapshot.version as i32,
 489                                        ),
 490                                        content_changes: snapshot
 491                                            .buffer_snapshot
 492                                            .edits_since::<(PointUtf16, usize)>(
 493                                                prev_snapshot.buffer_snapshot.version(),
 494                                            )
 495                                            .map(|edit| {
 496                                                let edit_start = edit.new.start.0;
 497                                                let edit_end = edit_start
 498                                                    + (edit.old.end.0 - edit.old.start.0);
 499                                                let new_text = snapshot
 500                                                    .buffer_snapshot
 501                                                    .text_for_range(
 502                                                        edit.new.start.1..edit.new.end.1,
 503                                                    )
 504                                                    .collect();
 505                                                lsp::TextDocumentContentChangeEvent {
 506                                                    range: Some(lsp::Range::new(
 507                                                        lsp::Position::new(
 508                                                            edit_start.row,
 509                                                            edit_start.column,
 510                                                        ),
 511                                                        lsp::Position::new(
 512                                                            edit_end.row,
 513                                                            edit_end.column,
 514                                                        ),
 515                                                    )),
 516                                                    range_length: None,
 517                                                    text: new_text,
 518                                                }
 519                                            })
 520                                            .collect(),
 521                                    };
 522                                    server
 523                                        .notify::<lsp::notification::DidChangeTextDocument>(changes)
 524                                        .await?;
 525                                } else {
 526                                    server
 527                                        .notify::<lsp::notification::DidOpenTextDocument>(
 528                                            lsp::DidOpenTextDocumentParams {
 529                                                text_document: lsp::TextDocumentItem::new(
 530                                                    uri,
 531                                                    Default::default(),
 532                                                    snapshot.version as i32,
 533                                                    snapshot.buffer_snapshot.text().to_string(),
 534                                                ),
 535                                            },
 536                                        )
 537                                        .await?;
 538                                }
 539
 540                                prev_snapshot = Some(snapshot);
 541                            }
 542                        }
 543                        Ok(())
 544                    }
 545                    .log_err(),
 546                ),
 547            })
 548        } else {
 549            None
 550        };
 551
 552        self.reparse(cx);
 553        self.update_language_server();
 554    }
 555
 556    pub fn did_save(
 557        &mut self,
 558        version: clock::Global,
 559        mtime: SystemTime,
 560        new_file: Option<Box<dyn File>>,
 561        cx: &mut ModelContext<Self>,
 562    ) {
 563        self.saved_mtime = mtime;
 564        self.saved_version = version;
 565        if let Some(new_file) = new_file {
 566            self.file = Some(new_file);
 567        }
 568        if let Some(state) = &self.language_server {
 569            cx.background()
 570                .spawn(
 571                    state
 572                        .server
 573                        .notify::<lsp::notification::DidSaveTextDocument>(
 574                            lsp::DidSaveTextDocumentParams {
 575                                text_document: lsp::TextDocumentIdentifier {
 576                                    uri: lsp::Url::from_file_path(
 577                                        self.file.as_ref().unwrap().abs_path().unwrap(),
 578                                    )
 579                                    .unwrap(),
 580                                },
 581                                text: None,
 582                            },
 583                        ),
 584                )
 585                .detach()
 586        }
 587        cx.emit(Event::Saved);
 588    }
 589
 590    pub fn file_updated(
 591        &mut self,
 592        new_file: Box<dyn File>,
 593        cx: &mut ModelContext<Self>,
 594    ) -> Option<Task<()>> {
 595        let old_file = self.file.as_ref()?;
 596        let mut file_changed = false;
 597        let mut task = None;
 598
 599        if new_file.path() != old_file.path() {
 600            file_changed = true;
 601        }
 602
 603        if new_file.is_deleted() {
 604            if !old_file.is_deleted() {
 605                file_changed = true;
 606                if !self.is_dirty() {
 607                    cx.emit(Event::Dirtied);
 608                }
 609            }
 610        } else {
 611            let new_mtime = new_file.mtime();
 612            if new_mtime != old_file.mtime() {
 613                file_changed = true;
 614
 615                if !self.is_dirty() {
 616                    task = Some(cx.spawn(|this, mut cx| {
 617                        async move {
 618                            let new_text = this.read_with(&cx, |this, cx| {
 619                                this.file.as_ref().and_then(|file| file.load_local(cx))
 620                            });
 621                            if let Some(new_text) = new_text {
 622                                let new_text = new_text.await?;
 623                                let diff = this
 624                                    .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
 625                                    .await;
 626                                this.update(&mut cx, |this, cx| {
 627                                    if this.apply_diff(diff, cx) {
 628                                        this.saved_version = this.version();
 629                                        this.saved_mtime = new_mtime;
 630                                        cx.emit(Event::Reloaded);
 631                                    }
 632                                });
 633                            }
 634                            Ok(())
 635                        }
 636                        .log_err()
 637                        .map(drop)
 638                    }));
 639                }
 640            }
 641        }
 642
 643        if file_changed {
 644            cx.emit(Event::FileHandleChanged);
 645        }
 646        self.file = Some(new_file);
 647        task
 648    }
 649
 650    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 651        cx.emit(Event::Closed);
 652    }
 653
 654    pub fn language(&self) -> Option<&Arc<Language>> {
 655        self.language.as_ref()
 656    }
 657
 658    pub fn parse_count(&self) -> usize {
 659        self.parse_count
 660    }
 661
 662    pub fn selections_update_count(&self) -> usize {
 663        self.selections_update_count
 664    }
 665
 666    pub fn diagnostics_update_count(&self) -> usize {
 667        self.diagnostics_update_count
 668    }
 669
 670    pub(crate) fn syntax_tree(&self) -> Option<Tree> {
 671        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 672            self.interpolate_tree(syntax_tree);
 673            Some(syntax_tree.tree.clone())
 674        } else {
 675            None
 676        }
 677    }
 678
 679    #[cfg(any(test, feature = "test-support"))]
 680    pub fn is_parsing(&self) -> bool {
 681        self.parsing_in_background
 682    }
 683
 684    #[cfg(test)]
 685    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 686        self.sync_parse_timeout = timeout;
 687    }
 688
 689    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 690        if self.parsing_in_background {
 691            return false;
 692        }
 693
 694        if let Some(grammar) = self.grammar().cloned() {
 695            let old_tree = self.syntax_tree();
 696            let text = self.as_rope().clone();
 697            let parsed_version = self.version();
 698            let parse_task = cx.background().spawn({
 699                let grammar = grammar.clone();
 700                async move { Self::parse_text(&text, old_tree, &grammar) }
 701            });
 702
 703            match cx
 704                .background()
 705                .block_with_timeout(self.sync_parse_timeout, parse_task)
 706            {
 707                Ok(new_tree) => {
 708                    self.did_finish_parsing(new_tree, parsed_version, cx);
 709                    return true;
 710                }
 711                Err(parse_task) => {
 712                    self.parsing_in_background = true;
 713                    cx.spawn(move |this, mut cx| async move {
 714                        let new_tree = parse_task.await;
 715                        this.update(&mut cx, move |this, cx| {
 716                            let grammar_changed = this
 717                                .grammar()
 718                                .map_or(true, |curr_grammar| !Arc::ptr_eq(&grammar, curr_grammar));
 719                            let parse_again = this.version.gt(&parsed_version) || grammar_changed;
 720                            this.parsing_in_background = false;
 721                            this.did_finish_parsing(new_tree, parsed_version, cx);
 722
 723                            if parse_again && this.reparse(cx) {
 724                                return;
 725                            }
 726                        });
 727                    })
 728                    .detach();
 729                }
 730            }
 731        }
 732        false
 733    }
 734
 735    fn parse_text(text: &Rope, old_tree: Option<Tree>, grammar: &Grammar) -> Tree {
 736        PARSER.with(|parser| {
 737            let mut parser = parser.borrow_mut();
 738            parser
 739                .set_language(grammar.ts_language)
 740                .expect("incompatible grammar");
 741            let mut chunks = text.chunks_in_range(0..text.len());
 742            let tree = parser
 743                .parse_with(
 744                    &mut move |offset, _| {
 745                        chunks.seek(offset);
 746                        chunks.next().unwrap_or("").as_bytes()
 747                    },
 748                    old_tree.as_ref(),
 749                )
 750                .unwrap();
 751            tree
 752        })
 753    }
 754
 755    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 756        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 757            let (bytes, lines) = edit.flatten();
 758            tree.tree.edit(&InputEdit {
 759                start_byte: bytes.new.start,
 760                old_end_byte: bytes.new.start + bytes.old.len(),
 761                new_end_byte: bytes.new.end,
 762                start_position: lines.new.start.to_ts_point(),
 763                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 764                    .to_ts_point(),
 765                new_end_position: lines.new.end.to_ts_point(),
 766            });
 767        }
 768        tree.version = self.version();
 769    }
 770
 771    fn did_finish_parsing(
 772        &mut self,
 773        tree: Tree,
 774        version: clock::Global,
 775        cx: &mut ModelContext<Self>,
 776    ) {
 777        self.parse_count += 1;
 778        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 779        self.request_autoindent(cx);
 780        cx.emit(Event::Reparsed);
 781        cx.notify();
 782    }
 783
 784    pub fn update_diagnostics<T>(
 785        &mut self,
 786        provider_name: Arc<str>,
 787        version: Option<i32>,
 788        mut diagnostics: Vec<DiagnosticEntry<T>>,
 789        cx: &mut ModelContext<Self>,
 790    ) -> Result<Operation>
 791    where
 792        T: Copy + Ord + TextDimension + Sub<Output = T> + Clip + ToPoint,
 793    {
 794        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 795            Ordering::Equal
 796                .then_with(|| b.is_primary.cmp(&a.is_primary))
 797                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 798                .then_with(|| a.severity.cmp(&b.severity))
 799                .then_with(|| a.message.cmp(&b.message))
 800        }
 801
 802        let version = version.map(|version| version as usize);
 803        let content = if let Some(version) = version {
 804            let language_server = self.language_server.as_mut().unwrap();
 805            language_server
 806                .pending_snapshots
 807                .retain(|&v, _| v >= version);
 808            let snapshot = language_server
 809                .pending_snapshots
 810                .get(&version)
 811                .ok_or_else(|| anyhow!("missing snapshot"))?;
 812            &snapshot.buffer_snapshot
 813        } else {
 814            self.deref()
 815        };
 816
 817        diagnostics.sort_unstable_by(|a, b| {
 818            Ordering::Equal
 819                .then_with(|| a.range.start.cmp(&b.range.start))
 820                .then_with(|| b.range.end.cmp(&a.range.end))
 821                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 822        });
 823
 824        let mut sanitized_diagnostics = Vec::new();
 825        let mut edits_since_save = content.edits_since::<T>(&self.saved_version).peekable();
 826        let mut last_edit_old_end = T::default();
 827        let mut last_edit_new_end = T::default();
 828        'outer: for entry in diagnostics {
 829            let mut start = entry.range.start;
 830            let mut end = entry.range.end;
 831
 832            // Some diagnostics are based on files on disk instead of buffers'
 833            // current contents. Adjust these diagnostics' ranges to reflect
 834            // any unsaved edits.
 835            if entry.diagnostic.is_disk_based {
 836                while let Some(edit) = edits_since_save.peek() {
 837                    if edit.old.end <= start {
 838                        last_edit_old_end = edit.old.end;
 839                        last_edit_new_end = edit.new.end;
 840                        edits_since_save.next();
 841                    } else if edit.old.start <= end && edit.old.end >= start {
 842                        continue 'outer;
 843                    } else {
 844                        break;
 845                    }
 846                }
 847
 848                let start_overshoot = start - last_edit_old_end;
 849                start = last_edit_new_end;
 850                start.add_assign(&start_overshoot);
 851
 852                let end_overshoot = end - last_edit_old_end;
 853                end = last_edit_new_end;
 854                end.add_assign(&end_overshoot);
 855            }
 856
 857            let range = start.clip(Bias::Left, content)..end.clip(Bias::Right, content);
 858            let mut range = range.start.to_point(content)..range.end.to_point(content);
 859            // Expand empty ranges by one character
 860            if range.start == range.end {
 861                range.end.column += 1;
 862                range.end = content.clip_point(range.end, Bias::Right);
 863                if range.start == range.end && range.end.column > 0 {
 864                    range.start.column -= 1;
 865                    range.start = content.clip_point(range.start, Bias::Left);
 866                }
 867            }
 868
 869            sanitized_diagnostics.push(DiagnosticEntry {
 870                range,
 871                diagnostic: entry.diagnostic,
 872            });
 873        }
 874        drop(edits_since_save);
 875
 876        let set = DiagnosticSet::new(provider_name, sanitized_diagnostics, content);
 877        self.apply_diagnostic_update(set.clone(), cx);
 878        Ok(Operation::UpdateDiagnostics {
 879            provider_name: set.provider_name().to_string(),
 880            diagnostics: set.iter().cloned().collect(),
 881            lamport_timestamp: self.text.lamport_clock.tick(),
 882        })
 883    }
 884
 885    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 886        if let Some(indent_columns) = self.compute_autoindents() {
 887            let indent_columns = cx.background().spawn(indent_columns);
 888            match cx
 889                .background()
 890                .block_with_timeout(Duration::from_micros(500), indent_columns)
 891            {
 892                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 893                Err(indent_columns) => {
 894                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 895                        let indent_columns = indent_columns.await;
 896                        this.update(&mut cx, |this, cx| {
 897                            this.apply_autoindents(indent_columns, cx);
 898                        });
 899                    }));
 900                }
 901            }
 902        }
 903    }
 904
 905    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 906        let max_rows_between_yields = 100;
 907        let snapshot = self.snapshot();
 908        if snapshot.language.is_none()
 909            || snapshot.tree.is_none()
 910            || self.autoindent_requests.is_empty()
 911        {
 912            return None;
 913        }
 914
 915        let autoindent_requests = self.autoindent_requests.clone();
 916        Some(async move {
 917            let mut indent_columns = BTreeMap::new();
 918            for request in autoindent_requests {
 919                let old_to_new_rows = request
 920                    .edited
 921                    .iter()
 922                    .map(|anchor| anchor.summary::<Point>(&request.before_edit).row)
 923                    .zip(
 924                        request
 925                            .edited
 926                            .iter()
 927                            .map(|anchor| anchor.summary::<Point>(&snapshot).row),
 928                    )
 929                    .collect::<BTreeMap<u32, u32>>();
 930
 931                let mut old_suggestions = HashMap::<u32, u32>::default();
 932                let old_edited_ranges =
 933                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 934                for old_edited_range in old_edited_ranges {
 935                    let suggestions = request
 936                        .before_edit
 937                        .suggest_autoindents(old_edited_range.clone())
 938                        .into_iter()
 939                        .flatten();
 940                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 941                        let indentation_basis = old_to_new_rows
 942                            .get(&suggestion.basis_row)
 943                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 944                            .unwrap_or_else(|| {
 945                                request
 946                                    .before_edit
 947                                    .indent_column_for_line(suggestion.basis_row)
 948                            });
 949                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 950                        old_suggestions.insert(
 951                            *old_to_new_rows.get(&old_row).unwrap(),
 952                            indentation_basis + delta,
 953                        );
 954                    }
 955                    yield_now().await;
 956                }
 957
 958                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 959                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 960                let new_edited_row_ranges =
 961                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 962                for new_edited_row_range in new_edited_row_ranges {
 963                    let suggestions = snapshot
 964                        .suggest_autoindents(new_edited_row_range.clone())
 965                        .into_iter()
 966                        .flatten();
 967                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 968                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 969                        let new_indentation = indent_columns
 970                            .get(&suggestion.basis_row)
 971                            .copied()
 972                            .unwrap_or_else(|| {
 973                                snapshot.indent_column_for_line(suggestion.basis_row)
 974                            })
 975                            + delta;
 976                        if old_suggestions
 977                            .get(&new_row)
 978                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 979                        {
 980                            indent_columns.insert(new_row, new_indentation);
 981                        }
 982                    }
 983                    yield_now().await;
 984                }
 985
 986                if let Some(inserted) = request.inserted.as_ref() {
 987                    let inserted_row_ranges = contiguous_ranges(
 988                        inserted
 989                            .iter()
 990                            .map(|range| range.to_point(&snapshot))
 991                            .flat_map(|range| range.start.row..range.end.row + 1),
 992                        max_rows_between_yields,
 993                    );
 994                    for inserted_row_range in inserted_row_ranges {
 995                        let suggestions = snapshot
 996                            .suggest_autoindents(inserted_row_range.clone())
 997                            .into_iter()
 998                            .flatten();
 999                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
1000                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1001                            let new_indentation = indent_columns
1002                                .get(&suggestion.basis_row)
1003                                .copied()
1004                                .unwrap_or_else(|| {
1005                                    snapshot.indent_column_for_line(suggestion.basis_row)
1006                                })
1007                                + delta;
1008                            indent_columns.insert(row, new_indentation);
1009                        }
1010                        yield_now().await;
1011                    }
1012                }
1013            }
1014            indent_columns
1015        })
1016    }
1017
1018    fn apply_autoindents(
1019        &mut self,
1020        indent_columns: BTreeMap<u32, u32>,
1021        cx: &mut ModelContext<Self>,
1022    ) {
1023        self.autoindent_requests.clear();
1024        self.start_transaction();
1025        for (row, indent_column) in &indent_columns {
1026            self.set_indent_column_for_line(*row, *indent_column, cx);
1027        }
1028        self.end_transaction(cx);
1029    }
1030
1031    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1032        let current_column = self.indent_column_for_line(row);
1033        if column > current_column {
1034            let offset = Point::new(row, 0).to_offset(&*self);
1035            self.edit(
1036                [offset..offset],
1037                " ".repeat((column - current_column) as usize),
1038                cx,
1039            );
1040        } else if column < current_column {
1041            self.edit(
1042                [Point::new(row, 0)..Point::new(row, current_column - column)],
1043                "",
1044                cx,
1045            );
1046        }
1047    }
1048
1049    pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1050        // TODO: it would be nice to not allocate here.
1051        let old_text = self.text();
1052        let base_version = self.version();
1053        cx.background().spawn(async move {
1054            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1055                .iter_all_changes()
1056                .map(|c| (c.tag(), c.value().len()))
1057                .collect::<Vec<_>>();
1058            Diff {
1059                base_version,
1060                new_text,
1061                changes,
1062            }
1063        })
1064    }
1065
1066    pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1067        if self.version == diff.base_version {
1068            self.start_transaction();
1069            let mut offset = 0;
1070            for (tag, len) in diff.changes {
1071                let range = offset..(offset + len);
1072                match tag {
1073                    ChangeTag::Equal => offset += len,
1074                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1075                    ChangeTag::Insert => {
1076                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1077                        offset += len;
1078                    }
1079                }
1080            }
1081            self.end_transaction(cx);
1082            true
1083        } else {
1084            false
1085        }
1086    }
1087
1088    pub fn is_dirty(&self) -> bool {
1089        !self.saved_version.ge(&self.version)
1090            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1091    }
1092
1093    pub fn has_conflict(&self) -> bool {
1094        !self.saved_version.ge(&self.version)
1095            && self
1096                .file
1097                .as_ref()
1098                .map_or(false, |file| file.mtime() > self.saved_mtime)
1099    }
1100
1101    pub fn subscribe(&mut self) -> Subscription {
1102        self.text.subscribe()
1103    }
1104
1105    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1106        self.start_transaction_at(Instant::now())
1107    }
1108
1109    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1110        self.text.start_transaction_at(now)
1111    }
1112
1113    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1114        self.end_transaction_at(Instant::now(), cx)
1115    }
1116
1117    pub fn end_transaction_at(
1118        &mut self,
1119        now: Instant,
1120        cx: &mut ModelContext<Self>,
1121    ) -> Option<TransactionId> {
1122        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1123            let was_dirty = start_version != self.saved_version;
1124            self.did_edit(&start_version, was_dirty, cx);
1125            Some(transaction_id)
1126        } else {
1127            None
1128        }
1129    }
1130
1131    pub fn set_active_selections(
1132        &mut self,
1133        selections: Arc<[Selection<Anchor>]>,
1134        cx: &mut ModelContext<Self>,
1135    ) {
1136        let lamport_timestamp = self.text.lamport_clock.tick();
1137        self.remote_selections
1138            .insert(self.text.replica_id(), selections.clone());
1139        self.send_operation(
1140            Operation::UpdateSelections {
1141                replica_id: self.text.replica_id(),
1142                selections,
1143                lamport_timestamp,
1144            },
1145            cx,
1146        );
1147    }
1148
1149    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1150        let lamport_timestamp = self.text.lamport_clock.tick();
1151        self.send_operation(
1152            Operation::RemoveSelections {
1153                replica_id: self.text.replica_id(),
1154                lamport_timestamp,
1155            },
1156            cx,
1157        );
1158    }
1159
1160    fn update_language_server(&mut self) {
1161        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1162            language_server
1163        } else {
1164            return;
1165        };
1166        let abs_path = self
1167            .file
1168            .as_ref()
1169            .map_or(Path::new("/").to_path_buf(), |file| {
1170                file.abs_path().unwrap()
1171            });
1172
1173        let version = post_inc(&mut language_server.next_version);
1174        let snapshot = LanguageServerSnapshot {
1175            buffer_snapshot: self.text.snapshot(),
1176            version,
1177            path: Arc::from(abs_path),
1178        };
1179        language_server
1180            .pending_snapshots
1181            .insert(version, snapshot.clone());
1182        let _ = language_server
1183            .latest_snapshot
1184            .blocking_send(Some(snapshot));
1185    }
1186
1187    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1188    where
1189        I: IntoIterator<Item = Range<S>>,
1190        S: ToOffset,
1191        T: Into<String>,
1192    {
1193        self.edit_internal(ranges_iter, new_text, false, cx)
1194    }
1195
1196    pub fn edit_with_autoindent<I, S, T>(
1197        &mut self,
1198        ranges_iter: I,
1199        new_text: T,
1200        cx: &mut ModelContext<Self>,
1201    ) where
1202        I: IntoIterator<Item = Range<S>>,
1203        S: ToOffset,
1204        T: Into<String>,
1205    {
1206        self.edit_internal(ranges_iter, new_text, true, cx)
1207    }
1208
1209    pub fn edit_internal<I, S, T>(
1210        &mut self,
1211        ranges_iter: I,
1212        new_text: T,
1213        autoindent: bool,
1214        cx: &mut ModelContext<Self>,
1215    ) where
1216        I: IntoIterator<Item = Range<S>>,
1217        S: ToOffset,
1218        T: Into<String>,
1219    {
1220        let new_text = new_text.into();
1221
1222        // Skip invalid ranges and coalesce contiguous ones.
1223        let mut ranges: Vec<Range<usize>> = Vec::new();
1224        for range in ranges_iter {
1225            let range = range.start.to_offset(self)..range.end.to_offset(self);
1226            if !new_text.is_empty() || !range.is_empty() {
1227                if let Some(prev_range) = ranges.last_mut() {
1228                    if prev_range.end >= range.start {
1229                        prev_range.end = cmp::max(prev_range.end, range.end);
1230                    } else {
1231                        ranges.push(range);
1232                    }
1233                } else {
1234                    ranges.push(range);
1235                }
1236            }
1237        }
1238        if ranges.is_empty() {
1239            return;
1240        }
1241
1242        self.start_transaction();
1243        self.pending_autoindent.take();
1244        let autoindent_request = if autoindent && self.language.is_some() {
1245            let before_edit = self.snapshot();
1246            let edited = ranges
1247                .iter()
1248                .filter_map(|range| {
1249                    let start = range.start.to_point(self);
1250                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1251                        None
1252                    } else {
1253                        Some(self.anchor_before(range.start))
1254                    }
1255                })
1256                .collect();
1257            Some((before_edit, edited))
1258        } else {
1259            None
1260        };
1261
1262        let first_newline_ix = new_text.find('\n');
1263        let new_text_len = new_text.len();
1264
1265        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1266
1267        if let Some((before_edit, edited)) = autoindent_request {
1268            let mut inserted = None;
1269            if let Some(first_newline_ix) = first_newline_ix {
1270                let mut delta = 0isize;
1271                inserted = Some(
1272                    ranges
1273                        .iter()
1274                        .map(|range| {
1275                            let start =
1276                                (delta + range.start as isize) as usize + first_newline_ix + 1;
1277                            let end = (delta + range.start as isize) as usize + new_text_len;
1278                            delta +=
1279                                (range.end as isize - range.start as isize) + new_text_len as isize;
1280                            self.anchor_before(start)..self.anchor_after(end)
1281                        })
1282                        .collect(),
1283                );
1284            }
1285
1286            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1287                before_edit,
1288                edited,
1289                inserted,
1290            }));
1291        }
1292
1293        self.end_transaction(cx);
1294        self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1295    }
1296
1297    fn did_edit(
1298        &mut self,
1299        old_version: &clock::Global,
1300        was_dirty: bool,
1301        cx: &mut ModelContext<Self>,
1302    ) {
1303        if self.edits_since::<usize>(old_version).next().is_none() {
1304            return;
1305        }
1306
1307        self.reparse(cx);
1308        self.update_language_server();
1309
1310        cx.emit(Event::Edited);
1311        if !was_dirty {
1312            cx.emit(Event::Dirtied);
1313        }
1314        cx.notify();
1315    }
1316
1317    fn grammar(&self) -> Option<&Arc<Grammar>> {
1318        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1319    }
1320
1321    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1322        &mut self,
1323        ops: I,
1324        cx: &mut ModelContext<Self>,
1325    ) -> Result<()> {
1326        self.pending_autoindent.take();
1327        let was_dirty = self.is_dirty();
1328        let old_version = self.version.clone();
1329        let mut deferred_ops = Vec::new();
1330        let buffer_ops = ops
1331            .into_iter()
1332            .filter_map(|op| match op {
1333                Operation::Buffer(op) => Some(op),
1334                _ => {
1335                    if self.can_apply_op(&op) {
1336                        self.apply_op(op, cx);
1337                    } else {
1338                        deferred_ops.push(op);
1339                    }
1340                    None
1341                }
1342            })
1343            .collect::<Vec<_>>();
1344        self.text.apply_ops(buffer_ops)?;
1345        self.flush_deferred_ops(cx);
1346        self.did_edit(&old_version, was_dirty, cx);
1347        // Notify independently of whether the buffer was edited as the operations could include a
1348        // selection update.
1349        cx.notify();
1350        Ok(())
1351    }
1352
1353    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1354        let mut deferred_ops = Vec::new();
1355        for op in self.deferred_ops.drain().iter().cloned() {
1356            if self.can_apply_op(&op) {
1357                self.apply_op(op, cx);
1358            } else {
1359                deferred_ops.push(op);
1360            }
1361        }
1362        self.deferred_ops.insert(deferred_ops);
1363    }
1364
1365    fn can_apply_op(&self, operation: &Operation) -> bool {
1366        match operation {
1367            Operation::Buffer(_) => {
1368                unreachable!("buffer operations should never be applied at this layer")
1369            }
1370            Operation::UpdateDiagnostics {
1371                diagnostics: diagnostic_set,
1372                ..
1373            } => diagnostic_set.iter().all(|diagnostic| {
1374                self.text.can_resolve(&diagnostic.range.start)
1375                    && self.text.can_resolve(&diagnostic.range.end)
1376            }),
1377            Operation::UpdateSelections { selections, .. } => selections
1378                .iter()
1379                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1380            Operation::RemoveSelections { .. } => true,
1381        }
1382    }
1383
1384    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1385        match operation {
1386            Operation::Buffer(_) => {
1387                unreachable!("buffer operations should never be applied at this layer")
1388            }
1389            Operation::UpdateDiagnostics {
1390                provider_name,
1391                diagnostics: diagnostic_set,
1392                ..
1393            } => {
1394                let snapshot = self.snapshot();
1395                self.apply_diagnostic_update(
1396                    DiagnosticSet::from_sorted_entries(
1397                        provider_name,
1398                        diagnostic_set.iter().cloned(),
1399                        &snapshot,
1400                    ),
1401                    cx,
1402                );
1403            }
1404            Operation::UpdateSelections {
1405                replica_id,
1406                selections,
1407                lamport_timestamp,
1408            } => {
1409                self.remote_selections.insert(replica_id, selections);
1410                self.text.lamport_clock.observe(lamport_timestamp);
1411                self.selections_update_count += 1;
1412            }
1413            Operation::RemoveSelections {
1414                replica_id,
1415                lamport_timestamp,
1416            } => {
1417                self.remote_selections.remove(&replica_id);
1418                self.text.lamport_clock.observe(lamport_timestamp);
1419                self.selections_update_count += 1;
1420            }
1421        }
1422    }
1423
1424    fn apply_diagnostic_update(&mut self, set: DiagnosticSet, cx: &mut ModelContext<Self>) {
1425        match self
1426            .diagnostic_sets
1427            .binary_search_by_key(&set.provider_name(), |set| set.provider_name())
1428        {
1429            Ok(ix) => self.diagnostic_sets[ix] = set.clone(),
1430            Err(ix) => self.diagnostic_sets.insert(ix, set.clone()),
1431        }
1432
1433        self.diagnostics_update_count += 1;
1434        cx.notify();
1435        cx.emit(Event::DiagnosticsUpdated);
1436    }
1437
1438    #[cfg(not(test))]
1439    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1440        if let Some(file) = &self.file {
1441            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1442        }
1443    }
1444
1445    #[cfg(test)]
1446    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1447        self.operations.push(operation);
1448    }
1449
1450    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1451        self.remote_selections.remove(&replica_id);
1452        cx.notify();
1453    }
1454
1455    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1456        let was_dirty = self.is_dirty();
1457        let old_version = self.version.clone();
1458
1459        if let Some((transaction_id, operation)) = self.text.undo() {
1460            self.send_operation(Operation::Buffer(operation), cx);
1461            self.did_edit(&old_version, was_dirty, cx);
1462            Some(transaction_id)
1463        } else {
1464            None
1465        }
1466    }
1467
1468    pub fn undo_transaction(
1469        &mut self,
1470        transaction_id: TransactionId,
1471        cx: &mut ModelContext<Self>,
1472    ) -> bool {
1473        let was_dirty = self.is_dirty();
1474        let old_version = self.version.clone();
1475
1476        if let Some(operation) = self.text.undo_transaction(transaction_id) {
1477            self.send_operation(Operation::Buffer(operation), cx);
1478            self.did_edit(&old_version, was_dirty, cx);
1479            true
1480        } else {
1481            false
1482        }
1483    }
1484
1485    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1486        let was_dirty = self.is_dirty();
1487        let old_version = self.version.clone();
1488
1489        if let Some((transaction_id, operation)) = self.text.redo() {
1490            self.send_operation(Operation::Buffer(operation), cx);
1491            self.did_edit(&old_version, was_dirty, cx);
1492            Some(transaction_id)
1493        } else {
1494            None
1495        }
1496    }
1497
1498    pub fn redo_transaction(
1499        &mut self,
1500        transaction_id: TransactionId,
1501        cx: &mut ModelContext<Self>,
1502    ) -> bool {
1503        let was_dirty = self.is_dirty();
1504        let old_version = self.version.clone();
1505
1506        if let Some(operation) = self.text.redo_transaction(transaction_id) {
1507            self.send_operation(Operation::Buffer(operation), cx);
1508            self.did_edit(&old_version, was_dirty, cx);
1509            true
1510        } else {
1511            false
1512        }
1513    }
1514}
1515
1516#[cfg(any(test, feature = "test-support"))]
1517impl Buffer {
1518    pub fn set_group_interval(&mut self, group_interval: Duration) {
1519        self.text.set_group_interval(group_interval);
1520    }
1521
1522    pub fn randomly_edit<T>(
1523        &mut self,
1524        rng: &mut T,
1525        old_range_count: usize,
1526        cx: &mut ModelContext<Self>,
1527    ) where
1528        T: rand::Rng,
1529    {
1530        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1531        for _ in 0..old_range_count {
1532            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1533            if last_end > self.len() {
1534                break;
1535            }
1536            old_ranges.push(self.text.random_byte_range(last_end, rng));
1537        }
1538        let new_text_len = rng.gen_range(0..10);
1539        let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1540            .take(new_text_len)
1541            .collect();
1542        log::info!(
1543            "mutating buffer {} at {:?}: {:?}",
1544            self.replica_id(),
1545            old_ranges,
1546            new_text
1547        );
1548        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1549    }
1550
1551    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1552        let was_dirty = self.is_dirty();
1553        let old_version = self.version.clone();
1554
1555        let ops = self.text.randomly_undo_redo(rng);
1556        if !ops.is_empty() {
1557            for op in ops {
1558                self.send_operation(Operation::Buffer(op), cx);
1559                self.did_edit(&old_version, was_dirty, cx);
1560            }
1561        }
1562    }
1563}
1564
1565impl Entity for Buffer {
1566    type Event = Event;
1567
1568    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1569        if let Some(file) = self.file.as_ref() {
1570            file.buffer_removed(self.remote_id(), cx);
1571        }
1572    }
1573}
1574
1575impl Deref for Buffer {
1576    type Target = TextBuffer;
1577
1578    fn deref(&self) -> &Self::Target {
1579        &self.text
1580    }
1581}
1582
1583impl BufferSnapshot {
1584    fn suggest_autoindents<'a>(
1585        &'a self,
1586        row_range: Range<u32>,
1587    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1588        let mut query_cursor = QueryCursorHandle::new();
1589        if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1590            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1591
1592            // Get the "indentation ranges" that intersect this row range.
1593            let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
1594            let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
1595            query_cursor.set_point_range(
1596                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1597                    ..Point::new(row_range.end, 0).to_ts_point(),
1598            );
1599            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1600            for mat in query_cursor.matches(
1601                &grammar.indents_query,
1602                tree.root_node(),
1603                TextProvider(self.as_rope()),
1604            ) {
1605                let mut node_kind = "";
1606                let mut start: Option<Point> = None;
1607                let mut end: Option<Point> = None;
1608                for capture in mat.captures {
1609                    if Some(capture.index) == indent_capture_ix {
1610                        node_kind = capture.node.kind();
1611                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1612                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1613                    } else if Some(capture.index) == end_capture_ix {
1614                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1615                    }
1616                }
1617
1618                if let Some((start, end)) = start.zip(end) {
1619                    if start.row == end.row {
1620                        continue;
1621                    }
1622
1623                    let range = start..end;
1624                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1625                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1626                        Ok(ix) => {
1627                            let prev_range = &mut indentation_ranges[ix];
1628                            prev_range.0.end = prev_range.0.end.max(range.end);
1629                        }
1630                    }
1631                }
1632            }
1633
1634            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1635            Some(row_range.map(move |row| {
1636                let row_start = Point::new(row, self.indent_column_for_line(row));
1637
1638                let mut indent_from_prev_row = false;
1639                let mut outdent_to_row = u32::MAX;
1640                for (range, _node_kind) in &indentation_ranges {
1641                    if range.start.row >= row {
1642                        break;
1643                    }
1644
1645                    if range.start.row == prev_row && range.end > row_start {
1646                        indent_from_prev_row = true;
1647                    }
1648                    if range.end.row >= prev_row && range.end <= row_start {
1649                        outdent_to_row = outdent_to_row.min(range.start.row);
1650                    }
1651                }
1652
1653                let suggestion = if outdent_to_row == prev_row {
1654                    IndentSuggestion {
1655                        basis_row: prev_row,
1656                        indent: false,
1657                    }
1658                } else if indent_from_prev_row {
1659                    IndentSuggestion {
1660                        basis_row: prev_row,
1661                        indent: true,
1662                    }
1663                } else if outdent_to_row < prev_row {
1664                    IndentSuggestion {
1665                        basis_row: outdent_to_row,
1666                        indent: false,
1667                    }
1668                } else {
1669                    IndentSuggestion {
1670                        basis_row: prev_row,
1671                        indent: false,
1672                    }
1673                };
1674
1675                prev_row = row;
1676                suggestion
1677            }))
1678        } else {
1679            None
1680        }
1681    }
1682
1683    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1684        while row > 0 {
1685            row -= 1;
1686            if !self.is_line_blank(row) {
1687                return Some(row);
1688            }
1689        }
1690        None
1691    }
1692
1693    pub fn chunks<'a, T: ToOffset>(
1694        &'a self,
1695        range: Range<T>,
1696        theme: Option<&'a SyntaxTheme>,
1697    ) -> BufferChunks<'a> {
1698        let range = range.start.to_offset(self)..range.end.to_offset(self);
1699
1700        let mut highlights = None;
1701        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1702        if let Some(theme) = theme {
1703            for (_, entry) in self.diagnostics_in_range::<_, usize>(range.clone()) {
1704                diagnostic_endpoints.push(DiagnosticEndpoint {
1705                    offset: entry.range.start,
1706                    is_start: true,
1707                    severity: entry.diagnostic.severity,
1708                });
1709                diagnostic_endpoints.push(DiagnosticEndpoint {
1710                    offset: entry.range.end,
1711                    is_start: false,
1712                    severity: entry.diagnostic.severity,
1713                });
1714            }
1715            diagnostic_endpoints
1716                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1717
1718            if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1719                let mut query_cursor = QueryCursorHandle::new();
1720
1721                // TODO - add a Tree-sitter API to remove the need for this.
1722                let cursor = unsafe {
1723                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1724                };
1725                let captures = cursor.set_byte_range(range.clone()).captures(
1726                    &grammar.highlights_query,
1727                    tree.root_node(),
1728                    TextProvider(self.text.as_rope()),
1729                );
1730                highlights = Some(BufferChunkHighlights {
1731                    captures,
1732                    next_capture: None,
1733                    stack: Default::default(),
1734                    highlight_map: grammar.highlight_map(),
1735                    _query_cursor: query_cursor,
1736                    theme,
1737                })
1738            }
1739        }
1740
1741        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1742        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1743
1744        BufferChunks {
1745            range,
1746            chunks,
1747            diagnostic_endpoints,
1748            error_depth: 0,
1749            warning_depth: 0,
1750            information_depth: 0,
1751            hint_depth: 0,
1752            highlights,
1753        }
1754    }
1755
1756    pub fn language(&self) -> Option<&Arc<Language>> {
1757        self.language.as_ref()
1758    }
1759
1760    fn grammar(&self) -> Option<&Arc<Grammar>> {
1761        self.language
1762            .as_ref()
1763            .and_then(|language| language.grammar.as_ref())
1764    }
1765
1766    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1767        if let Some(tree) = self.tree.as_ref() {
1768            let root = tree.root_node();
1769            let range = range.start.to_offset(self)..range.end.to_offset(self);
1770            let mut node = root.descendant_for_byte_range(range.start, range.end);
1771            while node.map_or(false, |n| n.byte_range() == range) {
1772                node = node.unwrap().parent();
1773            }
1774            node.map(|n| n.byte_range())
1775        } else {
1776            None
1777        }
1778    }
1779
1780    pub fn enclosing_bracket_ranges<T: ToOffset>(
1781        &self,
1782        range: Range<T>,
1783    ) -> Option<(Range<usize>, Range<usize>)> {
1784        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
1785        let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
1786        let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
1787
1788        // Find bracket pairs that *inclusively* contain the given range.
1789        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1790        let mut cursor = QueryCursorHandle::new();
1791        let matches = cursor.set_byte_range(range).matches(
1792            &grammar.brackets_query,
1793            tree.root_node(),
1794            TextProvider(self.as_rope()),
1795        );
1796
1797        // Get the ranges of the innermost pair of brackets.
1798        matches
1799            .filter_map(|mat| {
1800                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1801                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1802                Some((open.byte_range(), close.byte_range()))
1803            })
1804            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1805    }
1806
1807    pub fn remote_selections_in_range<'a>(
1808        &'a self,
1809        range: Range<Anchor>,
1810    ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
1811    {
1812        self.remote_selections
1813            .iter()
1814            .filter(|(replica_id, _)| **replica_id != self.text.replica_id())
1815            .map(move |(replica_id, selections)| {
1816                let start_ix = match selections
1817                    .binary_search_by(|probe| probe.end.cmp(&range.start, self).unwrap())
1818                {
1819                    Ok(ix) | Err(ix) => ix,
1820                };
1821                let end_ix = match selections
1822                    .binary_search_by(|probe| probe.start.cmp(&range.end, self).unwrap())
1823                {
1824                    Ok(ix) | Err(ix) => ix,
1825                };
1826
1827                (*replica_id, selections[start_ix..end_ix].iter())
1828            })
1829    }
1830
1831    pub fn diagnostics_in_range<'a, T, O>(
1832        &'a self,
1833        search_range: Range<T>,
1834    ) -> impl 'a + Iterator<Item = (&'a str, DiagnosticEntry<O>)>
1835    where
1836        T: 'a + Clone + ToOffset,
1837        O: 'a + FromAnchor,
1838    {
1839        self.diagnostic_sets.iter().flat_map(move |set| {
1840            set.range(search_range.clone(), self, true)
1841                .map(|e| (set.provider_name(), e))
1842        })
1843    }
1844
1845    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
1846        let mut groups = Vec::new();
1847        for set in &self.diagnostic_sets {
1848            set.groups(&mut groups, self);
1849        }
1850        groups
1851    }
1852
1853    pub fn diagnostic_group<'a, O>(
1854        &'a self,
1855        provider_name: &str,
1856        group_id: usize,
1857    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1858    where
1859        O: 'a + FromAnchor,
1860    {
1861        self.diagnostic_sets
1862            .iter()
1863            .find(|s| s.provider_name() == provider_name)
1864            .into_iter()
1865            .flat_map(move |s| s.group(group_id, self))
1866    }
1867
1868    pub fn diagnostics_update_count(&self) -> usize {
1869        self.diagnostics_update_count
1870    }
1871
1872    pub fn parse_count(&self) -> usize {
1873        self.parse_count
1874    }
1875
1876    pub fn selections_update_count(&self) -> usize {
1877        self.selections_update_count
1878    }
1879}
1880
1881impl Clone for BufferSnapshot {
1882    fn clone(&self) -> Self {
1883        Self {
1884            text: self.text.clone(),
1885            tree: self.tree.clone(),
1886            remote_selections: self.remote_selections.clone(),
1887            selections_update_count: self.selections_update_count,
1888            diagnostic_sets: self.diagnostic_sets.clone(),
1889            diagnostics_update_count: self.diagnostics_update_count,
1890            is_parsing: self.is_parsing,
1891            language: self.language.clone(),
1892            parse_count: self.parse_count,
1893        }
1894    }
1895}
1896
1897impl Deref for BufferSnapshot {
1898    type Target = text::BufferSnapshot;
1899
1900    fn deref(&self) -> &Self::Target {
1901        &self.text
1902    }
1903}
1904
1905impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1906    type I = ByteChunks<'a>;
1907
1908    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1909        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1910    }
1911}
1912
1913struct ByteChunks<'a>(rope::Chunks<'a>);
1914
1915impl<'a> Iterator for ByteChunks<'a> {
1916    type Item = &'a [u8];
1917
1918    fn next(&mut self) -> Option<Self::Item> {
1919        self.0.next().map(str::as_bytes)
1920    }
1921}
1922
1923unsafe impl<'a> Send for BufferChunks<'a> {}
1924
1925impl<'a> BufferChunks<'a> {
1926    pub fn seek(&mut self, offset: usize) {
1927        self.range.start = offset;
1928        self.chunks.seek(self.range.start);
1929        if let Some(highlights) = self.highlights.as_mut() {
1930            highlights
1931                .stack
1932                .retain(|(end_offset, _)| *end_offset > offset);
1933            if let Some((mat, capture_ix)) = &highlights.next_capture {
1934                let capture = mat.captures[*capture_ix as usize];
1935                if offset >= capture.node.start_byte() {
1936                    let next_capture_end = capture.node.end_byte();
1937                    if offset < next_capture_end {
1938                        highlights.stack.push((
1939                            next_capture_end,
1940                            highlights.highlight_map.get(capture.index),
1941                        ));
1942                    }
1943                    highlights.next_capture.take();
1944                }
1945            }
1946            highlights.captures.set_byte_range(self.range.clone());
1947        }
1948    }
1949
1950    pub fn offset(&self) -> usize {
1951        self.range.start
1952    }
1953
1954    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1955        let depth = match endpoint.severity {
1956            DiagnosticSeverity::ERROR => &mut self.error_depth,
1957            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1958            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1959            DiagnosticSeverity::HINT => &mut self.hint_depth,
1960            _ => return,
1961        };
1962        if endpoint.is_start {
1963            *depth += 1;
1964        } else {
1965            *depth -= 1;
1966        }
1967    }
1968
1969    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1970        if self.error_depth > 0 {
1971            Some(DiagnosticSeverity::ERROR)
1972        } else if self.warning_depth > 0 {
1973            Some(DiagnosticSeverity::WARNING)
1974        } else if self.information_depth > 0 {
1975            Some(DiagnosticSeverity::INFORMATION)
1976        } else if self.hint_depth > 0 {
1977            Some(DiagnosticSeverity::HINT)
1978        } else {
1979            None
1980        }
1981    }
1982}
1983
1984impl<'a> Iterator for BufferChunks<'a> {
1985    type Item = Chunk<'a>;
1986
1987    fn next(&mut self) -> Option<Self::Item> {
1988        let mut next_capture_start = usize::MAX;
1989        let mut next_diagnostic_endpoint = usize::MAX;
1990
1991        if let Some(highlights) = self.highlights.as_mut() {
1992            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1993                if *parent_capture_end <= self.range.start {
1994                    highlights.stack.pop();
1995                } else {
1996                    break;
1997                }
1998            }
1999
2000            if highlights.next_capture.is_none() {
2001                highlights.next_capture = highlights.captures.next();
2002            }
2003
2004            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2005                let capture = mat.captures[*capture_ix as usize];
2006                if self.range.start < capture.node.start_byte() {
2007                    next_capture_start = capture.node.start_byte();
2008                    break;
2009                } else {
2010                    let highlight_id = highlights.highlight_map.get(capture.index);
2011                    highlights
2012                        .stack
2013                        .push((capture.node.end_byte(), highlight_id));
2014                    highlights.next_capture = highlights.captures.next();
2015                }
2016            }
2017        }
2018
2019        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2020            if endpoint.offset <= self.range.start {
2021                self.update_diagnostic_depths(endpoint);
2022                self.diagnostic_endpoints.next();
2023            } else {
2024                next_diagnostic_endpoint = endpoint.offset;
2025                break;
2026            }
2027        }
2028
2029        if let Some(chunk) = self.chunks.peek() {
2030            let chunk_start = self.range.start;
2031            let mut chunk_end = (self.chunks.offset() + chunk.len())
2032                .min(next_capture_start)
2033                .min(next_diagnostic_endpoint);
2034            let mut highlight_style = None;
2035            if let Some(highlights) = self.highlights.as_ref() {
2036                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2037                    chunk_end = chunk_end.min(*parent_capture_end);
2038                    highlight_style = parent_highlight_id.style(highlights.theme);
2039                }
2040            }
2041
2042            let slice =
2043                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2044            self.range.start = chunk_end;
2045            if self.range.start == self.chunks.offset() + chunk.len() {
2046                self.chunks.next().unwrap();
2047            }
2048
2049            Some(Chunk {
2050                text: slice,
2051                highlight_style,
2052                diagnostic: self.current_diagnostic_severity(),
2053            })
2054        } else {
2055            None
2056        }
2057    }
2058}
2059
2060impl QueryCursorHandle {
2061    fn new() -> Self {
2062        QueryCursorHandle(Some(
2063            QUERY_CURSORS
2064                .lock()
2065                .pop()
2066                .unwrap_or_else(|| QueryCursor::new()),
2067        ))
2068    }
2069}
2070
2071impl Deref for QueryCursorHandle {
2072    type Target = QueryCursor;
2073
2074    fn deref(&self) -> &Self::Target {
2075        self.0.as_ref().unwrap()
2076    }
2077}
2078
2079impl DerefMut for QueryCursorHandle {
2080    fn deref_mut(&mut self) -> &mut Self::Target {
2081        self.0.as_mut().unwrap()
2082    }
2083}
2084
2085impl Drop for QueryCursorHandle {
2086    fn drop(&mut self) {
2087        let mut cursor = self.0.take().unwrap();
2088        cursor.set_byte_range(0..usize::MAX);
2089        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2090        QUERY_CURSORS.lock().push(cursor)
2091    }
2092}
2093
2094trait ToTreeSitterPoint {
2095    fn to_ts_point(self) -> tree_sitter::Point;
2096    fn from_ts_point(point: tree_sitter::Point) -> Self;
2097}
2098
2099impl ToTreeSitterPoint for Point {
2100    fn to_ts_point(self) -> tree_sitter::Point {
2101        tree_sitter::Point::new(self.row as usize, self.column as usize)
2102    }
2103
2104    fn from_ts_point(point: tree_sitter::Point) -> Self {
2105        Point::new(point.row as u32, point.column as u32)
2106    }
2107}
2108
2109impl operation_queue::Operation for Operation {
2110    fn lamport_timestamp(&self) -> clock::Lamport {
2111        match self {
2112            Operation::Buffer(_) => {
2113                unreachable!("buffer operations should never be deferred at this layer")
2114            }
2115            Operation::UpdateDiagnostics {
2116                lamport_timestamp, ..
2117            }
2118            | Operation::UpdateSelections {
2119                lamport_timestamp, ..
2120            }
2121            | Operation::RemoveSelections {
2122                lamport_timestamp, ..
2123            } => *lamport_timestamp,
2124        }
2125    }
2126}
2127
2128impl Default for Diagnostic {
2129    fn default() -> Self {
2130        Self {
2131            code: Default::default(),
2132            severity: DiagnosticSeverity::ERROR,
2133            message: Default::default(),
2134            group_id: Default::default(),
2135            is_primary: Default::default(),
2136            is_valid: true,
2137            is_disk_based: false,
2138        }
2139    }
2140}
2141
2142pub fn contiguous_ranges(
2143    values: impl Iterator<Item = u32>,
2144    max_len: usize,
2145) -> impl Iterator<Item = Range<u32>> {
2146    let mut values = values.into_iter();
2147    let mut current_range: Option<Range<u32>> = None;
2148    std::iter::from_fn(move || loop {
2149        if let Some(value) = values.next() {
2150            if let Some(range) = &mut current_range {
2151                if value == range.end && range.len() < max_len {
2152                    range.end += 1;
2153                    continue;
2154                }
2155            }
2156
2157            let prev_range = current_range.clone();
2158            current_range = Some(value..(value + 1));
2159            if prev_range.is_some() {
2160                return prev_range;
2161            }
2162        } else {
2163            return current_range.take();
2164        }
2165    })
2166}