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,
  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
 117struct LanguageServerState {
 118    server: Arc<LanguageServer>,
 119    latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
 120    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
 121    next_version: usize,
 122    _maintain_server: Task<Option<()>>,
 123}
 124
 125#[derive(Clone)]
 126struct LanguageServerSnapshot {
 127    buffer_snapshot: text::BufferSnapshot,
 128    version: usize,
 129    path: Arc<Path>,
 130}
 131
 132#[derive(Clone, Debug)]
 133pub enum Operation {
 134    Buffer(text::Operation),
 135    UpdateDiagnostics {
 136        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 137        lamport_timestamp: clock::Lamport,
 138    },
 139    UpdateSelections {
 140        replica_id: ReplicaId,
 141        selections: Arc<[Selection<Anchor>]>,
 142        lamport_timestamp: clock::Lamport,
 143    },
 144}
 145
 146#[derive(Clone, Debug, Eq, PartialEq)]
 147pub enum Event {
 148    Edited,
 149    Dirtied,
 150    Saved,
 151    FileHandleChanged,
 152    Reloaded,
 153    Reparsed,
 154    DiagnosticsUpdated,
 155    Closed,
 156}
 157
 158pub trait File {
 159    fn as_local(&self) -> Option<&dyn LocalFile>;
 160
 161    fn mtime(&self) -> SystemTime;
 162
 163    /// Returns the path of this file relative to the worktree's root directory.
 164    fn path(&self) -> &Arc<Path>;
 165
 166    /// Returns the path of this file relative to the worktree's parent directory (this means it
 167    /// includes the name of the worktree's root folder).
 168    fn full_path(&self, cx: &AppContext) -> PathBuf;
 169
 170    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 171    /// of its worktree, then this method will return the name of the worktree itself.
 172    fn file_name(&self, cx: &AppContext) -> OsString;
 173
 174    fn is_deleted(&self) -> bool;
 175
 176    fn save(
 177        &self,
 178        buffer_id: u64,
 179        text: Rope,
 180        version: clock::Global,
 181        cx: &mut MutableAppContext,
 182    ) -> Task<Result<(clock::Global, SystemTime)>>;
 183
 184    fn format_remote(&self, buffer_id: u64, cx: &mut MutableAppContext)
 185        -> Option<Task<Result<()>>>;
 186
 187    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
 188
 189    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
 190
 191    fn as_any(&self) -> &dyn Any;
 192
 193    fn to_proto(&self) -> rpc::proto::File;
 194}
 195
 196pub trait LocalFile: File {
 197    /// Returns the absolute path of this file.
 198    fn abs_path(&self, cx: &AppContext) -> PathBuf;
 199
 200    fn load(&self, cx: &AppContext) -> Task<Result<String>>;
 201
 202    fn buffer_reloaded(
 203        &self,
 204        buffer_id: u64,
 205        version: &clock::Global,
 206        mtime: SystemTime,
 207        cx: &mut MutableAppContext,
 208    );
 209}
 210
 211pub(crate) struct QueryCursorHandle(Option<QueryCursor>);
 212
 213#[derive(Clone)]
 214struct SyntaxTree {
 215    tree: Tree,
 216    version: clock::Global,
 217}
 218
 219#[derive(Clone)]
 220struct AutoindentRequest {
 221    before_edit: BufferSnapshot,
 222    edited: Vec<Anchor>,
 223    inserted: Option<Vec<Range<Anchor>>>,
 224}
 225
 226#[derive(Debug)]
 227struct IndentSuggestion {
 228    basis_row: u32,
 229    indent: bool,
 230}
 231
 232struct TextProvider<'a>(&'a Rope);
 233
 234struct BufferChunkHighlights<'a> {
 235    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 236    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 237    stack: Vec<(usize, HighlightId)>,
 238    highlight_map: HighlightMap,
 239    theme: &'a SyntaxTheme,
 240    _query_cursor: QueryCursorHandle,
 241}
 242
 243pub struct BufferChunks<'a> {
 244    range: Range<usize>,
 245    chunks: rope::Chunks<'a>,
 246    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 247    error_depth: usize,
 248    warning_depth: usize,
 249    information_depth: usize,
 250    hint_depth: usize,
 251    highlights: Option<BufferChunkHighlights<'a>>,
 252}
 253
 254#[derive(Clone, Copy, Debug, Default)]
 255pub struct Chunk<'a> {
 256    pub text: &'a str,
 257    pub highlight_style: Option<HighlightStyle>,
 258    pub diagnostic: Option<DiagnosticSeverity>,
 259}
 260
 261pub(crate) struct Diff {
 262    base_version: clock::Global,
 263    new_text: Arc<str>,
 264    changes: Vec<(ChangeTag, usize)>,
 265}
 266
 267#[derive(Clone, Copy)]
 268struct DiagnosticEndpoint {
 269    offset: usize,
 270    is_start: bool,
 271    severity: DiagnosticSeverity,
 272}
 273
 274impl Buffer {
 275    pub fn new<T: Into<Arc<str>>>(
 276        replica_id: ReplicaId,
 277        base_text: T,
 278        cx: &mut ModelContext<Self>,
 279    ) -> Self {
 280        Self::build(
 281            TextBuffer::new(
 282                replica_id,
 283                cx.model_id() as u64,
 284                History::new(base_text.into()),
 285            ),
 286            None,
 287        )
 288    }
 289
 290    pub fn from_file<T: Into<Arc<str>>>(
 291        replica_id: ReplicaId,
 292        base_text: T,
 293        file: Box<dyn File>,
 294        cx: &mut ModelContext<Self>,
 295    ) -> Self {
 296        Self::build(
 297            TextBuffer::new(
 298                replica_id,
 299                cx.model_id() as u64,
 300                History::new(base_text.into()),
 301            ),
 302            Some(file),
 303        )
 304    }
 305
 306    pub fn from_proto(
 307        replica_id: ReplicaId,
 308        message: proto::Buffer,
 309        file: Option<Box<dyn File>>,
 310        cx: &mut ModelContext<Self>,
 311    ) -> Result<Self> {
 312        let fragments_len = message.fragments.len();
 313        let buffer = TextBuffer::from_parts(
 314            replica_id,
 315            message.id,
 316            &message.visible_text,
 317            &message.deleted_text,
 318            message
 319                .undo_map
 320                .into_iter()
 321                .map(proto::deserialize_undo_map_entry),
 322            message
 323                .fragments
 324                .into_iter()
 325                .enumerate()
 326                .map(|(i, fragment)| {
 327                    proto::deserialize_buffer_fragment(fragment, i, fragments_len)
 328                }),
 329            message.lamport_timestamp,
 330            From::from(message.version),
 331        );
 332        let mut this = Self::build(buffer, file);
 333        for selection_set in message.selections {
 334            this.remote_selections.insert(
 335                selection_set.replica_id as ReplicaId,
 336                SelectionSet {
 337                    selections: proto::deserialize_selections(selection_set.selections),
 338                    lamport_timestamp: clock::Lamport {
 339                        replica_id: selection_set.replica_id as ReplicaId,
 340                        value: selection_set.lamport_timestamp,
 341                    },
 342                },
 343            );
 344        }
 345        let snapshot = this.snapshot();
 346        let entries = proto::deserialize_diagnostics(message.diagnostics);
 347        this.apply_diagnostic_update(
 348            DiagnosticSet::from_sorted_entries(entries.into_iter().cloned(), &snapshot),
 349            cx,
 350        );
 351
 352        let deferred_ops = message
 353            .deferred_operations
 354            .into_iter()
 355            .map(proto::deserialize_operation)
 356            .collect::<Result<Vec<_>>>()?;
 357        this.apply_ops(deferred_ops, cx)?;
 358
 359        Ok(this)
 360    }
 361
 362    pub fn to_proto(&self) -> proto::Buffer {
 363        proto::Buffer {
 364            id: self.remote_id(),
 365            file: self.file.as_ref().map(|f| f.to_proto()),
 366            visible_text: self.text.text(),
 367            deleted_text: self.text.deleted_text(),
 368            undo_map: self
 369                .text
 370                .undo_history()
 371                .map(proto::serialize_undo_map_entry)
 372                .collect(),
 373            version: From::from(&self.version),
 374            lamport_timestamp: self.lamport_clock.value,
 375            fragments: self
 376                .text
 377                .fragments()
 378                .map(proto::serialize_buffer_fragment)
 379                .collect(),
 380            selections: self
 381                .remote_selections
 382                .iter()
 383                .map(|(replica_id, set)| proto::SelectionSet {
 384                    replica_id: *replica_id as u32,
 385                    selections: proto::serialize_selections(&set.selections),
 386                    lamport_timestamp: set.lamport_timestamp.value,
 387                })
 388                .collect(),
 389            diagnostics: proto::serialize_diagnostics(self.diagnostics.iter()),
 390            deferred_operations: self
 391                .deferred_ops
 392                .iter()
 393                .map(proto::serialize_operation)
 394                .chain(
 395                    self.text
 396                        .deferred_ops()
 397                        .map(|op| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 398                )
 399                .collect(),
 400        }
 401    }
 402
 403    pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
 404        self.set_language(Some(language), cx);
 405        self
 406    }
 407
 408    pub fn with_language_server(
 409        mut self,
 410        server: Arc<LanguageServer>,
 411        cx: &mut ModelContext<Self>,
 412    ) -> Self {
 413        self.set_language_server(Some(server), cx);
 414        self
 415    }
 416
 417    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 418        let saved_mtime;
 419        if let Some(file) = file.as_ref() {
 420            saved_mtime = file.mtime();
 421        } else {
 422            saved_mtime = UNIX_EPOCH;
 423        }
 424
 425        Self {
 426            saved_mtime,
 427            saved_version: buffer.version(),
 428            text: buffer,
 429            file,
 430            syntax_tree: Mutex::new(None),
 431            parsing_in_background: false,
 432            parse_count: 0,
 433            sync_parse_timeout: Duration::from_millis(1),
 434            autoindent_requests: Default::default(),
 435            pending_autoindent: Default::default(),
 436            language: None,
 437            remote_selections: Default::default(),
 438            selections_update_count: 0,
 439            diagnostics: Default::default(),
 440            diagnostics_update_count: 0,
 441            language_server: None,
 442            deferred_ops: OperationQueue::new(),
 443            #[cfg(test)]
 444            operations: Default::default(),
 445        }
 446    }
 447
 448    pub fn snapshot(&self) -> BufferSnapshot {
 449        BufferSnapshot {
 450            text: self.text.snapshot(),
 451            tree: self.syntax_tree(),
 452            remote_selections: self.remote_selections.clone(),
 453            diagnostics: self.diagnostics.clone(),
 454            diagnostics_update_count: self.diagnostics_update_count,
 455            is_parsing: self.parsing_in_background,
 456            language: self.language.clone(),
 457            parse_count: self.parse_count,
 458            selections_update_count: self.selections_update_count,
 459        }
 460    }
 461
 462    pub fn file(&self) -> Option<&dyn File> {
 463        self.file.as_deref()
 464    }
 465
 466    pub fn format(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 467        let file = if let Some(file) = self.file.as_ref() {
 468            file
 469        } else {
 470            return Task::ready(Err(anyhow!("buffer has no file")));
 471        };
 472
 473        if let Some(LanguageServerState { server, .. }) = self.language_server.as_ref() {
 474            let server = server.clone();
 475            let abs_path = file.as_local().unwrap().abs_path(cx);
 476            let version = self.version();
 477            cx.spawn(|this, mut cx| async move {
 478                let edits = server
 479                    .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
 480                        text_document: lsp::TextDocumentIdentifier::new(
 481                            lsp::Url::from_file_path(&abs_path).unwrap(),
 482                        ),
 483                        options: Default::default(),
 484                        work_done_progress_params: Default::default(),
 485                    })
 486                    .await?;
 487
 488                if let Some(edits) = edits {
 489                    this.update(&mut cx, |this, cx| {
 490                        if this.version == version {
 491                            for edit in &edits {
 492                                let range = range_from_lsp(edit.range);
 493                                if this.clip_point_utf16(range.start, Bias::Left) != range.start
 494                                    || this.clip_point_utf16(range.end, Bias::Left) != range.end
 495                                {
 496                                    return Err(anyhow!(
 497                                        "invalid formatting edits received from language server"
 498                                    ));
 499                                }
 500                            }
 501
 502                            for edit in edits.into_iter().rev() {
 503                                this.edit([range_from_lsp(edit.range)], edit.new_text, cx);
 504                            }
 505                            Ok(())
 506                        } else {
 507                            Err(anyhow!("buffer edited since starting to format"))
 508                        }
 509                    })
 510                } else {
 511                    Ok(())
 512                }
 513            })
 514        } else {
 515            let format = file.format_remote(self.remote_id(), cx.as_mut());
 516            cx.spawn(|_, _| async move {
 517                if let Some(format) = format {
 518                    format.await?;
 519                }
 520                Ok(())
 521            })
 522        }
 523    }
 524
 525    pub fn save(
 526        &mut self,
 527        cx: &mut ModelContext<Self>,
 528    ) -> Task<Result<(clock::Global, SystemTime)>> {
 529        let file = if let Some(file) = self.file.as_ref() {
 530            file
 531        } else {
 532            return Task::ready(Err(anyhow!("buffer has no file")));
 533        };
 534        let text = self.as_rope().clone();
 535        let version = self.version();
 536        let save = file.save(self.remote_id(), text, version, cx.as_mut());
 537        cx.spawn(|this, mut cx| async move {
 538            let (version, mtime) = save.await?;
 539            this.update(&mut cx, |this, cx| {
 540                this.did_save(version.clone(), mtime, None, cx);
 541            });
 542            Ok((version, mtime))
 543        })
 544    }
 545
 546    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
 547        self.language = language;
 548        self.reparse(cx);
 549    }
 550
 551    pub fn set_language_server(
 552        &mut self,
 553        language_server: Option<Arc<lsp::LanguageServer>>,
 554        cx: &mut ModelContext<Self>,
 555    ) {
 556        self.language_server = if let Some(server) = language_server {
 557            let (latest_snapshot_tx, mut latest_snapshot_rx) = watch::channel();
 558            Some(LanguageServerState {
 559                latest_snapshot: latest_snapshot_tx,
 560                pending_snapshots: Default::default(),
 561                next_version: 0,
 562                server: server.clone(),
 563                _maintain_server: cx.background().spawn(
 564                    async move {
 565                        let mut prev_snapshot: Option<LanguageServerSnapshot> = None;
 566                        while let Some(snapshot) = latest_snapshot_rx.recv().await {
 567                            if let Some(snapshot) = snapshot {
 568                                let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
 569                                if let Some(prev_snapshot) = prev_snapshot {
 570                                    let changes = lsp::DidChangeTextDocumentParams {
 571                                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 572                                            uri,
 573                                            snapshot.version as i32,
 574                                        ),
 575                                        content_changes: snapshot
 576                                            .buffer_snapshot
 577                                            .edits_since::<(PointUtf16, usize)>(
 578                                                prev_snapshot.buffer_snapshot.version(),
 579                                            )
 580                                            .map(|edit| {
 581                                                let edit_start = edit.new.start.0;
 582                                                let edit_end = edit_start
 583                                                    + (edit.old.end.0 - edit.old.start.0);
 584                                                let new_text = snapshot
 585                                                    .buffer_snapshot
 586                                                    .text_for_range(
 587                                                        edit.new.start.1..edit.new.end.1,
 588                                                    )
 589                                                    .collect();
 590                                                lsp::TextDocumentContentChangeEvent {
 591                                                    range: Some(lsp::Range::new(
 592                                                        lsp::Position::new(
 593                                                            edit_start.row,
 594                                                            edit_start.column,
 595                                                        ),
 596                                                        lsp::Position::new(
 597                                                            edit_end.row,
 598                                                            edit_end.column,
 599                                                        ),
 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 set_active_selections(
1238        &mut self,
1239        selections: Arc<[Selection<Anchor>]>,
1240        cx: &mut ModelContext<Self>,
1241    ) {
1242        let lamport_timestamp = self.text.lamport_clock.tick();
1243        self.remote_selections.insert(
1244            self.text.replica_id(),
1245            SelectionSet {
1246                selections: selections.clone(),
1247                lamport_timestamp,
1248            },
1249        );
1250        self.send_operation(
1251            Operation::UpdateSelections {
1252                replica_id: self.text.replica_id(),
1253                selections,
1254                lamport_timestamp,
1255            },
1256            cx,
1257        );
1258    }
1259
1260    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1261        self.set_active_selections(Arc::from([]), cx);
1262    }
1263
1264    fn update_language_server(&mut self, cx: &AppContext) {
1265        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1266            language_server
1267        } else {
1268            return;
1269        };
1270        let abs_path = self
1271            .file
1272            .as_ref()
1273            .and_then(|f| f.as_local())
1274            .map_or(Path::new("/").to_path_buf(), |file| file.abs_path(cx));
1275
1276        let version = post_inc(&mut language_server.next_version);
1277        let snapshot = LanguageServerSnapshot {
1278            buffer_snapshot: self.text.snapshot(),
1279            version,
1280            path: Arc::from(abs_path),
1281        };
1282        language_server
1283            .pending_snapshots
1284            .insert(version, snapshot.clone());
1285        let _ = language_server
1286            .latest_snapshot
1287            .blocking_send(Some(snapshot));
1288    }
1289
1290    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1291    where
1292        I: IntoIterator<Item = Range<S>>,
1293        S: ToOffset,
1294        T: Into<String>,
1295    {
1296        self.edit_internal(ranges_iter, new_text, false, cx)
1297    }
1298
1299    pub fn edit_with_autoindent<I, S, T>(
1300        &mut self,
1301        ranges_iter: I,
1302        new_text: T,
1303        cx: &mut ModelContext<Self>,
1304    ) where
1305        I: IntoIterator<Item = Range<S>>,
1306        S: ToOffset,
1307        T: Into<String>,
1308    {
1309        self.edit_internal(ranges_iter, new_text, true, cx)
1310    }
1311
1312    /*
1313    impl Buffer
1314        pub fn edit
1315        pub fn edit_internal
1316        pub fn edit_with_autoindent
1317    */
1318
1319    pub fn edit_internal<I, S, T>(
1320        &mut self,
1321        ranges_iter: I,
1322        new_text: T,
1323        autoindent: bool,
1324        cx: &mut ModelContext<Self>,
1325    ) where
1326        I: IntoIterator<Item = Range<S>>,
1327        S: ToOffset,
1328        T: Into<String>,
1329    {
1330        let new_text = new_text.into();
1331
1332        // Skip invalid ranges and coalesce contiguous ones.
1333        let mut ranges: Vec<Range<usize>> = Vec::new();
1334        for range in ranges_iter {
1335            let range = range.start.to_offset(self)..range.end.to_offset(self);
1336            if !new_text.is_empty() || !range.is_empty() {
1337                if let Some(prev_range) = ranges.last_mut() {
1338                    if prev_range.end >= range.start {
1339                        prev_range.end = cmp::max(prev_range.end, range.end);
1340                    } else {
1341                        ranges.push(range);
1342                    }
1343                } else {
1344                    ranges.push(range);
1345                }
1346            }
1347        }
1348        if ranges.is_empty() {
1349            return;
1350        }
1351
1352        self.start_transaction();
1353        self.pending_autoindent.take();
1354        let autoindent_request = if autoindent && self.language.is_some() {
1355            let before_edit = self.snapshot();
1356            let edited = ranges
1357                .iter()
1358                .filter_map(|range| {
1359                    let start = range.start.to_point(self);
1360                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1361                        None
1362                    } else {
1363                        Some(self.anchor_before(range.start))
1364                    }
1365                })
1366                .collect();
1367            Some((before_edit, edited))
1368        } else {
1369            None
1370        };
1371
1372        let first_newline_ix = new_text.find('\n');
1373        let new_text_len = new_text.len();
1374
1375        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1376
1377        if let Some((before_edit, edited)) = autoindent_request {
1378            let mut inserted = None;
1379            if let Some(first_newline_ix) = first_newline_ix {
1380                let mut delta = 0isize;
1381                inserted = Some(
1382                    ranges
1383                        .iter()
1384                        .map(|range| {
1385                            let start =
1386                                (delta + range.start as isize) as usize + first_newline_ix + 1;
1387                            let end = (delta + range.start as isize) as usize + new_text_len;
1388                            delta +=
1389                                (range.end as isize - range.start as isize) + new_text_len as isize;
1390                            self.anchor_before(start)..self.anchor_after(end)
1391                        })
1392                        .collect(),
1393                );
1394            }
1395
1396            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1397                before_edit,
1398                edited,
1399                inserted,
1400            }));
1401        }
1402
1403        self.end_transaction(cx);
1404        self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1405    }
1406
1407    fn did_edit(
1408        &mut self,
1409        old_version: &clock::Global,
1410        was_dirty: bool,
1411        cx: &mut ModelContext<Self>,
1412    ) {
1413        if self.edits_since::<usize>(old_version).next().is_none() {
1414            return;
1415        }
1416
1417        self.reparse(cx);
1418        self.update_language_server(cx);
1419
1420        cx.emit(Event::Edited);
1421        if !was_dirty {
1422            cx.emit(Event::Dirtied);
1423        }
1424        cx.notify();
1425    }
1426
1427    fn grammar(&self) -> Option<&Arc<Grammar>> {
1428        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1429    }
1430
1431    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1432        &mut self,
1433        ops: I,
1434        cx: &mut ModelContext<Self>,
1435    ) -> Result<()> {
1436        self.pending_autoindent.take();
1437        let was_dirty = self.is_dirty();
1438        let old_version = self.version.clone();
1439        let mut deferred_ops = Vec::new();
1440        let buffer_ops = ops
1441            .into_iter()
1442            .filter_map(|op| match op {
1443                Operation::Buffer(op) => Some(op),
1444                _ => {
1445                    if self.can_apply_op(&op) {
1446                        self.apply_op(op, cx);
1447                    } else {
1448                        deferred_ops.push(op);
1449                    }
1450                    None
1451                }
1452            })
1453            .collect::<Vec<_>>();
1454        self.text.apply_ops(buffer_ops)?;
1455        self.deferred_ops.insert(deferred_ops);
1456        self.flush_deferred_ops(cx);
1457        self.did_edit(&old_version, was_dirty, cx);
1458        // Notify independently of whether the buffer was edited as the operations could include a
1459        // selection update.
1460        cx.notify();
1461        Ok(())
1462    }
1463
1464    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1465        let mut deferred_ops = Vec::new();
1466        for op in self.deferred_ops.drain().iter().cloned() {
1467            if self.can_apply_op(&op) {
1468                self.apply_op(op, cx);
1469            } else {
1470                deferred_ops.push(op);
1471            }
1472        }
1473        self.deferred_ops.insert(deferred_ops);
1474    }
1475
1476    fn can_apply_op(&self, operation: &Operation) -> bool {
1477        match operation {
1478            Operation::Buffer(_) => {
1479                unreachable!("buffer operations should never be applied at this layer")
1480            }
1481            Operation::UpdateDiagnostics {
1482                diagnostics: diagnostic_set,
1483                ..
1484            } => diagnostic_set.iter().all(|diagnostic| {
1485                self.text.can_resolve(&diagnostic.range.start)
1486                    && self.text.can_resolve(&diagnostic.range.end)
1487            }),
1488            Operation::UpdateSelections { selections, .. } => selections
1489                .iter()
1490                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1491        }
1492    }
1493
1494    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1495        match operation {
1496            Operation::Buffer(_) => {
1497                unreachable!("buffer operations should never be applied at this layer")
1498            }
1499            Operation::UpdateDiagnostics {
1500                diagnostics: diagnostic_set,
1501                ..
1502            } => {
1503                let snapshot = self.snapshot();
1504                self.apply_diagnostic_update(
1505                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1506                    cx,
1507                );
1508            }
1509            Operation::UpdateSelections {
1510                replica_id,
1511                selections,
1512                lamport_timestamp,
1513            } => {
1514                if let Some(set) = self.remote_selections.get(&replica_id) {
1515                    if set.lamport_timestamp > lamport_timestamp {
1516                        return;
1517                    }
1518                }
1519
1520                self.remote_selections.insert(
1521                    replica_id,
1522                    SelectionSet {
1523                        selections,
1524                        lamport_timestamp,
1525                    },
1526                );
1527                self.text.lamport_clock.observe(lamport_timestamp);
1528                self.selections_update_count += 1;
1529            }
1530        }
1531    }
1532
1533    fn apply_diagnostic_update(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
1534        self.diagnostics = diagnostics;
1535        self.diagnostics_update_count += 1;
1536        cx.notify();
1537        cx.emit(Event::DiagnosticsUpdated);
1538    }
1539
1540    #[cfg(not(test))]
1541    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1542        if let Some(file) = &self.file {
1543            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1544        }
1545    }
1546
1547    #[cfg(test)]
1548    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1549        self.operations.push(operation);
1550    }
1551
1552    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1553        self.remote_selections.remove(&replica_id);
1554        cx.notify();
1555    }
1556
1557    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1558        let was_dirty = self.is_dirty();
1559        let old_version = self.version.clone();
1560
1561        if let Some((transaction_id, operation)) = self.text.undo() {
1562            self.send_operation(Operation::Buffer(operation), cx);
1563            self.did_edit(&old_version, was_dirty, cx);
1564            Some(transaction_id)
1565        } else {
1566            None
1567        }
1568    }
1569
1570    pub fn undo_transaction(
1571        &mut self,
1572        transaction_id: TransactionId,
1573        cx: &mut ModelContext<Self>,
1574    ) -> bool {
1575        let was_dirty = self.is_dirty();
1576        let old_version = self.version.clone();
1577
1578        if let Some(operation) = self.text.undo_transaction(transaction_id) {
1579            self.send_operation(Operation::Buffer(operation), cx);
1580            self.did_edit(&old_version, was_dirty, cx);
1581            true
1582        } else {
1583            false
1584        }
1585    }
1586
1587    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1588        let was_dirty = self.is_dirty();
1589        let old_version = self.version.clone();
1590
1591        if let Some((transaction_id, operation)) = self.text.redo() {
1592            self.send_operation(Operation::Buffer(operation), cx);
1593            self.did_edit(&old_version, was_dirty, cx);
1594            Some(transaction_id)
1595        } else {
1596            None
1597        }
1598    }
1599
1600    pub fn redo_transaction(
1601        &mut self,
1602        transaction_id: TransactionId,
1603        cx: &mut ModelContext<Self>,
1604    ) -> bool {
1605        let was_dirty = self.is_dirty();
1606        let old_version = self.version.clone();
1607
1608        if let Some(operation) = self.text.redo_transaction(transaction_id) {
1609            self.send_operation(Operation::Buffer(operation), cx);
1610            self.did_edit(&old_version, was_dirty, cx);
1611            true
1612        } else {
1613            false
1614        }
1615    }
1616}
1617
1618#[cfg(any(test, feature = "test-support"))]
1619impl Buffer {
1620    pub fn set_group_interval(&mut self, group_interval: Duration) {
1621        self.text.set_group_interval(group_interval);
1622    }
1623
1624    pub fn randomly_edit<T>(
1625        &mut self,
1626        rng: &mut T,
1627        old_range_count: usize,
1628        cx: &mut ModelContext<Self>,
1629    ) where
1630        T: rand::Rng,
1631    {
1632        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1633        for _ in 0..old_range_count {
1634            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1635            if last_end > self.len() {
1636                break;
1637            }
1638            old_ranges.push(self.text.random_byte_range(last_end, rng));
1639        }
1640        let new_text_len = rng.gen_range(0..10);
1641        let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1642            .take(new_text_len)
1643            .collect();
1644        log::info!(
1645            "mutating buffer {} at {:?}: {:?}",
1646            self.replica_id(),
1647            old_ranges,
1648            new_text
1649        );
1650        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1651    }
1652
1653    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1654        let was_dirty = self.is_dirty();
1655        let old_version = self.version.clone();
1656
1657        let ops = self.text.randomly_undo_redo(rng);
1658        if !ops.is_empty() {
1659            for op in ops {
1660                self.send_operation(Operation::Buffer(op), cx);
1661                self.did_edit(&old_version, was_dirty, cx);
1662            }
1663        }
1664    }
1665}
1666
1667impl Entity for Buffer {
1668    type Event = Event;
1669
1670    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1671        if let Some(file) = self.file.as_ref() {
1672            file.buffer_removed(self.remote_id(), cx);
1673        }
1674    }
1675}
1676
1677impl Deref for Buffer {
1678    type Target = TextBuffer;
1679
1680    fn deref(&self) -> &Self::Target {
1681        &self.text
1682    }
1683}
1684
1685impl BufferSnapshot {
1686    fn suggest_autoindents<'a>(
1687        &'a self,
1688        row_range: Range<u32>,
1689    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1690        let mut query_cursor = QueryCursorHandle::new();
1691        if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1692            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1693
1694            // Get the "indentation ranges" that intersect this row range.
1695            let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
1696            let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
1697            query_cursor.set_point_range(
1698                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1699                    ..Point::new(row_range.end, 0).to_ts_point(),
1700            );
1701            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1702            for mat in query_cursor.matches(
1703                &grammar.indents_query,
1704                tree.root_node(),
1705                TextProvider(self.as_rope()),
1706            ) {
1707                let mut node_kind = "";
1708                let mut start: Option<Point> = None;
1709                let mut end: Option<Point> = None;
1710                for capture in mat.captures {
1711                    if Some(capture.index) == indent_capture_ix {
1712                        node_kind = capture.node.kind();
1713                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1714                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1715                    } else if Some(capture.index) == end_capture_ix {
1716                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1717                    }
1718                }
1719
1720                if let Some((start, end)) = start.zip(end) {
1721                    if start.row == end.row {
1722                        continue;
1723                    }
1724
1725                    let range = start..end;
1726                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1727                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1728                        Ok(ix) => {
1729                            let prev_range = &mut indentation_ranges[ix];
1730                            prev_range.0.end = prev_range.0.end.max(range.end);
1731                        }
1732                    }
1733                }
1734            }
1735
1736            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1737            Some(row_range.map(move |row| {
1738                let row_start = Point::new(row, self.indent_column_for_line(row));
1739
1740                let mut indent_from_prev_row = false;
1741                let mut outdent_to_row = u32::MAX;
1742                for (range, _node_kind) in &indentation_ranges {
1743                    if range.start.row >= row {
1744                        break;
1745                    }
1746
1747                    if range.start.row == prev_row && range.end > row_start {
1748                        indent_from_prev_row = true;
1749                    }
1750                    if range.end.row >= prev_row && range.end <= row_start {
1751                        outdent_to_row = outdent_to_row.min(range.start.row);
1752                    }
1753                }
1754
1755                let suggestion = if outdent_to_row == prev_row {
1756                    IndentSuggestion {
1757                        basis_row: prev_row,
1758                        indent: false,
1759                    }
1760                } else if indent_from_prev_row {
1761                    IndentSuggestion {
1762                        basis_row: prev_row,
1763                        indent: true,
1764                    }
1765                } else if outdent_to_row < prev_row {
1766                    IndentSuggestion {
1767                        basis_row: outdent_to_row,
1768                        indent: false,
1769                    }
1770                } else {
1771                    IndentSuggestion {
1772                        basis_row: prev_row,
1773                        indent: false,
1774                    }
1775                };
1776
1777                prev_row = row;
1778                suggestion
1779            }))
1780        } else {
1781            None
1782        }
1783    }
1784
1785    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1786        while row > 0 {
1787            row -= 1;
1788            if !self.is_line_blank(row) {
1789                return Some(row);
1790            }
1791        }
1792        None
1793    }
1794
1795    pub fn chunks<'a, T: ToOffset>(
1796        &'a self,
1797        range: Range<T>,
1798        theme: Option<&'a SyntaxTheme>,
1799    ) -> BufferChunks<'a> {
1800        let range = range.start.to_offset(self)..range.end.to_offset(self);
1801
1802        let mut highlights = None;
1803        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1804        if let Some(theme) = theme {
1805            for entry in self.diagnostics_in_range::<_, usize>(range.clone()) {
1806                diagnostic_endpoints.push(DiagnosticEndpoint {
1807                    offset: entry.range.start,
1808                    is_start: true,
1809                    severity: entry.diagnostic.severity,
1810                });
1811                diagnostic_endpoints.push(DiagnosticEndpoint {
1812                    offset: entry.range.end,
1813                    is_start: false,
1814                    severity: entry.diagnostic.severity,
1815                });
1816            }
1817            diagnostic_endpoints
1818                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1819
1820            if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1821                let mut query_cursor = QueryCursorHandle::new();
1822
1823                // TODO - add a Tree-sitter API to remove the need for this.
1824                let cursor = unsafe {
1825                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1826                };
1827                let captures = cursor.set_byte_range(range.clone()).captures(
1828                    &grammar.highlights_query,
1829                    tree.root_node(),
1830                    TextProvider(self.text.as_rope()),
1831                );
1832                highlights = Some(BufferChunkHighlights {
1833                    captures,
1834                    next_capture: None,
1835                    stack: Default::default(),
1836                    highlight_map: grammar.highlight_map(),
1837                    _query_cursor: query_cursor,
1838                    theme,
1839                })
1840            }
1841        }
1842
1843        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1844        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1845
1846        BufferChunks {
1847            range,
1848            chunks,
1849            diagnostic_endpoints,
1850            error_depth: 0,
1851            warning_depth: 0,
1852            information_depth: 0,
1853            hint_depth: 0,
1854            highlights,
1855        }
1856    }
1857
1858    pub fn language(&self) -> Option<&Arc<Language>> {
1859        self.language.as_ref()
1860    }
1861
1862    fn grammar(&self) -> Option<&Arc<Grammar>> {
1863        self.language
1864            .as_ref()
1865            .and_then(|language| language.grammar.as_ref())
1866    }
1867
1868    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1869        if let Some(tree) = self.tree.as_ref() {
1870            let root = tree.root_node();
1871            let range = range.start.to_offset(self)..range.end.to_offset(self);
1872            let mut node = root.descendant_for_byte_range(range.start, range.end);
1873            while node.map_or(false, |n| n.byte_range() == range) {
1874                node = node.unwrap().parent();
1875            }
1876            node.map(|n| n.byte_range())
1877        } else {
1878            None
1879        }
1880    }
1881
1882    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1883        let tree = self.tree.as_ref()?;
1884        let grammar = self
1885            .language
1886            .as_ref()
1887            .and_then(|language| language.grammar.as_ref())?;
1888
1889        let mut cursor = QueryCursorHandle::new();
1890        let matches = cursor.matches(
1891            &grammar.outline_query,
1892            tree.root_node(),
1893            TextProvider(self.as_rope()),
1894        );
1895
1896        let mut chunks = self.chunks(0..self.len(), theme);
1897
1898        let item_capture_ix = grammar.outline_query.capture_index_for_name("item")?;
1899        let name_capture_ix = grammar.outline_query.capture_index_for_name("name")?;
1900        let context_capture_ix = grammar
1901            .outline_query
1902            .capture_index_for_name("context")
1903            .unwrap_or(u32::MAX);
1904
1905        let mut stack = Vec::<Range<usize>>::new();
1906        let items = matches
1907            .filter_map(|mat| {
1908                let item_node = mat.nodes_for_capture_index(item_capture_ix).next()?;
1909                let range = item_node.start_byte()..item_node.end_byte();
1910                let mut text = String::new();
1911                let mut name_ranges = Vec::new();
1912                let mut highlight_ranges = Vec::new();
1913
1914                for capture in mat.captures {
1915                    let node_is_name;
1916                    if capture.index == name_capture_ix {
1917                        node_is_name = true;
1918                    } else if capture.index == context_capture_ix {
1919                        node_is_name = false;
1920                    } else {
1921                        continue;
1922                    }
1923
1924                    let range = capture.node.start_byte()..capture.node.end_byte();
1925                    if !text.is_empty() {
1926                        text.push(' ');
1927                    }
1928                    if node_is_name {
1929                        let mut start = text.len();
1930                        let end = start + range.len();
1931
1932                        // When multiple names are captured, then the matcheable text
1933                        // includes the whitespace in between the names.
1934                        if !name_ranges.is_empty() {
1935                            start -= 1;
1936                        }
1937
1938                        name_ranges.push(start..end);
1939                    }
1940
1941                    let mut offset = range.start;
1942                    chunks.seek(offset);
1943                    while let Some(mut chunk) = chunks.next() {
1944                        if chunk.text.len() > range.end - offset {
1945                            chunk.text = &chunk.text[0..(range.end - offset)];
1946                            offset = range.end;
1947                        } else {
1948                            offset += chunk.text.len();
1949                        }
1950                        if let Some(style) = chunk.highlight_style {
1951                            let start = text.len();
1952                            let end = start + chunk.text.len();
1953                            highlight_ranges.push((start..end, style));
1954                        }
1955                        text.push_str(chunk.text);
1956                        if offset >= range.end {
1957                            break;
1958                        }
1959                    }
1960                }
1961
1962                while stack.last().map_or(false, |prev_range| {
1963                    !prev_range.contains(&range.start) || !prev_range.contains(&range.end)
1964                }) {
1965                    stack.pop();
1966                }
1967                stack.push(range.clone());
1968
1969                Some(OutlineItem {
1970                    depth: stack.len() - 1,
1971                    range: self.anchor_after(range.start)..self.anchor_before(range.end),
1972                    text,
1973                    highlight_ranges,
1974                    name_ranges,
1975                })
1976            })
1977            .collect::<Vec<_>>();
1978
1979        if items.is_empty() {
1980            None
1981        } else {
1982            Some(Outline::new(items))
1983        }
1984    }
1985
1986    pub fn enclosing_bracket_ranges<T: ToOffset>(
1987        &self,
1988        range: Range<T>,
1989    ) -> Option<(Range<usize>, Range<usize>)> {
1990        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
1991        let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
1992        let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
1993
1994        // Find bracket pairs that *inclusively* contain the given range.
1995        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1996        let mut cursor = QueryCursorHandle::new();
1997        let matches = cursor.set_byte_range(range).matches(
1998            &grammar.brackets_query,
1999            tree.root_node(),
2000            TextProvider(self.as_rope()),
2001        );
2002
2003        // Get the ranges of the innermost pair of brackets.
2004        matches
2005            .filter_map(|mat| {
2006                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
2007                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
2008                Some((open.byte_range(), close.byte_range()))
2009            })
2010            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
2011    }
2012
2013    /*
2014    impl BufferSnapshot
2015      pub fn remote_selections_in_range(&self, Range<Anchor>) -> impl Iterator<Item = (ReplicaId, impl Iterator<Item = &Selection<Anchor>>)>
2016      pub fn remote_selections_in_range(&self, Range<Anchor>) -> impl Iterator<Item = (ReplicaId, i
2017    */
2018
2019    pub fn remote_selections_in_range<'a>(
2020        &'a self,
2021        range: Range<Anchor>,
2022    ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
2023    {
2024        self.remote_selections
2025            .iter()
2026            .filter(|(replica_id, set)| {
2027                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2028            })
2029            .map(move |(replica_id, set)| {
2030                let start_ix = match set.selections.binary_search_by(|probe| {
2031                    probe
2032                        .end
2033                        .cmp(&range.start, self)
2034                        .unwrap()
2035                        .then(Ordering::Greater)
2036                }) {
2037                    Ok(ix) | Err(ix) => ix,
2038                };
2039                let end_ix = match set.selections.binary_search_by(|probe| {
2040                    probe
2041                        .start
2042                        .cmp(&range.end, self)
2043                        .unwrap()
2044                        .then(Ordering::Less)
2045                }) {
2046                    Ok(ix) | Err(ix) => ix,
2047                };
2048
2049                (*replica_id, set.selections[start_ix..end_ix].iter())
2050            })
2051    }
2052
2053    pub fn diagnostics_in_range<'a, T, O>(
2054        &'a self,
2055        search_range: Range<T>,
2056    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2057    where
2058        T: 'a + Clone + ToOffset,
2059        O: 'a + FromAnchor,
2060    {
2061        self.diagnostics.range(search_range.clone(), self, true)
2062    }
2063
2064    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2065        let mut groups = Vec::new();
2066        self.diagnostics.groups(&mut groups, self);
2067        groups
2068    }
2069
2070    pub fn diagnostic_group<'a, O>(
2071        &'a self,
2072        group_id: usize,
2073    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2074    where
2075        O: 'a + FromAnchor,
2076    {
2077        self.diagnostics.group(group_id, self)
2078    }
2079
2080    pub fn diagnostics_update_count(&self) -> usize {
2081        self.diagnostics_update_count
2082    }
2083
2084    pub fn parse_count(&self) -> usize {
2085        self.parse_count
2086    }
2087
2088    pub fn selections_update_count(&self) -> usize {
2089        self.selections_update_count
2090    }
2091}
2092
2093impl Clone for BufferSnapshot {
2094    fn clone(&self) -> Self {
2095        Self {
2096            text: self.text.clone(),
2097            tree: self.tree.clone(),
2098            remote_selections: self.remote_selections.clone(),
2099            diagnostics: self.diagnostics.clone(),
2100            selections_update_count: self.selections_update_count,
2101            diagnostics_update_count: self.diagnostics_update_count,
2102            is_parsing: self.is_parsing,
2103            language: self.language.clone(),
2104            parse_count: self.parse_count,
2105        }
2106    }
2107}
2108
2109impl Deref for BufferSnapshot {
2110    type Target = text::BufferSnapshot;
2111
2112    fn deref(&self) -> &Self::Target {
2113        &self.text
2114    }
2115}
2116
2117impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
2118    type I = ByteChunks<'a>;
2119
2120    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
2121        ByteChunks(self.0.chunks_in_range(node.byte_range()))
2122    }
2123}
2124
2125struct ByteChunks<'a>(rope::Chunks<'a>);
2126
2127impl<'a> Iterator for ByteChunks<'a> {
2128    type Item = &'a [u8];
2129
2130    fn next(&mut self) -> Option<Self::Item> {
2131        self.0.next().map(str::as_bytes)
2132    }
2133}
2134
2135unsafe impl<'a> Send for BufferChunks<'a> {}
2136
2137impl<'a> BufferChunks<'a> {
2138    pub fn seek(&mut self, offset: usize) {
2139        self.range.start = offset;
2140        self.chunks.seek(self.range.start);
2141        if let Some(highlights) = self.highlights.as_mut() {
2142            highlights
2143                .stack
2144                .retain(|(end_offset, _)| *end_offset > offset);
2145            if let Some((mat, capture_ix)) = &highlights.next_capture {
2146                let capture = mat.captures[*capture_ix as usize];
2147                if offset >= capture.node.start_byte() {
2148                    let next_capture_end = capture.node.end_byte();
2149                    if offset < next_capture_end {
2150                        highlights.stack.push((
2151                            next_capture_end,
2152                            highlights.highlight_map.get(capture.index),
2153                        ));
2154                    }
2155                    highlights.next_capture.take();
2156                }
2157            }
2158            highlights.captures.set_byte_range(self.range.clone());
2159        }
2160    }
2161
2162    pub fn offset(&self) -> usize {
2163        self.range.start
2164    }
2165
2166    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2167        let depth = match endpoint.severity {
2168            DiagnosticSeverity::ERROR => &mut self.error_depth,
2169            DiagnosticSeverity::WARNING => &mut self.warning_depth,
2170            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2171            DiagnosticSeverity::HINT => &mut self.hint_depth,
2172            _ => return,
2173        };
2174        if endpoint.is_start {
2175            *depth += 1;
2176        } else {
2177            *depth -= 1;
2178        }
2179    }
2180
2181    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
2182        if self.error_depth > 0 {
2183            Some(DiagnosticSeverity::ERROR)
2184        } else if self.warning_depth > 0 {
2185            Some(DiagnosticSeverity::WARNING)
2186        } else if self.information_depth > 0 {
2187            Some(DiagnosticSeverity::INFORMATION)
2188        } else if self.hint_depth > 0 {
2189            Some(DiagnosticSeverity::HINT)
2190        } else {
2191            None
2192        }
2193    }
2194}
2195
2196impl<'a> Iterator for BufferChunks<'a> {
2197    type Item = Chunk<'a>;
2198
2199    fn next(&mut self) -> Option<Self::Item> {
2200        let mut next_capture_start = usize::MAX;
2201        let mut next_diagnostic_endpoint = usize::MAX;
2202
2203        if let Some(highlights) = self.highlights.as_mut() {
2204            while let Some((parent_capture_end, _)) = highlights.stack.last() {
2205                if *parent_capture_end <= self.range.start {
2206                    highlights.stack.pop();
2207                } else {
2208                    break;
2209                }
2210            }
2211
2212            if highlights.next_capture.is_none() {
2213                highlights.next_capture = highlights.captures.next();
2214            }
2215
2216            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
2217                let capture = mat.captures[*capture_ix as usize];
2218                if self.range.start < capture.node.start_byte() {
2219                    next_capture_start = capture.node.start_byte();
2220                    break;
2221                } else {
2222                    let highlight_id = highlights.highlight_map.get(capture.index);
2223                    highlights
2224                        .stack
2225                        .push((capture.node.end_byte(), highlight_id));
2226                    highlights.next_capture = highlights.captures.next();
2227                }
2228            }
2229        }
2230
2231        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2232            if endpoint.offset <= self.range.start {
2233                self.update_diagnostic_depths(endpoint);
2234                self.diagnostic_endpoints.next();
2235            } else {
2236                next_diagnostic_endpoint = endpoint.offset;
2237                break;
2238            }
2239        }
2240
2241        if let Some(chunk) = self.chunks.peek() {
2242            let chunk_start = self.range.start;
2243            let mut chunk_end = (self.chunks.offset() + chunk.len())
2244                .min(next_capture_start)
2245                .min(next_diagnostic_endpoint);
2246            let mut highlight_style = None;
2247            if let Some(highlights) = self.highlights.as_ref() {
2248                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2249                    chunk_end = chunk_end.min(*parent_capture_end);
2250                    highlight_style = parent_highlight_id.style(highlights.theme);
2251                }
2252            }
2253
2254            let slice =
2255                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2256            self.range.start = chunk_end;
2257            if self.range.start == self.chunks.offset() + chunk.len() {
2258                self.chunks.next().unwrap();
2259            }
2260
2261            Some(Chunk {
2262                text: slice,
2263                highlight_style,
2264                diagnostic: self.current_diagnostic_severity(),
2265            })
2266        } else {
2267            None
2268        }
2269    }
2270}
2271
2272impl QueryCursorHandle {
2273    pub(crate) fn new() -> Self {
2274        QueryCursorHandle(Some(
2275            QUERY_CURSORS
2276                .lock()
2277                .pop()
2278                .unwrap_or_else(|| QueryCursor::new()),
2279        ))
2280    }
2281}
2282
2283impl Deref for QueryCursorHandle {
2284    type Target = QueryCursor;
2285
2286    fn deref(&self) -> &Self::Target {
2287        self.0.as_ref().unwrap()
2288    }
2289}
2290
2291impl DerefMut for QueryCursorHandle {
2292    fn deref_mut(&mut self) -> &mut Self::Target {
2293        self.0.as_mut().unwrap()
2294    }
2295}
2296
2297impl Drop for QueryCursorHandle {
2298    fn drop(&mut self) {
2299        let mut cursor = self.0.take().unwrap();
2300        cursor.set_byte_range(0..usize::MAX);
2301        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2302        QUERY_CURSORS.lock().push(cursor)
2303    }
2304}
2305
2306trait ToTreeSitterPoint {
2307    fn to_ts_point(self) -> tree_sitter::Point;
2308    fn from_ts_point(point: tree_sitter::Point) -> Self;
2309}
2310
2311impl ToTreeSitterPoint for Point {
2312    fn to_ts_point(self) -> tree_sitter::Point {
2313        tree_sitter::Point::new(self.row as usize, self.column as usize)
2314    }
2315
2316    fn from_ts_point(point: tree_sitter::Point) -> Self {
2317        Point::new(point.row as u32, point.column as u32)
2318    }
2319}
2320
2321impl operation_queue::Operation for Operation {
2322    fn lamport_timestamp(&self) -> clock::Lamport {
2323        match self {
2324            Operation::Buffer(_) => {
2325                unreachable!("buffer operations should never be deferred at this layer")
2326            }
2327            Operation::UpdateDiagnostics {
2328                lamport_timestamp, ..
2329            }
2330            | Operation::UpdateSelections {
2331                lamport_timestamp, ..
2332            } => *lamport_timestamp,
2333        }
2334    }
2335}
2336
2337impl Default for Diagnostic {
2338    fn default() -> Self {
2339        Self {
2340            code: Default::default(),
2341            severity: DiagnosticSeverity::ERROR,
2342            message: Default::default(),
2343            group_id: Default::default(),
2344            is_primary: Default::default(),
2345            is_valid: true,
2346            is_disk_based: false,
2347        }
2348    }
2349}
2350
2351pub fn contiguous_ranges(
2352    values: impl Iterator<Item = u32>,
2353    max_len: usize,
2354) -> impl Iterator<Item = Range<u32>> {
2355    let mut values = values.into_iter();
2356    let mut current_range: Option<Range<u32>> = None;
2357    std::iter::from_fn(move || loop {
2358        if let Some(value) = values.next() {
2359            if let Some(range) = &mut current_range {
2360                if value == range.end && range.len() < max_len {
2361                    range.end += 1;
2362                    continue;
2363                }
2364            }
2365
2366            let prev_range = current_range.clone();
2367            current_range = Some(value..(value + 1));
2368            if prev_range.is_some() {
2369                return prev_range;
2370            }
2371        } else {
2372            return current_range.take();
2373        }
2374    })
2375}