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