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