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