buffer.rs

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