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