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