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