buffer.rs

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