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