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    diagnostics_timestamp: clock::Lamport,
  72    file_update_count: usize,
  73    language_server: Option<LanguageServerState>,
  74    completion_triggers: Vec<String>,
  75    deferred_ops: OperationQueue<Operation>,
  76}
  77
  78pub struct BufferSnapshot {
  79    text: text::BufferSnapshot,
  80    tree: Option<Tree>,
  81    path: Option<Arc<Path>>,
  82    diagnostics: DiagnosticSet,
  83    diagnostics_update_count: usize,
  84    file_update_count: usize,
  85    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  86    selections_update_count: usize,
  87    is_parsing: bool,
  88    language: Option<Arc<Language>>,
  89    parse_count: usize,
  90}
  91
  92#[derive(Clone, Debug)]
  93struct SelectionSet {
  94    selections: Arc<[Selection<Anchor>]>,
  95    lamport_timestamp: clock::Lamport,
  96}
  97
  98#[derive(Clone, Debug, PartialEq, Eq)]
  99pub struct GroupId {
 100    source: Arc<str>,
 101    id: usize,
 102}
 103
 104#[derive(Clone, Debug, PartialEq, Eq)]
 105pub struct Diagnostic {
 106    pub code: Option<String>,
 107    pub severity: DiagnosticSeverity,
 108    pub message: String,
 109    pub group_id: usize,
 110    pub is_valid: bool,
 111    pub is_primary: bool,
 112    pub is_disk_based: bool,
 113}
 114
 115#[derive(Clone, Debug)]
 116pub struct Completion {
 117    pub old_range: Range<Anchor>,
 118    pub new_text: String,
 119    pub label: CodeLabel,
 120    pub lsp_completion: lsp::CompletionItem,
 121}
 122
 123#[derive(Clone, Debug)]
 124pub struct CodeAction {
 125    pub range: Range<Anchor>,
 126    pub lsp_action: lsp::CodeAction,
 127}
 128
 129struct LanguageServerState {
 130    server: Arc<LanguageServer>,
 131    latest_snapshot: watch::Sender<LanguageServerSnapshot>,
 132    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
 133    next_version: usize,
 134    _maintain_server: Task<Option<()>>,
 135}
 136
 137#[derive(Clone)]
 138struct LanguageServerSnapshot {
 139    buffer_snapshot: text::BufferSnapshot,
 140    version: usize,
 141    path: Arc<Path>,
 142}
 143
 144#[derive(Clone, Debug, PartialEq, Eq)]
 145pub enum Operation {
 146    Buffer(text::Operation),
 147    UpdateDiagnostics {
 148        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 149        lamport_timestamp: clock::Lamport,
 150    },
 151    UpdateSelections {
 152        selections: Arc<[Selection<Anchor>]>,
 153        lamport_timestamp: clock::Lamport,
 154    },
 155    UpdateCompletionTriggers {
 156        triggers: Vec<String>,
 157        lamport_timestamp: clock::Lamport,
 158    },
 159}
 160
 161#[derive(Clone, Debug, PartialEq, Eq)]
 162pub enum Event {
 163    Operation(Operation),
 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 as_any(&self) -> &dyn Any;
 205
 206    fn to_proto(&self) -> rpc::proto::File;
 207}
 208
 209pub trait LocalFile: File {
 210    /// Returns the absolute path of this file.
 211    fn abs_path(&self, cx: &AppContext) -> PathBuf;
 212
 213    fn load(&self, cx: &AppContext) -> Task<Result<String>>;
 214
 215    fn buffer_reloaded(
 216        &self,
 217        buffer_id: u64,
 218        version: &clock::Global,
 219        mtime: SystemTime,
 220        cx: &mut MutableAppContext,
 221    );
 222}
 223
 224#[cfg(any(test, feature = "test-support"))]
 225pub struct FakeFile {
 226    pub path: Arc<Path>,
 227}
 228
 229#[cfg(any(test, feature = "test-support"))]
 230impl FakeFile {
 231    pub fn new(path: impl AsRef<Path>) -> Self {
 232        Self {
 233            path: path.as_ref().into(),
 234        }
 235    }
 236}
 237
 238#[cfg(any(test, feature = "test-support"))]
 239impl File for FakeFile {
 240    fn as_local(&self) -> Option<&dyn LocalFile> {
 241        Some(self)
 242    }
 243
 244    fn mtime(&self) -> SystemTime {
 245        SystemTime::UNIX_EPOCH
 246    }
 247
 248    fn path(&self) -> &Arc<Path> {
 249        &self.path
 250    }
 251
 252    fn full_path(&self, _: &AppContext) -> PathBuf {
 253        self.path.to_path_buf()
 254    }
 255
 256    fn file_name(&self, _: &AppContext) -> OsString {
 257        self.path.file_name().unwrap().to_os_string()
 258    }
 259
 260    fn is_deleted(&self) -> bool {
 261        false
 262    }
 263
 264    fn save(
 265        &self,
 266        _: u64,
 267        _: Rope,
 268        _: clock::Global,
 269        cx: &mut MutableAppContext,
 270    ) -> Task<Result<(clock::Global, SystemTime)>> {
 271        cx.spawn(|_| async move { Ok((Default::default(), SystemTime::UNIX_EPOCH)) })
 272    }
 273
 274    fn as_any(&self) -> &dyn Any {
 275        self
 276    }
 277
 278    fn to_proto(&self) -> rpc::proto::File {
 279        unimplemented!()
 280    }
 281}
 282
 283#[cfg(any(test, feature = "test-support"))]
 284impl LocalFile for FakeFile {
 285    fn abs_path(&self, _: &AppContext) -> PathBuf {
 286        self.path.to_path_buf()
 287    }
 288
 289    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
 290        cx.background().spawn(async move { Ok(Default::default()) })
 291    }
 292
 293    fn buffer_reloaded(&self, _: u64, _: &clock::Global, _: SystemTime, _: &mut MutableAppContext) {
 294    }
 295}
 296
 297pub(crate) struct QueryCursorHandle(Option<QueryCursor>);
 298
 299#[derive(Clone)]
 300struct SyntaxTree {
 301    tree: Tree,
 302    version: clock::Global,
 303}
 304
 305#[derive(Clone)]
 306struct AutoindentRequest {
 307    before_edit: BufferSnapshot,
 308    edited: Vec<Anchor>,
 309    inserted: Option<Vec<Range<Anchor>>>,
 310}
 311
 312#[derive(Debug)]
 313struct IndentSuggestion {
 314    basis_row: u32,
 315    indent: bool,
 316}
 317
 318pub(crate) struct TextProvider<'a>(pub(crate) &'a Rope);
 319
 320struct BufferChunkHighlights<'a> {
 321    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 322    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 323    stack: Vec<(usize, HighlightId)>,
 324    highlight_map: HighlightMap,
 325    _query_cursor: QueryCursorHandle,
 326}
 327
 328pub struct BufferChunks<'a> {
 329    range: Range<usize>,
 330    chunks: rope::Chunks<'a>,
 331    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 332    error_depth: usize,
 333    warning_depth: usize,
 334    information_depth: usize,
 335    hint_depth: usize,
 336    highlights: Option<BufferChunkHighlights<'a>>,
 337}
 338
 339#[derive(Clone, Copy, Debug, Default)]
 340pub struct Chunk<'a> {
 341    pub text: &'a str,
 342    pub highlight_id: Option<HighlightId>,
 343    pub diagnostic: Option<DiagnosticSeverity>,
 344}
 345
 346pub(crate) struct Diff {
 347    base_version: clock::Global,
 348    new_text: Arc<str>,
 349    changes: Vec<(ChangeTag, usize)>,
 350    start_offset: usize,
 351}
 352
 353#[derive(Clone, Copy)]
 354pub(crate) struct DiagnosticEndpoint {
 355    offset: usize,
 356    is_start: bool,
 357    severity: DiagnosticSeverity,
 358}
 359
 360#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
 361pub enum CharKind {
 362    Newline,
 363    Punctuation,
 364    Whitespace,
 365    Word,
 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            let lamport_timestamp = clock::Lamport {
 421                replica_id: selection_set.replica_id as ReplicaId,
 422                value: selection_set.lamport_timestamp,
 423            };
 424            this.remote_selections.insert(
 425                selection_set.replica_id as ReplicaId,
 426                SelectionSet {
 427                    selections: proto::deserialize_selections(selection_set.selections),
 428                    lamport_timestamp,
 429                },
 430            );
 431            this.text.lamport_clock.observe(lamport_timestamp);
 432        }
 433        let snapshot = this.snapshot();
 434        let entries = proto::deserialize_diagnostics(message.diagnostics);
 435        this.apply_diagnostic_update(
 436            DiagnosticSet::from_sorted_entries(entries.iter().cloned(), &snapshot),
 437            clock::Lamport {
 438                replica_id: 0,
 439                value: message.diagnostics_timestamp,
 440            },
 441            cx,
 442        );
 443
 444        this.completion_triggers = message.completion_triggers;
 445
 446        Ok(this)
 447    }
 448
 449    pub fn to_proto(&self) -> proto::BufferState {
 450        let mut operations = self
 451            .text
 452            .history()
 453            .map(|op| proto::serialize_operation(&Operation::Buffer(op.clone())))
 454            .chain(self.deferred_ops.iter().map(proto::serialize_operation))
 455            .collect::<Vec<_>>();
 456        operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
 457        proto::BufferState {
 458            id: self.remote_id(),
 459            file: self.file.as_ref().map(|f| f.to_proto()),
 460            base_text: self.base_text().to_string(),
 461            operations,
 462            selections: self
 463                .remote_selections
 464                .iter()
 465                .map(|(replica_id, set)| proto::SelectionSet {
 466                    replica_id: *replica_id as u32,
 467                    selections: proto::serialize_selections(&set.selections),
 468                    lamport_timestamp: set.lamport_timestamp.value,
 469                })
 470                .collect(),
 471            diagnostics: proto::serialize_diagnostics(self.diagnostics.iter()),
 472            diagnostics_timestamp: self.diagnostics_timestamp.value,
 473            completion_triggers: self.completion_triggers.clone(),
 474        }
 475    }
 476
 477    pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
 478        self.set_language(Some(language), cx);
 479        self
 480    }
 481
 482    pub fn with_language_server(
 483        mut self,
 484        server: Arc<LanguageServer>,
 485        cx: &mut ModelContext<Self>,
 486    ) -> Self {
 487        self.set_language_server(Some(server), cx);
 488        self
 489    }
 490
 491    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 492        let saved_mtime;
 493        if let Some(file) = file.as_ref() {
 494            saved_mtime = file.mtime();
 495        } else {
 496            saved_mtime = UNIX_EPOCH;
 497        }
 498
 499        Self {
 500            saved_mtime,
 501            saved_version: buffer.version(),
 502            text: buffer,
 503            file,
 504            syntax_tree: Mutex::new(None),
 505            parsing_in_background: false,
 506            parse_count: 0,
 507            sync_parse_timeout: Duration::from_millis(1),
 508            autoindent_requests: Default::default(),
 509            pending_autoindent: Default::default(),
 510            language: None,
 511            remote_selections: Default::default(),
 512            selections_update_count: 0,
 513            diagnostics: Default::default(),
 514            diagnostics_update_count: 0,
 515            diagnostics_timestamp: Default::default(),
 516            file_update_count: 0,
 517            language_server: None,
 518            completion_triggers: Default::default(),
 519            deferred_ops: OperationQueue::new(),
 520        }
 521    }
 522
 523    pub fn snapshot(&self) -> BufferSnapshot {
 524        BufferSnapshot {
 525            text: self.text.snapshot(),
 526            tree: self.syntax_tree(),
 527            path: self.file.as_ref().map(|f| f.path().clone()),
 528            remote_selections: self.remote_selections.clone(),
 529            diagnostics: self.diagnostics.clone(),
 530            diagnostics_update_count: self.diagnostics_update_count,
 531            file_update_count: self.file_update_count,
 532            is_parsing: self.parsing_in_background,
 533            language: self.language.clone(),
 534            parse_count: self.parse_count,
 535            selections_update_count: self.selections_update_count,
 536        }
 537    }
 538
 539    pub fn file(&self) -> Option<&dyn File> {
 540        self.file.as_deref()
 541    }
 542
 543    pub fn save(
 544        &mut self,
 545        cx: &mut ModelContext<Self>,
 546    ) -> Task<Result<(clock::Global, SystemTime)>> {
 547        let file = if let Some(file) = self.file.as_ref() {
 548            file
 549        } else {
 550            return Task::ready(Err(anyhow!("buffer has no file")));
 551        };
 552        let text = self.as_rope().clone();
 553        let version = self.version();
 554        let save = file.save(self.remote_id(), text, version, cx.as_mut());
 555        cx.spawn(|this, mut cx| async move {
 556            let (version, mtime) = save.await?;
 557            this.update(&mut cx, |this, cx| {
 558                this.did_save(version.clone(), mtime, None, cx);
 559            });
 560            Ok((version, mtime))
 561        })
 562    }
 563
 564    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
 565        self.language = language;
 566        self.reparse(cx);
 567    }
 568
 569    pub fn set_language_server(
 570        &mut self,
 571        language_server: Option<Arc<lsp::LanguageServer>>,
 572        cx: &mut ModelContext<Self>,
 573    ) {
 574        self.language_server = if let Some((server, file)) =
 575            language_server.zip(self.file.as_ref().and_then(|f| f.as_local()))
 576        {
 577            let initial_snapshot = LanguageServerSnapshot {
 578                buffer_snapshot: self.text.snapshot(),
 579                version: 0,
 580                path: file.abs_path(cx).into(),
 581            };
 582            let (latest_snapshot_tx, mut latest_snapshot_rx) =
 583                watch::channel_with::<LanguageServerSnapshot>(initial_snapshot.clone());
 584
 585            Some(LanguageServerState {
 586                latest_snapshot: latest_snapshot_tx,
 587                pending_snapshots: BTreeMap::from_iter([(0, initial_snapshot)]),
 588                next_version: 1,
 589                server: server.clone(),
 590                _maintain_server: cx.spawn_weak(|this, mut cx| async move {
 591                    let capabilities = server.capabilities().await.or_else(|| {
 592                        log::info!("language server exited");
 593                        if let Some(this) = this.upgrade(&cx) {
 594                            this.update(&mut cx, |this, _| this.language_server = None);
 595                        }
 596                        None
 597                    })?;
 598
 599                    let triggers = capabilities
 600                        .completion_provider
 601                        .and_then(|c| c.trigger_characters)
 602                        .unwrap_or_default();
 603                    this.upgrade(&cx)?.update(&mut cx, |this, cx| {
 604                        let lamport_timestamp = this.text.lamport_clock.tick();
 605                        this.completion_triggers = triggers.clone();
 606                        this.send_operation(
 607                            Operation::UpdateCompletionTriggers {
 608                                triggers,
 609                                lamport_timestamp,
 610                            },
 611                            cx,
 612                        );
 613                        cx.notify();
 614                    });
 615
 616                    let maintain_changes = cx.background().spawn(async move {
 617                        let initial_snapshot =
 618                            latest_snapshot_rx.recv().await.ok_or_else(|| {
 619                                anyhow!("buffer dropped before sending DidOpenTextDocument")
 620                            })?;
 621                        server
 622                            .notify::<lsp::notification::DidOpenTextDocument>(
 623                                lsp::DidOpenTextDocumentParams {
 624                                    text_document: lsp::TextDocumentItem::new(
 625                                        lsp::Url::from_file_path(initial_snapshot.path).unwrap(),
 626                                        Default::default(),
 627                                        initial_snapshot.version as i32,
 628                                        initial_snapshot.buffer_snapshot.text(),
 629                                    ),
 630                                },
 631                            )
 632                            .await?;
 633
 634                        let mut prev_version = initial_snapshot.buffer_snapshot.version().clone();
 635                        while let Some(snapshot) = latest_snapshot_rx.recv().await {
 636                            let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
 637                            let buffer_snapshot = snapshot.buffer_snapshot.clone();
 638                            let content_changes = buffer_snapshot
 639                                .edits_since::<(PointUtf16, usize)>(&prev_version)
 640                                .map(|edit| {
 641                                    let edit_start = edit.new.start.0;
 642                                    let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 643                                    let new_text = buffer_snapshot
 644                                        .text_for_range(edit.new.start.1..edit.new.end.1)
 645                                        .collect();
 646                                    lsp::TextDocumentContentChangeEvent {
 647                                        range: Some(lsp::Range::new(
 648                                            edit_start.to_lsp_position(),
 649                                            edit_end.to_lsp_position(),
 650                                        )),
 651                                        range_length: None,
 652                                        text: new_text,
 653                                    }
 654                                })
 655                                .collect();
 656                            let changes = lsp::DidChangeTextDocumentParams {
 657                                text_document: lsp::VersionedTextDocumentIdentifier::new(
 658                                    uri,
 659                                    snapshot.version as i32,
 660                                ),
 661                                content_changes,
 662                            };
 663                            server
 664                                .notify::<lsp::notification::DidChangeTextDocument>(changes)
 665                                .await?;
 666
 667                            prev_version = snapshot.buffer_snapshot.version().clone();
 668                        }
 669
 670                        Ok::<_, anyhow::Error>(())
 671                    });
 672
 673                    maintain_changes.log_err().await
 674                }),
 675            })
 676        } else {
 677            None
 678        };
 679    }
 680
 681    pub fn did_save(
 682        &mut self,
 683        version: clock::Global,
 684        mtime: SystemTime,
 685        new_file: Option<Box<dyn File>>,
 686        cx: &mut ModelContext<Self>,
 687    ) {
 688        self.saved_mtime = mtime;
 689        self.saved_version = version;
 690        if let Some(new_file) = new_file {
 691            self.file = Some(new_file);
 692            self.file_update_count += 1;
 693        }
 694        cx.emit(Event::Saved);
 695        cx.notify();
 696    }
 697
 698    pub fn did_reload(
 699        &mut self,
 700        version: clock::Global,
 701        mtime: SystemTime,
 702        cx: &mut ModelContext<Self>,
 703    ) {
 704        self.saved_mtime = mtime;
 705        self.saved_version = version;
 706        if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
 707            file.buffer_reloaded(self.remote_id(), &self.saved_version, self.saved_mtime, cx);
 708        }
 709        cx.emit(Event::Reloaded);
 710        cx.notify();
 711    }
 712
 713    pub fn file_updated(
 714        &mut self,
 715        new_file: Box<dyn File>,
 716        cx: &mut ModelContext<Self>,
 717    ) -> Task<()> {
 718        let old_file = if let Some(file) = self.file.as_ref() {
 719            file
 720        } else {
 721            return Task::ready(());
 722        };
 723        let mut file_changed = false;
 724        let mut task = Task::ready(());
 725
 726        if new_file.path() != old_file.path() {
 727            file_changed = true;
 728        }
 729
 730        if new_file.is_deleted() {
 731            if !old_file.is_deleted() {
 732                file_changed = true;
 733                if !self.is_dirty() {
 734                    cx.emit(Event::Dirtied);
 735                }
 736            }
 737        } else {
 738            let new_mtime = new_file.mtime();
 739            if new_mtime != old_file.mtime() {
 740                file_changed = true;
 741
 742                if !self.is_dirty() {
 743                    task = cx.spawn(|this, mut cx| {
 744                        async move {
 745                            let new_text = this.read_with(&cx, |this, cx| {
 746                                this.file
 747                                    .as_ref()
 748                                    .and_then(|file| file.as_local().map(|f| f.load(cx)))
 749                            });
 750                            if let Some(new_text) = new_text {
 751                                let new_text = new_text.await?;
 752                                let diff = this
 753                                    .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
 754                                    .await;
 755                                this.update(&mut cx, |this, cx| {
 756                                    if this.apply_diff(diff, cx) {
 757                                        this.did_reload(this.version(), new_mtime, cx);
 758                                    }
 759                                });
 760                            }
 761                            Ok(())
 762                        }
 763                        .log_err()
 764                        .map(drop)
 765                    });
 766                }
 767            }
 768        }
 769
 770        if file_changed {
 771            self.file_update_count += 1;
 772            cx.emit(Event::FileHandleChanged);
 773            cx.notify();
 774        }
 775        self.file = Some(new_file);
 776        task
 777    }
 778
 779    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 780        cx.emit(Event::Closed);
 781    }
 782
 783    pub fn language(&self) -> Option<&Arc<Language>> {
 784        self.language.as_ref()
 785    }
 786
 787    pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
 788        self.language_server.as_ref().map(|state| &state.server)
 789    }
 790
 791    pub fn parse_count(&self) -> usize {
 792        self.parse_count
 793    }
 794
 795    pub fn selections_update_count(&self) -> usize {
 796        self.selections_update_count
 797    }
 798
 799    pub fn diagnostics_update_count(&self) -> usize {
 800        self.diagnostics_update_count
 801    }
 802
 803    pub fn file_update_count(&self) -> usize {
 804        self.file_update_count
 805    }
 806
 807    pub(crate) fn syntax_tree(&self) -> Option<Tree> {
 808        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 809            self.interpolate_tree(syntax_tree);
 810            Some(syntax_tree.tree.clone())
 811        } else {
 812            None
 813        }
 814    }
 815
 816    #[cfg(any(test, feature = "test-support"))]
 817    pub fn is_parsing(&self) -> bool {
 818        self.parsing_in_background
 819    }
 820
 821    #[cfg(test)]
 822    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 823        self.sync_parse_timeout = timeout;
 824    }
 825
 826    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 827        if self.parsing_in_background {
 828            return false;
 829        }
 830
 831        if let Some(grammar) = self.grammar().cloned() {
 832            let old_tree = self.syntax_tree();
 833            let text = self.as_rope().clone();
 834            let parsed_version = self.version();
 835            let parse_task = cx.background().spawn({
 836                let grammar = grammar.clone();
 837                async move { grammar.parse_text(&text, old_tree) }
 838            });
 839
 840            match cx
 841                .background()
 842                .block_with_timeout(self.sync_parse_timeout, parse_task)
 843            {
 844                Ok(new_tree) => {
 845                    self.did_finish_parsing(new_tree, parsed_version, cx);
 846                    return true;
 847                }
 848                Err(parse_task) => {
 849                    self.parsing_in_background = true;
 850                    cx.spawn(move |this, mut cx| async move {
 851                        let new_tree = parse_task.await;
 852                        this.update(&mut cx, move |this, cx| {
 853                            let grammar_changed = this
 854                                .grammar()
 855                                .map_or(true, |curr_grammar| !Arc::ptr_eq(&grammar, curr_grammar));
 856                            let parse_again =
 857                                this.version.changed_since(&parsed_version) || grammar_changed;
 858                            this.parsing_in_background = false;
 859                            this.did_finish_parsing(new_tree, parsed_version, cx);
 860
 861                            if parse_again && this.reparse(cx) {
 862                                return;
 863                            }
 864                        });
 865                    })
 866                    .detach();
 867                }
 868            }
 869        }
 870        false
 871    }
 872
 873    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 874        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 875            let (bytes, lines) = edit.flatten();
 876            tree.tree.edit(&InputEdit {
 877                start_byte: bytes.new.start,
 878                old_end_byte: bytes.new.start + bytes.old.len(),
 879                new_end_byte: bytes.new.end,
 880                start_position: lines.new.start.to_ts_point(),
 881                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 882                    .to_ts_point(),
 883                new_end_position: lines.new.end.to_ts_point(),
 884            });
 885        }
 886        tree.version = self.version();
 887    }
 888
 889    fn did_finish_parsing(
 890        &mut self,
 891        tree: Tree,
 892        version: clock::Global,
 893        cx: &mut ModelContext<Self>,
 894    ) {
 895        self.parse_count += 1;
 896        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 897        self.request_autoindent(cx);
 898        cx.emit(Event::Reparsed);
 899        cx.notify();
 900    }
 901
 902    pub fn update_diagnostics<T>(
 903        &mut self,
 904        mut diagnostics: Vec<DiagnosticEntry<T>>,
 905        version: Option<i32>,
 906        cx: &mut ModelContext<Self>,
 907    ) -> Result<()>
 908    where
 909        T: Copy + Ord + TextDimension + Sub<Output = T> + Clip + ToPoint,
 910    {
 911        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 912            Ordering::Equal
 913                .then_with(|| b.is_primary.cmp(&a.is_primary))
 914                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 915                .then_with(|| a.severity.cmp(&b.severity))
 916                .then_with(|| a.message.cmp(&b.message))
 917        }
 918
 919        let version = version.map(|version| version as usize);
 920        let content =
 921            if let Some((version, language_server)) = version.zip(self.language_server.as_mut()) {
 922                language_server.snapshot_for_version(version)?
 923            } else {
 924                self.deref()
 925            };
 926
 927        diagnostics.sort_unstable_by(|a, b| {
 928            Ordering::Equal
 929                .then_with(|| a.range.start.cmp(&b.range.start))
 930                .then_with(|| b.range.end.cmp(&a.range.end))
 931                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 932        });
 933
 934        let mut sanitized_diagnostics = Vec::new();
 935        let mut edits_since_save = content.edits_since::<T>(&self.saved_version).peekable();
 936        let mut last_edit_old_end = T::default();
 937        let mut last_edit_new_end = T::default();
 938        'outer: for entry in diagnostics {
 939            let mut start = entry.range.start;
 940            let mut end = entry.range.end;
 941
 942            // Some diagnostics are based on files on disk instead of buffers'
 943            // current contents. Adjust these diagnostics' ranges to reflect
 944            // any unsaved edits.
 945            if entry.diagnostic.is_disk_based {
 946                while let Some(edit) = edits_since_save.peek() {
 947                    if edit.old.end <= start {
 948                        last_edit_old_end = edit.old.end;
 949                        last_edit_new_end = edit.new.end;
 950                        edits_since_save.next();
 951                    } else if edit.old.start <= end && edit.old.end >= start {
 952                        continue 'outer;
 953                    } else {
 954                        break;
 955                    }
 956                }
 957
 958                let start_overshoot = start - last_edit_old_end;
 959                start = last_edit_new_end;
 960                start.add_assign(&start_overshoot);
 961
 962                let end_overshoot = end - last_edit_old_end;
 963                end = last_edit_new_end;
 964                end.add_assign(&end_overshoot);
 965            }
 966
 967            let range = start.clip(Bias::Left, content)..end.clip(Bias::Right, content);
 968            let mut range = range.start.to_point(content)..range.end.to_point(content);
 969            // Expand empty ranges by one character
 970            if range.start == range.end {
 971                range.end.column += 1;
 972                range.end = content.clip_point(range.end, Bias::Right);
 973                if range.start == range.end && range.end.column > 0 {
 974                    range.start.column -= 1;
 975                    range.start = content.clip_point(range.start, Bias::Left);
 976                }
 977            }
 978
 979            sanitized_diagnostics.push(DiagnosticEntry {
 980                range,
 981                diagnostic: entry.diagnostic,
 982            });
 983        }
 984        drop(edits_since_save);
 985
 986        let set = DiagnosticSet::new(sanitized_diagnostics, content);
 987        let lamport_timestamp = self.text.lamport_clock.tick();
 988        self.apply_diagnostic_update(set.clone(), lamport_timestamp, cx);
 989
 990        let op = Operation::UpdateDiagnostics {
 991            diagnostics: set.iter().cloned().collect(),
 992            lamport_timestamp,
 993        };
 994        self.send_operation(op, cx);
 995        Ok(())
 996    }
 997
 998    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 999        if let Some(indent_columns) = self.compute_autoindents() {
1000            let indent_columns = cx.background().spawn(indent_columns);
1001            match cx
1002                .background()
1003                .block_with_timeout(Duration::from_micros(500), indent_columns)
1004            {
1005                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
1006                Err(indent_columns) => {
1007                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
1008                        let indent_columns = indent_columns.await;
1009                        this.update(&mut cx, |this, cx| {
1010                            this.apply_autoindents(indent_columns, cx);
1011                        });
1012                    }));
1013                }
1014            }
1015        }
1016    }
1017
1018    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
1019        let max_rows_between_yields = 100;
1020        let snapshot = self.snapshot();
1021        if snapshot.language.is_none()
1022            || snapshot.tree.is_none()
1023            || self.autoindent_requests.is_empty()
1024        {
1025            return None;
1026        }
1027
1028        let autoindent_requests = self.autoindent_requests.clone();
1029        Some(async move {
1030            let mut indent_columns = BTreeMap::new();
1031            for request in autoindent_requests {
1032                let old_to_new_rows = request
1033                    .edited
1034                    .iter()
1035                    .map(|anchor| anchor.summary::<Point>(&request.before_edit).row)
1036                    .zip(
1037                        request
1038                            .edited
1039                            .iter()
1040                            .map(|anchor| anchor.summary::<Point>(&snapshot).row),
1041                    )
1042                    .collect::<BTreeMap<u32, u32>>();
1043
1044                let mut old_suggestions = HashMap::<u32, u32>::default();
1045                let old_edited_ranges =
1046                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
1047                for old_edited_range in old_edited_ranges {
1048                    let suggestions = request
1049                        .before_edit
1050                        .suggest_autoindents(old_edited_range.clone())
1051                        .into_iter()
1052                        .flatten();
1053                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
1054                        let indentation_basis = old_to_new_rows
1055                            .get(&suggestion.basis_row)
1056                            .and_then(|from_row| old_suggestions.get(from_row).copied())
1057                            .unwrap_or_else(|| {
1058                                request
1059                                    .before_edit
1060                                    .indent_column_for_line(suggestion.basis_row)
1061                            });
1062                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1063                        old_suggestions.insert(
1064                            *old_to_new_rows.get(&old_row).unwrap(),
1065                            indentation_basis + delta,
1066                        );
1067                    }
1068                    yield_now().await;
1069                }
1070
1071                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
1072                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
1073                let new_edited_row_ranges =
1074                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
1075                for new_edited_row_range in new_edited_row_ranges {
1076                    let suggestions = snapshot
1077                        .suggest_autoindents(new_edited_row_range.clone())
1078                        .into_iter()
1079                        .flatten();
1080                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
1081                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1082                        let new_indentation = indent_columns
1083                            .get(&suggestion.basis_row)
1084                            .copied()
1085                            .unwrap_or_else(|| {
1086                                snapshot.indent_column_for_line(suggestion.basis_row)
1087                            })
1088                            + delta;
1089                        if old_suggestions
1090                            .get(&new_row)
1091                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
1092                        {
1093                            indent_columns.insert(new_row, new_indentation);
1094                        }
1095                    }
1096                    yield_now().await;
1097                }
1098
1099                if let Some(inserted) = request.inserted.as_ref() {
1100                    let inserted_row_ranges = contiguous_ranges(
1101                        inserted
1102                            .iter()
1103                            .map(|range| range.to_point(&snapshot))
1104                            .flat_map(|range| range.start.row..range.end.row + 1),
1105                        max_rows_between_yields,
1106                    );
1107                    for inserted_row_range in inserted_row_ranges {
1108                        let suggestions = snapshot
1109                            .suggest_autoindents(inserted_row_range.clone())
1110                            .into_iter()
1111                            .flatten();
1112                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
1113                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
1114                            let new_indentation = indent_columns
1115                                .get(&suggestion.basis_row)
1116                                .copied()
1117                                .unwrap_or_else(|| {
1118                                    snapshot.indent_column_for_line(suggestion.basis_row)
1119                                })
1120                                + delta;
1121                            indent_columns.insert(row, new_indentation);
1122                        }
1123                        yield_now().await;
1124                    }
1125                }
1126            }
1127            indent_columns
1128        })
1129    }
1130
1131    fn apply_autoindents(
1132        &mut self,
1133        indent_columns: BTreeMap<u32, u32>,
1134        cx: &mut ModelContext<Self>,
1135    ) {
1136        self.autoindent_requests.clear();
1137        self.start_transaction();
1138        for (row, indent_column) in &indent_columns {
1139            self.set_indent_column_for_line(*row, *indent_column, cx);
1140        }
1141        self.end_transaction(cx);
1142    }
1143
1144    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1145        let current_column = self.indent_column_for_line(row);
1146        if column > current_column {
1147            let offset = Point::new(row, 0).to_offset(&*self);
1148            self.edit(
1149                [offset..offset],
1150                " ".repeat((column - current_column) as usize),
1151                cx,
1152            );
1153        } else if column < current_column {
1154            self.edit(
1155                [Point::new(row, 0)..Point::new(row, current_column - column)],
1156                "",
1157                cx,
1158            );
1159        }
1160    }
1161
1162    pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1163        // TODO: it would be nice to not allocate here.
1164        let old_text = self.text();
1165        let base_version = self.version();
1166        cx.background().spawn(async move {
1167            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1168                .iter_all_changes()
1169                .map(|c| (c.tag(), c.value().len()))
1170                .collect::<Vec<_>>();
1171            Diff {
1172                base_version,
1173                new_text,
1174                changes,
1175                start_offset: 0,
1176            }
1177        })
1178    }
1179
1180    pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1181        if self.version == diff.base_version {
1182            self.start_transaction();
1183            let mut offset = diff.start_offset;
1184            for (tag, len) in diff.changes {
1185                let range = offset..(offset + len);
1186                match tag {
1187                    ChangeTag::Equal => offset += len,
1188                    ChangeTag::Delete => {
1189                        self.edit([range], "", cx);
1190                    }
1191                    ChangeTag::Insert => {
1192                        self.edit(
1193                            [offset..offset],
1194                            &diff.new_text
1195                                [range.start - diff.start_offset..range.end - diff.start_offset],
1196                            cx,
1197                        );
1198                        offset += len;
1199                    }
1200                }
1201            }
1202            self.end_transaction(cx);
1203            true
1204        } else {
1205            false
1206        }
1207    }
1208
1209    pub fn is_dirty(&self) -> bool {
1210        !self.saved_version.observed_all(&self.version)
1211            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1212    }
1213
1214    pub fn has_conflict(&self) -> bool {
1215        !self.saved_version.observed_all(&self.version)
1216            && self
1217                .file
1218                .as_ref()
1219                .map_or(false, |file| file.mtime() > self.saved_mtime)
1220    }
1221
1222    pub fn subscribe(&mut self) -> Subscription {
1223        self.text.subscribe()
1224    }
1225
1226    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1227        self.start_transaction_at(Instant::now())
1228    }
1229
1230    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1231        self.text.start_transaction_at(now)
1232    }
1233
1234    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1235        self.end_transaction_at(Instant::now(), cx)
1236    }
1237
1238    pub fn end_transaction_at(
1239        &mut self,
1240        now: Instant,
1241        cx: &mut ModelContext<Self>,
1242    ) -> Option<TransactionId> {
1243        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1244            let was_dirty = start_version != self.saved_version;
1245            self.did_edit(&start_version, was_dirty, cx);
1246            Some(transaction_id)
1247        } else {
1248            None
1249        }
1250    }
1251
1252    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1253        self.text.push_transaction(transaction, now);
1254    }
1255
1256    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1257        self.text.finalize_last_transaction()
1258    }
1259
1260    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1261        self.text.forget_transaction(transaction_id);
1262    }
1263
1264    pub fn wait_for_edits(
1265        &mut self,
1266        edit_ids: impl IntoIterator<Item = clock::Local>,
1267    ) -> impl Future<Output = ()> {
1268        self.text.wait_for_edits(edit_ids)
1269    }
1270
1271    pub fn wait_for_anchors<'a>(
1272        &mut self,
1273        anchors: impl IntoIterator<Item = &'a Anchor>,
1274    ) -> impl Future<Output = ()> {
1275        self.text.wait_for_anchors(anchors)
1276    }
1277
1278    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1279        self.text.wait_for_version(version)
1280    }
1281
1282    pub fn set_active_selections(
1283        &mut self,
1284        selections: Arc<[Selection<Anchor>]>,
1285        cx: &mut ModelContext<Self>,
1286    ) {
1287        let lamport_timestamp = self.text.lamport_clock.tick();
1288        self.remote_selections.insert(
1289            self.text.replica_id(),
1290            SelectionSet {
1291                selections: selections.clone(),
1292                lamport_timestamp,
1293            },
1294        );
1295        self.send_operation(
1296            Operation::UpdateSelections {
1297                selections,
1298                lamport_timestamp,
1299            },
1300            cx,
1301        );
1302    }
1303
1304    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1305        self.set_active_selections(Arc::from([]), cx);
1306    }
1307
1308    fn update_language_server(&mut self, cx: &AppContext) {
1309        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1310            language_server
1311        } else {
1312            return;
1313        };
1314        let file = if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
1315            file
1316        } else {
1317            return;
1318        };
1319
1320        let version = post_inc(&mut language_server.next_version);
1321        let snapshot = LanguageServerSnapshot {
1322            buffer_snapshot: self.text.snapshot(),
1323            version,
1324            path: Arc::from(file.abs_path(cx)),
1325        };
1326        language_server
1327            .pending_snapshots
1328            .insert(version, snapshot.clone());
1329        let _ = language_server.latest_snapshot.blocking_send(snapshot);
1330    }
1331
1332    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Local>
1333    where
1334        T: Into<String>,
1335    {
1336        self.edit_internal([0..self.len()], text, false, cx)
1337    }
1338
1339    pub fn edit<I, S, T>(
1340        &mut self,
1341        ranges_iter: I,
1342        new_text: T,
1343        cx: &mut ModelContext<Self>,
1344    ) -> Option<clock::Local>
1345    where
1346        I: IntoIterator<Item = Range<S>>,
1347        S: ToOffset,
1348        T: Into<String>,
1349    {
1350        self.edit_internal(ranges_iter, new_text, false, cx)
1351    }
1352
1353    pub fn edit_with_autoindent<I, S, T>(
1354        &mut self,
1355        ranges_iter: I,
1356        new_text: T,
1357        cx: &mut ModelContext<Self>,
1358    ) -> Option<clock::Local>
1359    where
1360        I: IntoIterator<Item = Range<S>>,
1361        S: ToOffset,
1362        T: Into<String>,
1363    {
1364        self.edit_internal(ranges_iter, new_text, true, cx)
1365    }
1366
1367    pub fn edit_internal<I, S, T>(
1368        &mut self,
1369        ranges_iter: I,
1370        new_text: T,
1371        autoindent: bool,
1372        cx: &mut ModelContext<Self>,
1373    ) -> Option<clock::Local>
1374    where
1375        I: IntoIterator<Item = Range<S>>,
1376        S: ToOffset,
1377        T: Into<String>,
1378    {
1379        let new_text = new_text.into();
1380
1381        // Skip invalid ranges and coalesce contiguous ones.
1382        let mut ranges: Vec<Range<usize>> = Vec::new();
1383        for range in ranges_iter {
1384            let range = range.start.to_offset(self)..range.end.to_offset(self);
1385            if !new_text.is_empty() || !range.is_empty() {
1386                if let Some(prev_range) = ranges.last_mut() {
1387                    if prev_range.end >= range.start {
1388                        prev_range.end = cmp::max(prev_range.end, range.end);
1389                    } else {
1390                        ranges.push(range);
1391                    }
1392                } else {
1393                    ranges.push(range);
1394                }
1395            }
1396        }
1397        if ranges.is_empty() {
1398            return None;
1399        }
1400
1401        self.start_transaction();
1402        self.pending_autoindent.take();
1403        let autoindent_request = if autoindent && self.language.is_some() {
1404            let before_edit = self.snapshot();
1405            let edited = ranges
1406                .iter()
1407                .filter_map(|range| {
1408                    let start = range.start.to_point(self);
1409                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1410                        None
1411                    } else {
1412                        Some(self.anchor_before(range.start))
1413                    }
1414                })
1415                .collect();
1416            Some((before_edit, edited))
1417        } else {
1418            None
1419        };
1420
1421        let first_newline_ix = new_text.find('\n');
1422        let new_text_len = new_text.len();
1423
1424        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1425        let edit_id = edit.local_timestamp();
1426
1427        if let Some((before_edit, edited)) = autoindent_request {
1428            let mut inserted = None;
1429            if let Some(first_newline_ix) = first_newline_ix {
1430                let mut delta = 0isize;
1431                inserted = Some(
1432                    ranges
1433                        .iter()
1434                        .map(|range| {
1435                            let start =
1436                                (delta + range.start as isize) as usize + first_newline_ix + 1;
1437                            let end = (delta + range.start as isize) as usize + new_text_len;
1438                            delta +=
1439                                (range.end as isize - range.start as isize) + new_text_len as isize;
1440                            self.anchor_before(start)..self.anchor_after(end)
1441                        })
1442                        .collect(),
1443                );
1444            }
1445
1446            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1447                before_edit,
1448                edited,
1449                inserted,
1450            }));
1451        }
1452
1453        self.end_transaction(cx);
1454        self.send_operation(Operation::Buffer(edit), cx);
1455        Some(edit_id)
1456    }
1457
1458    pub fn edits_from_lsp(
1459        &mut self,
1460        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
1461        version: Option<i32>,
1462        cx: &mut ModelContext<Self>,
1463    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
1464        let snapshot = if let Some((version, state)) = version.zip(self.language_server.as_mut()) {
1465            state
1466                .snapshot_for_version(version as usize)
1467                .map(Clone::clone)
1468        } else {
1469            Ok(TextBuffer::deref(self).clone())
1470        };
1471
1472        cx.background().spawn(async move {
1473            let snapshot = snapshot?;
1474            let mut lsp_edits = lsp_edits
1475                .into_iter()
1476                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
1477                .peekable();
1478
1479            let mut edits = Vec::new();
1480            while let Some((mut range, mut new_text)) = lsp_edits.next() {
1481                // Combine any LSP edits that are adjacent.
1482                //
1483                // Also, combine LSP edits that are separated from each other by only
1484                // a newline. This is important because for some code actions,
1485                // Rust-analyzer rewrites the entire buffer via a series of edits that
1486                // are separated by unchanged newline characters.
1487                //
1488                // In order for the diffing logic below to work properly, any edits that
1489                // cancel each other out must be combined into one.
1490                while let Some((next_range, next_text)) = lsp_edits.peek() {
1491                    if next_range.start > range.end {
1492                        if next_range.start.row > range.end.row + 1
1493                            || next_range.start.column > 0
1494                            || snapshot.clip_point_utf16(
1495                                PointUtf16::new(range.end.row, u32::MAX),
1496                                Bias::Left,
1497                            ) > range.end
1498                        {
1499                            break;
1500                        }
1501                        new_text.push('\n');
1502                    }
1503                    range.end = next_range.end;
1504                    new_text.push_str(&next_text);
1505                    lsp_edits.next();
1506                }
1507
1508                if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
1509                    || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
1510                {
1511                    return Err(anyhow!("invalid edits received from language server"));
1512                }
1513
1514                // For multiline edits, perform a diff of the old and new text so that
1515                // we can identify the changes more precisely, preserving the locations
1516                // of any anchors positioned in the unchanged regions.
1517                if range.end.row > range.start.row {
1518                    let mut offset = range.start.to_offset(&snapshot);
1519                    let old_text = snapshot.text_for_range(range).collect::<String>();
1520
1521                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
1522                    let mut moved_since_edit = true;
1523                    for change in diff.iter_all_changes() {
1524                        let tag = change.tag();
1525                        let value = change.value();
1526                        match tag {
1527                            ChangeTag::Equal => {
1528                                offset += value.len();
1529                                moved_since_edit = true;
1530                            }
1531                            ChangeTag::Delete => {
1532                                let start = snapshot.anchor_after(offset);
1533                                let end = snapshot.anchor_before(offset + value.len());
1534                                if moved_since_edit {
1535                                    edits.push((start..end, String::new()));
1536                                } else {
1537                                    edits.last_mut().unwrap().0.end = end;
1538                                }
1539                                offset += value.len();
1540                                moved_since_edit = false;
1541                            }
1542                            ChangeTag::Insert => {
1543                                if moved_since_edit {
1544                                    let anchor = snapshot.anchor_after(offset);
1545                                    edits.push((anchor.clone()..anchor, value.to_string()));
1546                                } else {
1547                                    edits.last_mut().unwrap().1.push_str(value);
1548                                }
1549                                moved_since_edit = false;
1550                            }
1551                        }
1552                    }
1553                } else if range.end == range.start {
1554                    let anchor = snapshot.anchor_after(range.start);
1555                    edits.push((anchor.clone()..anchor, new_text));
1556                } else {
1557                    let edit_start = snapshot.anchor_after(range.start);
1558                    let edit_end = snapshot.anchor_before(range.end);
1559                    edits.push((edit_start..edit_end, new_text));
1560                }
1561            }
1562
1563            Ok(edits)
1564        })
1565    }
1566
1567    fn did_edit(
1568        &mut self,
1569        old_version: &clock::Global,
1570        was_dirty: bool,
1571        cx: &mut ModelContext<Self>,
1572    ) {
1573        if self.edits_since::<usize>(old_version).next().is_none() {
1574            return;
1575        }
1576
1577        self.reparse(cx);
1578        self.update_language_server(cx);
1579
1580        cx.emit(Event::Edited);
1581        if !was_dirty {
1582            cx.emit(Event::Dirtied);
1583        }
1584        cx.notify();
1585    }
1586
1587    fn grammar(&self) -> Option<&Arc<Grammar>> {
1588        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1589    }
1590
1591    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1592        &mut self,
1593        ops: I,
1594        cx: &mut ModelContext<Self>,
1595    ) -> Result<()> {
1596        self.pending_autoindent.take();
1597        let was_dirty = self.is_dirty();
1598        let old_version = self.version.clone();
1599        let mut deferred_ops = Vec::new();
1600        let buffer_ops = ops
1601            .into_iter()
1602            .filter_map(|op| match op {
1603                Operation::Buffer(op) => Some(op),
1604                _ => {
1605                    if self.can_apply_op(&op) {
1606                        self.apply_op(op, cx);
1607                    } else {
1608                        deferred_ops.push(op);
1609                    }
1610                    None
1611                }
1612            })
1613            .collect::<Vec<_>>();
1614        self.text.apply_ops(buffer_ops)?;
1615        self.deferred_ops.insert(deferred_ops);
1616        self.flush_deferred_ops(cx);
1617        self.did_edit(&old_version, was_dirty, cx);
1618        // Notify independently of whether the buffer was edited as the operations could include a
1619        // selection update.
1620        cx.notify();
1621        Ok(())
1622    }
1623
1624    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1625        let mut deferred_ops = Vec::new();
1626        for op in self.deferred_ops.drain().iter().cloned() {
1627            if self.can_apply_op(&op) {
1628                self.apply_op(op, cx);
1629            } else {
1630                deferred_ops.push(op);
1631            }
1632        }
1633        self.deferred_ops.insert(deferred_ops);
1634    }
1635
1636    fn can_apply_op(&self, operation: &Operation) -> bool {
1637        match operation {
1638            Operation::Buffer(_) => {
1639                unreachable!("buffer operations should never be applied at this layer")
1640            }
1641            Operation::UpdateDiagnostics {
1642                diagnostics: diagnostic_set,
1643                ..
1644            } => diagnostic_set.iter().all(|diagnostic| {
1645                self.text.can_resolve(&diagnostic.range.start)
1646                    && self.text.can_resolve(&diagnostic.range.end)
1647            }),
1648            Operation::UpdateSelections { selections, .. } => selections
1649                .iter()
1650                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1651            Operation::UpdateCompletionTriggers { .. } => true,
1652        }
1653    }
1654
1655    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1656        match operation {
1657            Operation::Buffer(_) => {
1658                unreachable!("buffer operations should never be applied at this layer")
1659            }
1660            Operation::UpdateDiagnostics {
1661                diagnostics: diagnostic_set,
1662                lamport_timestamp,
1663            } => {
1664                let snapshot = self.snapshot();
1665                self.apply_diagnostic_update(
1666                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1667                    lamport_timestamp,
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(
1702        &mut self,
1703        diagnostics: DiagnosticSet,
1704        lamport_timestamp: clock::Lamport,
1705        cx: &mut ModelContext<Self>,
1706    ) {
1707        if lamport_timestamp > self.diagnostics_timestamp {
1708            self.diagnostics = diagnostics;
1709            self.diagnostics_timestamp = lamport_timestamp;
1710            self.diagnostics_update_count += 1;
1711            self.text.lamport_clock.observe(lamport_timestamp);
1712            cx.notify();
1713            cx.emit(Event::DiagnosticsUpdated);
1714        }
1715    }
1716
1717    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1718        cx.emit(Event::Operation(operation));
1719    }
1720
1721    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1722        self.remote_selections.remove(&replica_id);
1723        cx.notify();
1724    }
1725
1726    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1727        let was_dirty = self.is_dirty();
1728        let old_version = self.version.clone();
1729
1730        if let Some((transaction_id, operation)) = self.text.undo() {
1731            self.send_operation(Operation::Buffer(operation), cx);
1732            self.did_edit(&old_version, was_dirty, cx);
1733            Some(transaction_id)
1734        } else {
1735            None
1736        }
1737    }
1738
1739    pub fn undo_to_transaction(
1740        &mut self,
1741        transaction_id: TransactionId,
1742        cx: &mut ModelContext<Self>,
1743    ) -> bool {
1744        let was_dirty = self.is_dirty();
1745        let old_version = self.version.clone();
1746
1747        let operations = self.text.undo_to_transaction(transaction_id);
1748        let undone = !operations.is_empty();
1749        for operation in operations {
1750            self.send_operation(Operation::Buffer(operation), cx);
1751        }
1752        if undone {
1753            self.did_edit(&old_version, was_dirty, cx)
1754        }
1755        undone
1756    }
1757
1758    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1759        let was_dirty = self.is_dirty();
1760        let old_version = self.version.clone();
1761
1762        if let Some((transaction_id, operation)) = self.text.redo() {
1763            self.send_operation(Operation::Buffer(operation), cx);
1764            self.did_edit(&old_version, was_dirty, cx);
1765            Some(transaction_id)
1766        } else {
1767            None
1768        }
1769    }
1770
1771    pub fn redo_to_transaction(
1772        &mut self,
1773        transaction_id: TransactionId,
1774        cx: &mut ModelContext<Self>,
1775    ) -> bool {
1776        let was_dirty = self.is_dirty();
1777        let old_version = self.version.clone();
1778
1779        let operations = self.text.redo_to_transaction(transaction_id);
1780        let redone = !operations.is_empty();
1781        for operation in operations {
1782            self.send_operation(Operation::Buffer(operation), cx);
1783        }
1784        if redone {
1785            self.did_edit(&old_version, was_dirty, cx)
1786        }
1787        redone
1788    }
1789
1790    pub fn completion_triggers(&self) -> &[String] {
1791        &self.completion_triggers
1792    }
1793}
1794
1795#[cfg(any(test, feature = "test-support"))]
1796impl Buffer {
1797    pub fn set_group_interval(&mut self, group_interval: Duration) {
1798        self.text.set_group_interval(group_interval);
1799    }
1800
1801    pub fn randomly_edit<T>(
1802        &mut self,
1803        rng: &mut T,
1804        old_range_count: usize,
1805        cx: &mut ModelContext<Self>,
1806    ) where
1807        T: rand::Rng,
1808    {
1809        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1810        for _ in 0..old_range_count {
1811            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1812            if last_end > self.len() {
1813                break;
1814            }
1815            old_ranges.push(self.text.random_byte_range(last_end, rng));
1816        }
1817        let new_text_len = rng.gen_range(0..10);
1818        let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1819            .take(new_text_len)
1820            .collect();
1821        log::info!(
1822            "mutating buffer {} at {:?}: {:?}",
1823            self.replica_id(),
1824            old_ranges,
1825            new_text
1826        );
1827        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1828    }
1829
1830    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1831        let was_dirty = self.is_dirty();
1832        let old_version = self.version.clone();
1833
1834        let ops = self.text.randomly_undo_redo(rng);
1835        if !ops.is_empty() {
1836            for op in ops {
1837                self.send_operation(Operation::Buffer(op), cx);
1838                self.did_edit(&old_version, was_dirty, cx);
1839            }
1840        }
1841    }
1842}
1843
1844impl Entity for Buffer {
1845    type Event = Event;
1846
1847    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1848        if let Some(file) = self.file.as_ref() {
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}
2662
2663pub fn char_kind(c: char) -> CharKind {
2664    if c == '\n' {
2665        CharKind::Newline
2666    } else if c.is_whitespace() {
2667        CharKind::Whitespace
2668    } else if c.is_alphanumeric() || c == '_' {
2669        CharKind::Word
2670    } else {
2671        CharKind::Punctuation
2672    }
2673}