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