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