lib.rs

   1mod highlight_map;
   2mod language;
   3pub mod proto;
   4#[cfg(test)]
   5mod tests;
   6
   7pub use self::{
   8    highlight_map::{HighlightId, HighlightMap},
   9    language::{BracketPair, Language, LanguageConfig, LanguageRegistry, LanguageServerConfig},
  10};
  11use anyhow::{anyhow, Result};
  12pub use buffer::{Buffer as TextBuffer, Operation as _, *};
  13use clock::ReplicaId;
  14use futures::FutureExt as _;
  15use gpui::{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,
  26    collections::{BTreeMap, HashMap, HashSet},
  27    ffi::OsString,
  28    future::Future,
  29    iter::{Iterator, Peekable},
  30    ops::{Deref, DerefMut, Range},
  31    path::{Path, PathBuf},
  32    str,
  33    sync::Arc,
  34    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  35    vec,
  36};
  37use tree_sitter::{InputEdit, Parser, QueryCursor, Tree};
  38use util::{post_inc, TryFutureExt as _};
  39
  40#[cfg(any(test, feature = "test-support"))]
  41pub use tree_sitter_rust;
  42
  43pub use lsp::DiagnosticSeverity;
  44
  45thread_local! {
  46    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  47}
  48
  49lazy_static! {
  50    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  51}
  52
  53// TODO - Make this configurable
  54const INDENT_SIZE: u32 = 4;
  55
  56pub struct Buffer {
  57    text: TextBuffer,
  58    file: Option<Box<dyn File>>,
  59    saved_version: clock::Global,
  60    saved_mtime: SystemTime,
  61    language: Option<Arc<Language>>,
  62    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  63    pending_autoindent: Option<Task<()>>,
  64    sync_parse_timeout: Duration,
  65    syntax_tree: Mutex<Option<SyntaxTree>>,
  66    parsing_in_background: bool,
  67    parse_count: usize,
  68    diagnostics: AnchorRangeMultimap<Diagnostic>,
  69    diagnostics_update_count: usize,
  70    language_server: Option<LanguageServerState>,
  71    #[cfg(test)]
  72    operations: Vec<Operation>,
  73}
  74
  75pub struct Snapshot {
  76    text: buffer::Snapshot,
  77    tree: Option<Tree>,
  78    diagnostics: AnchorRangeMultimap<Diagnostic>,
  79    is_parsing: bool,
  80    language: Option<Arc<Language>>,
  81    query_cursor: QueryCursorHandle,
  82}
  83
  84#[derive(Clone, Debug, PartialEq, Eq)]
  85pub struct Diagnostic {
  86    pub severity: DiagnosticSeverity,
  87    pub message: String,
  88}
  89
  90struct LanguageServerState {
  91    server: Arc<LanguageServer>,
  92    latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
  93    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
  94    next_version: usize,
  95    _maintain_server: Task<Option<()>>,
  96}
  97
  98#[derive(Clone)]
  99struct LanguageServerSnapshot {
 100    buffer_snapshot: buffer::Snapshot,
 101    version: usize,
 102    path: Arc<Path>,
 103}
 104
 105#[derive(Clone)]
 106pub enum Operation {
 107    Buffer(buffer::Operation),
 108    UpdateDiagnostics(AnchorRangeMultimap<Diagnostic>),
 109}
 110
 111#[derive(Clone, Debug, Eq, PartialEq)]
 112pub enum Event {
 113    Edited,
 114    Dirtied,
 115    Saved,
 116    FileHandleChanged,
 117    Reloaded,
 118    Reparsed,
 119    Closed,
 120}
 121
 122pub trait File {
 123    fn worktree_id(&self) -> usize;
 124
 125    fn entry_id(&self) -> Option<usize>;
 126
 127    fn mtime(&self) -> SystemTime;
 128
 129    /// Returns the path of this file relative to the worktree's root directory.
 130    fn path(&self) -> &Arc<Path>;
 131
 132    /// Returns the absolute path of this file.
 133    fn abs_path(&self) -> Option<PathBuf>;
 134
 135    /// Returns the path of this file relative to the worktree's parent directory (this means it
 136    /// includes the name of the worktree's root folder).
 137    fn full_path(&self) -> PathBuf;
 138
 139    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 140    /// of its worktree, then this method will return the name of the worktree itself.
 141    fn file_name(&self) -> Option<OsString>;
 142
 143    fn is_deleted(&self) -> bool;
 144
 145    fn save(
 146        &self,
 147        buffer_id: u64,
 148        text: Rope,
 149        version: clock::Global,
 150        cx: &mut MutableAppContext,
 151    ) -> Task<Result<(clock::Global, SystemTime)>>;
 152
 153    fn load_local(&self, cx: &AppContext) -> Option<Task<Result<String>>>;
 154
 155    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
 156
 157    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
 158
 159    fn boxed_clone(&self) -> Box<dyn File>;
 160
 161    fn as_any(&self) -> &dyn Any;
 162}
 163
 164struct QueryCursorHandle(Option<QueryCursor>);
 165
 166#[derive(Clone)]
 167struct SyntaxTree {
 168    tree: Tree,
 169    version: clock::Global,
 170}
 171
 172#[derive(Clone)]
 173struct AutoindentRequest {
 174    selection_set_ids: HashSet<SelectionSetId>,
 175    before_edit: Snapshot,
 176    edited: AnchorSet,
 177    inserted: Option<AnchorRangeSet>,
 178}
 179
 180#[derive(Debug)]
 181struct IndentSuggestion {
 182    basis_row: u32,
 183    indent: bool,
 184}
 185
 186struct TextProvider<'a>(&'a Rope);
 187
 188struct Highlights<'a> {
 189    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 190    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 191    stack: Vec<(usize, HighlightId)>,
 192    highlight_map: HighlightMap,
 193}
 194
 195pub struct HighlightedChunks<'a> {
 196    range: Range<usize>,
 197    chunks: Chunks<'a>,
 198    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 199    error_depth: usize,
 200    warning_depth: usize,
 201    information_depth: usize,
 202    hint_depth: usize,
 203    highlights: Option<Highlights<'a>>,
 204}
 205
 206#[derive(Clone, Copy, Debug, Default)]
 207pub struct HighlightedChunk<'a> {
 208    pub text: &'a str,
 209    pub highlight_id: HighlightId,
 210    pub diagnostic: Option<DiagnosticSeverity>,
 211}
 212
 213struct Diff {
 214    base_version: clock::Global,
 215    new_text: Arc<str>,
 216    changes: Vec<(ChangeTag, usize)>,
 217}
 218
 219#[derive(Clone, Copy)]
 220struct DiagnosticEndpoint {
 221    offset: usize,
 222    is_start: bool,
 223    severity: DiagnosticSeverity,
 224}
 225
 226impl Buffer {
 227    pub fn new<T: Into<Arc<str>>>(
 228        replica_id: ReplicaId,
 229        base_text: T,
 230        cx: &mut ModelContext<Self>,
 231    ) -> Self {
 232        Self::build(
 233            TextBuffer::new(
 234                replica_id,
 235                cx.model_id() as u64,
 236                History::new(base_text.into()),
 237            ),
 238            None,
 239        )
 240    }
 241
 242    pub fn from_file<T: Into<Arc<str>>>(
 243        replica_id: ReplicaId,
 244        base_text: T,
 245        file: Box<dyn File>,
 246        cx: &mut ModelContext<Self>,
 247    ) -> Self {
 248        Self::build(
 249            TextBuffer::new(
 250                replica_id,
 251                cx.model_id() as u64,
 252                History::new(base_text.into()),
 253            ),
 254            Some(file),
 255        )
 256    }
 257
 258    pub fn from_proto(
 259        replica_id: ReplicaId,
 260        message: proto::Buffer,
 261        file: Option<Box<dyn File>>,
 262        cx: &mut ModelContext<Self>,
 263    ) -> Result<Self> {
 264        let mut buffer =
 265            buffer::Buffer::new(replica_id, message.id, History::new(message.content.into()));
 266        let ops = message
 267            .history
 268            .into_iter()
 269            .map(|op| buffer::Operation::Edit(proto::deserialize_edit_operation(op)));
 270        buffer.apply_ops(ops)?;
 271        for set in message.selections {
 272            let set = proto::deserialize_selection_set(set);
 273            buffer.add_raw_selection_set(set.id, set);
 274        }
 275        let mut this = Self::build(buffer, file);
 276        if let Some(diagnostics) = message.diagnostics {
 277            this.apply_diagnostic_update(proto::deserialize_diagnostics(diagnostics), cx);
 278        }
 279        Ok(this)
 280    }
 281
 282    pub fn to_proto(&self) -> proto::Buffer {
 283        proto::Buffer {
 284            id: self.remote_id(),
 285            content: self.text.base_text().to_string(),
 286            history: self
 287                .text
 288                .history()
 289                .map(proto::serialize_edit_operation)
 290                .collect(),
 291            selections: self
 292                .selection_sets()
 293                .map(|(_, set)| proto::serialize_selection_set(set))
 294                .collect(),
 295            diagnostics: Some(proto::serialize_diagnostics(&self.diagnostics)),
 296        }
 297    }
 298
 299    pub fn with_language(
 300        mut self,
 301        language: Option<Arc<Language>>,
 302        language_server: Option<Arc<LanguageServer>>,
 303        cx: &mut ModelContext<Self>,
 304    ) -> Self {
 305        self.set_language(language, language_server, cx);
 306        self
 307    }
 308
 309    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 310        let saved_mtime;
 311        if let Some(file) = file.as_ref() {
 312            saved_mtime = file.mtime();
 313        } else {
 314            saved_mtime = UNIX_EPOCH;
 315        }
 316
 317        Self {
 318            text: buffer,
 319            saved_mtime,
 320            saved_version: clock::Global::new(),
 321            file,
 322            syntax_tree: Mutex::new(None),
 323            parsing_in_background: false,
 324            parse_count: 0,
 325            sync_parse_timeout: Duration::from_millis(1),
 326            autoindent_requests: Default::default(),
 327            pending_autoindent: Default::default(),
 328            language: None,
 329            diagnostics: Default::default(),
 330            diagnostics_update_count: 0,
 331            language_server: None,
 332            #[cfg(test)]
 333            operations: Default::default(),
 334        }
 335    }
 336
 337    pub fn snapshot(&self) -> Snapshot {
 338        Snapshot {
 339            text: self.text.snapshot(),
 340            tree: self.syntax_tree(),
 341            diagnostics: self.diagnostics.clone(),
 342            is_parsing: self.parsing_in_background,
 343            language: self.language.clone(),
 344            query_cursor: QueryCursorHandle::new(),
 345        }
 346    }
 347
 348    pub fn file(&self) -> Option<&dyn File> {
 349        self.file.as_deref()
 350    }
 351
 352    pub fn save(
 353        &mut self,
 354        cx: &mut ModelContext<Self>,
 355    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 356        let file = self
 357            .file
 358            .as_ref()
 359            .ok_or_else(|| anyhow!("buffer has no file"))?;
 360        let text = self.as_rope().clone();
 361        let version = self.version();
 362        let save = file.save(self.remote_id(), text, version, cx.as_mut());
 363        Ok(cx.spawn(|this, mut cx| async move {
 364            let (version, mtime) = save.await?;
 365            this.update(&mut cx, |this, cx| {
 366                this.did_save(version.clone(), mtime, None, cx);
 367            });
 368            Ok((version, mtime))
 369        }))
 370    }
 371
 372    pub fn set_language(
 373        &mut self,
 374        language: Option<Arc<Language>>,
 375        language_server: Option<Arc<lsp::LanguageServer>>,
 376        cx: &mut ModelContext<Self>,
 377    ) {
 378        self.language = language;
 379        self.language_server = if let Some(server) = language_server {
 380            let (latest_snapshot_tx, mut latest_snapshot_rx) = watch::channel();
 381            Some(LanguageServerState {
 382                latest_snapshot: latest_snapshot_tx,
 383                pending_snapshots: Default::default(),
 384                next_version: 0,
 385                server: server.clone(),
 386                _maintain_server: cx.background().spawn(
 387                    async move {
 388                        let mut prev_snapshot: Option<LanguageServerSnapshot> = None;
 389                        while let Some(snapshot) = latest_snapshot_rx.recv().await {
 390                            if let Some(snapshot) = snapshot {
 391                                let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
 392                                if let Some(prev_snapshot) = prev_snapshot {
 393                                    let changes = lsp::DidChangeTextDocumentParams {
 394                                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 395                                            uri,
 396                                            snapshot.version as i32,
 397                                        ),
 398                                        content_changes: snapshot
 399                                            .buffer_snapshot
 400                                            .edits_since::<(PointUtf16, usize)>(
 401                                                prev_snapshot.buffer_snapshot.version(),
 402                                            )
 403                                            .map(|edit| {
 404                                                let edit_start = edit.new.start.0;
 405                                                let edit_end = edit_start
 406                                                    + (edit.old.end.0 - edit.old.start.0);
 407                                                let new_text = snapshot
 408                                                    .buffer_snapshot
 409                                                    .text_for_range(
 410                                                        edit.new.start.1..edit.new.end.1,
 411                                                    )
 412                                                    .collect();
 413                                                lsp::TextDocumentContentChangeEvent {
 414                                                    range: Some(lsp::Range::new(
 415                                                        lsp::Position::new(
 416                                                            edit_start.row,
 417                                                            edit_start.column,
 418                                                        ),
 419                                                        lsp::Position::new(
 420                                                            edit_end.row,
 421                                                            edit_end.column,
 422                                                        ),
 423                                                    )),
 424                                                    range_length: None,
 425                                                    text: new_text,
 426                                                }
 427                                            })
 428                                            .collect(),
 429                                    };
 430                                    server
 431                                        .notify::<lsp::notification::DidChangeTextDocument>(changes)
 432                                        .await?;
 433                                } else {
 434                                    server
 435                                        .notify::<lsp::notification::DidOpenTextDocument>(
 436                                            lsp::DidOpenTextDocumentParams {
 437                                                text_document: lsp::TextDocumentItem::new(
 438                                                    uri,
 439                                                    Default::default(),
 440                                                    snapshot.version as i32,
 441                                                    snapshot.buffer_snapshot.text().into(),
 442                                                ),
 443                                            },
 444                                        )
 445                                        .await?;
 446                                }
 447
 448                                prev_snapshot = Some(snapshot);
 449                            }
 450                        }
 451                        Ok(())
 452                    }
 453                    .log_err(),
 454                ),
 455            })
 456        } else {
 457            None
 458        };
 459
 460        self.reparse(cx);
 461        self.update_language_server();
 462    }
 463
 464    pub fn did_save(
 465        &mut self,
 466        version: clock::Global,
 467        mtime: SystemTime,
 468        new_file: Option<Box<dyn File>>,
 469        cx: &mut ModelContext<Self>,
 470    ) {
 471        self.saved_mtime = mtime;
 472        self.saved_version = version;
 473        if let Some(new_file) = new_file {
 474            self.file = Some(new_file);
 475        }
 476        if let Some(state) = &self.language_server {
 477            cx.background()
 478                .spawn(
 479                    state
 480                        .server
 481                        .notify::<lsp::notification::DidSaveTextDocument>(
 482                            lsp::DidSaveTextDocumentParams {
 483                                text_document: lsp::TextDocumentIdentifier {
 484                                    uri: lsp::Url::from_file_path(
 485                                        self.file.as_ref().unwrap().abs_path().unwrap(),
 486                                    )
 487                                    .unwrap(),
 488                                },
 489                                text: None,
 490                            },
 491                        ),
 492                )
 493                .detach()
 494        }
 495        cx.emit(Event::Saved);
 496    }
 497
 498    pub fn file_updated(
 499        &mut self,
 500        new_file: Box<dyn File>,
 501        cx: &mut ModelContext<Self>,
 502    ) -> Option<Task<()>> {
 503        let old_file = self.file.as_ref()?;
 504        let mut file_changed = false;
 505        let mut task = None;
 506
 507        if new_file.path() != old_file.path() {
 508            file_changed = true;
 509        }
 510
 511        if new_file.is_deleted() {
 512            if !old_file.is_deleted() {
 513                file_changed = true;
 514                if !self.is_dirty() {
 515                    cx.emit(Event::Dirtied);
 516                }
 517            }
 518        } else {
 519            let new_mtime = new_file.mtime();
 520            if new_mtime != old_file.mtime() {
 521                file_changed = true;
 522
 523                if !self.is_dirty() {
 524                    task = Some(cx.spawn(|this, mut cx| {
 525                        async move {
 526                            let new_text = this.read_with(&cx, |this, cx| {
 527                                this.file.as_ref().and_then(|file| file.load_local(cx))
 528                            });
 529                            if let Some(new_text) = new_text {
 530                                let new_text = new_text.await?;
 531                                let diff = this
 532                                    .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
 533                                    .await;
 534                                this.update(&mut cx, |this, cx| {
 535                                    if this.apply_diff(diff, cx) {
 536                                        this.saved_version = this.version();
 537                                        this.saved_mtime = new_mtime;
 538                                        cx.emit(Event::Reloaded);
 539                                    }
 540                                });
 541                            }
 542                            Ok(())
 543                        }
 544                        .log_err()
 545                        .map(drop)
 546                    }));
 547                }
 548            }
 549        }
 550
 551        if file_changed {
 552            cx.emit(Event::FileHandleChanged);
 553        }
 554        self.file = Some(new_file);
 555        task
 556    }
 557
 558    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 559        cx.emit(Event::Closed);
 560    }
 561
 562    pub fn language(&self) -> Option<&Arc<Language>> {
 563        self.language.as_ref()
 564    }
 565
 566    pub fn parse_count(&self) -> usize {
 567        self.parse_count
 568    }
 569
 570    fn syntax_tree(&self) -> Option<Tree> {
 571        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 572            self.interpolate_tree(syntax_tree);
 573            Some(syntax_tree.tree.clone())
 574        } else {
 575            None
 576        }
 577    }
 578
 579    #[cfg(any(test, feature = "test-support"))]
 580    pub fn is_parsing(&self) -> bool {
 581        self.parsing_in_background
 582    }
 583
 584    #[cfg(test)]
 585    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 586        self.sync_parse_timeout = timeout;
 587    }
 588
 589    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 590        if self.parsing_in_background {
 591            return false;
 592        }
 593
 594        if let Some(language) = self.language.clone() {
 595            let old_tree = self.syntax_tree();
 596            let text = self.as_rope().clone();
 597            let parsed_version = self.version();
 598            let parse_task = cx.background().spawn({
 599                let language = language.clone();
 600                async move { Self::parse_text(&text, old_tree, &language) }
 601            });
 602
 603            match cx
 604                .background()
 605                .block_with_timeout(self.sync_parse_timeout, parse_task)
 606            {
 607                Ok(new_tree) => {
 608                    self.did_finish_parsing(new_tree, parsed_version, cx);
 609                    return true;
 610                }
 611                Err(parse_task) => {
 612                    self.parsing_in_background = true;
 613                    cx.spawn(move |this, mut cx| async move {
 614                        let new_tree = parse_task.await;
 615                        this.update(&mut cx, move |this, cx| {
 616                            let language_changed =
 617                                this.language.as_ref().map_or(true, |curr_language| {
 618                                    !Arc::ptr_eq(curr_language, &language)
 619                                });
 620                            let parse_again = this.version > parsed_version || language_changed;
 621                            this.parsing_in_background = false;
 622                            this.did_finish_parsing(new_tree, parsed_version, cx);
 623
 624                            if parse_again && this.reparse(cx) {
 625                                return;
 626                            }
 627                        });
 628                    })
 629                    .detach();
 630                }
 631            }
 632        }
 633        false
 634    }
 635
 636    fn parse_text(text: &Rope, old_tree: Option<Tree>, language: &Language) -> Tree {
 637        PARSER.with(|parser| {
 638            let mut parser = parser.borrow_mut();
 639            parser
 640                .set_language(language.grammar)
 641                .expect("incompatible grammar");
 642            let mut chunks = text.chunks_in_range(0..text.len());
 643            let tree = parser
 644                .parse_with(
 645                    &mut move |offset, _| {
 646                        chunks.seek(offset);
 647                        chunks.next().unwrap_or("").as_bytes()
 648                    },
 649                    old_tree.as_ref(),
 650                )
 651                .unwrap();
 652            tree
 653        })
 654    }
 655
 656    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 657        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 658            let (bytes, lines) = edit.flatten();
 659            tree.tree.edit(&InputEdit {
 660                start_byte: bytes.new.start,
 661                old_end_byte: bytes.new.start + bytes.old.len(),
 662                new_end_byte: bytes.new.end,
 663                start_position: lines.new.start.to_ts_point(),
 664                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 665                    .to_ts_point(),
 666                new_end_position: lines.new.end.to_ts_point(),
 667            });
 668        }
 669        tree.version = self.version();
 670    }
 671
 672    fn did_finish_parsing(
 673        &mut self,
 674        tree: Tree,
 675        version: clock::Global,
 676        cx: &mut ModelContext<Self>,
 677    ) {
 678        self.parse_count += 1;
 679        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 680        self.request_autoindent(cx);
 681        cx.emit(Event::Reparsed);
 682        cx.notify();
 683    }
 684
 685    pub fn update_diagnostics(
 686        &mut self,
 687        version: Option<i32>,
 688        mut diagnostics: Vec<lsp::Diagnostic>,
 689        cx: &mut ModelContext<Self>,
 690    ) -> Result<Operation> {
 691        let version = version.map(|version| version as usize);
 692        let content = if let Some(version) = version {
 693            let language_server = self.language_server.as_mut().unwrap();
 694            let snapshot = language_server
 695                .pending_snapshots
 696                .get(&version)
 697                .ok_or_else(|| anyhow!("missing snapshot"))?;
 698            snapshot.buffer_snapshot.content()
 699        } else {
 700            self.content()
 701        };
 702
 703        let empty_set = HashSet::new();
 704        let disk_based_sources = self
 705            .language
 706            .as_ref()
 707            .and_then(|language| language.disk_based_diagnostic_sources())
 708            .unwrap_or(&empty_set);
 709
 710        diagnostics.sort_unstable_by_key(|d| (d.range.start, d.range.end));
 711        self.diagnostics = {
 712            let mut edits_since_save = content
 713                .edits_since::<PointUtf16>(&self.saved_version)
 714                .peekable();
 715            let mut last_edit_old_end = PointUtf16::zero();
 716            let mut last_edit_new_end = PointUtf16::zero();
 717
 718            content.anchor_range_multimap(
 719                Bias::Left,
 720                Bias::Right,
 721                diagnostics.into_iter().filter_map(|diagnostic| {
 722                    let mut start = PointUtf16::new(
 723                        diagnostic.range.start.line,
 724                        diagnostic.range.start.character,
 725                    );
 726                    let mut end =
 727                        PointUtf16::new(diagnostic.range.end.line, diagnostic.range.end.character);
 728                    if diagnostic
 729                        .source
 730                        .as_ref()
 731                        .map_or(false, |source| disk_based_sources.contains(source))
 732                    {
 733                        while let Some(edit) = edits_since_save.peek() {
 734                            if edit.old.end <= start {
 735                                last_edit_old_end = edit.old.end;
 736                                last_edit_new_end = edit.new.end;
 737                                edits_since_save.next();
 738                            } else if edit.old.start <= end && edit.old.end >= start {
 739                                return None;
 740                            } else {
 741                                break;
 742                            }
 743                        }
 744
 745                        start = last_edit_new_end + (start - last_edit_old_end);
 746                        end = last_edit_new_end + (end - last_edit_old_end);
 747                    }
 748
 749                    let mut range = content.clip_point_utf16(start, Bias::Left)
 750                        ..content.clip_point_utf16(end, Bias::Right);
 751                    if range.start == range.end {
 752                        range.end.column += 1;
 753                        range.end = content.clip_point_utf16(range.end, Bias::Right);
 754                    }
 755                    Some((
 756                        range,
 757                        Diagnostic {
 758                            severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
 759                            message: diagnostic.message,
 760                        },
 761                    ))
 762                }),
 763            )
 764        };
 765
 766        if let Some(version) = version {
 767            let language_server = self.language_server.as_mut().unwrap();
 768            let versions_to_delete = language_server
 769                .pending_snapshots
 770                .range(..version)
 771                .map(|(v, _)| *v)
 772                .collect::<Vec<_>>();
 773            for version in versions_to_delete {
 774                language_server.pending_snapshots.remove(&version);
 775            }
 776        }
 777
 778        self.diagnostics_update_count += 1;
 779        cx.notify();
 780        Ok(Operation::UpdateDiagnostics(self.diagnostics.clone()))
 781    }
 782
 783    pub fn diagnostics_in_range<'a, T, O>(
 784        &'a self,
 785        range: Range<T>,
 786    ) -> impl Iterator<Item = (Range<O>, &Diagnostic)> + 'a
 787    where
 788        T: 'a + ToOffset,
 789        O: 'a + FromAnchor,
 790    {
 791        let content = self.content();
 792        self.diagnostics
 793            .intersecting_ranges(range, content, true)
 794            .map(move |(_, range, diagnostic)| (range, diagnostic))
 795    }
 796
 797    pub fn diagnostics_update_count(&self) -> usize {
 798        self.diagnostics_update_count
 799    }
 800
 801    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 802        if let Some(indent_columns) = self.compute_autoindents() {
 803            let indent_columns = cx.background().spawn(indent_columns);
 804            match cx
 805                .background()
 806                .block_with_timeout(Duration::from_micros(500), indent_columns)
 807            {
 808                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 809                Err(indent_columns) => {
 810                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 811                        let indent_columns = indent_columns.await;
 812                        this.update(&mut cx, |this, cx| {
 813                            this.apply_autoindents(indent_columns, cx);
 814                        });
 815                    }));
 816                }
 817            }
 818        }
 819    }
 820
 821    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 822        let max_rows_between_yields = 100;
 823        let snapshot = self.snapshot();
 824        if snapshot.language.is_none()
 825            || snapshot.tree.is_none()
 826            || self.autoindent_requests.is_empty()
 827        {
 828            return None;
 829        }
 830
 831        let autoindent_requests = self.autoindent_requests.clone();
 832        Some(async move {
 833            let mut indent_columns = BTreeMap::new();
 834            for request in autoindent_requests {
 835                let old_to_new_rows = request
 836                    .edited
 837                    .iter::<Point, _>(&request.before_edit)
 838                    .map(|point| point.row)
 839                    .zip(
 840                        request
 841                            .edited
 842                            .iter::<Point, _>(&snapshot)
 843                            .map(|point| point.row),
 844                    )
 845                    .collect::<BTreeMap<u32, u32>>();
 846
 847                let mut old_suggestions = HashMap::<u32, u32>::default();
 848                let old_edited_ranges =
 849                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 850                for old_edited_range in old_edited_ranges {
 851                    let suggestions = request
 852                        .before_edit
 853                        .suggest_autoindents(old_edited_range.clone())
 854                        .into_iter()
 855                        .flatten();
 856                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 857                        let indentation_basis = old_to_new_rows
 858                            .get(&suggestion.basis_row)
 859                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 860                            .unwrap_or_else(|| {
 861                                request
 862                                    .before_edit
 863                                    .indent_column_for_line(suggestion.basis_row)
 864                            });
 865                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 866                        old_suggestions.insert(
 867                            *old_to_new_rows.get(&old_row).unwrap(),
 868                            indentation_basis + delta,
 869                        );
 870                    }
 871                    yield_now().await;
 872                }
 873
 874                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 875                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 876                let new_edited_row_ranges =
 877                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 878                for new_edited_row_range in new_edited_row_ranges {
 879                    let suggestions = snapshot
 880                        .suggest_autoindents(new_edited_row_range.clone())
 881                        .into_iter()
 882                        .flatten();
 883                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 884                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 885                        let new_indentation = indent_columns
 886                            .get(&suggestion.basis_row)
 887                            .copied()
 888                            .unwrap_or_else(|| {
 889                                snapshot.indent_column_for_line(suggestion.basis_row)
 890                            })
 891                            + delta;
 892                        if old_suggestions
 893                            .get(&new_row)
 894                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 895                        {
 896                            indent_columns.insert(new_row, new_indentation);
 897                        }
 898                    }
 899                    yield_now().await;
 900                }
 901
 902                if let Some(inserted) = request.inserted.as_ref() {
 903                    let inserted_row_ranges = contiguous_ranges(
 904                        inserted
 905                            .ranges::<Point, _>(&snapshot)
 906                            .flat_map(|range| range.start.row..range.end.row + 1),
 907                        max_rows_between_yields,
 908                    );
 909                    for inserted_row_range in inserted_row_ranges {
 910                        let suggestions = snapshot
 911                            .suggest_autoindents(inserted_row_range.clone())
 912                            .into_iter()
 913                            .flatten();
 914                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
 915                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 916                            let new_indentation = indent_columns
 917                                .get(&suggestion.basis_row)
 918                                .copied()
 919                                .unwrap_or_else(|| {
 920                                    snapshot.indent_column_for_line(suggestion.basis_row)
 921                                })
 922                                + delta;
 923                            indent_columns.insert(row, new_indentation);
 924                        }
 925                        yield_now().await;
 926                    }
 927                }
 928            }
 929            indent_columns
 930        })
 931    }
 932
 933    fn apply_autoindents(
 934        &mut self,
 935        indent_columns: BTreeMap<u32, u32>,
 936        cx: &mut ModelContext<Self>,
 937    ) {
 938        let selection_set_ids = self
 939            .autoindent_requests
 940            .drain(..)
 941            .flat_map(|req| req.selection_set_ids.clone())
 942            .collect::<HashSet<_>>();
 943
 944        self.start_transaction(selection_set_ids.iter().copied())
 945            .unwrap();
 946        for (row, indent_column) in &indent_columns {
 947            self.set_indent_column_for_line(*row, *indent_column, cx);
 948        }
 949
 950        for selection_set_id in &selection_set_ids {
 951            if let Ok(set) = self.selection_set(*selection_set_id) {
 952                let new_selections = set
 953                    .selections::<Point, _>(&*self)
 954                    .map(|selection| {
 955                        if selection.start.column == 0 {
 956                            let delta = Point::new(
 957                                0,
 958                                indent_columns
 959                                    .get(&selection.start.row)
 960                                    .copied()
 961                                    .unwrap_or(0),
 962                            );
 963                            if delta.column > 0 {
 964                                return Selection {
 965                                    id: selection.id,
 966                                    goal: selection.goal,
 967                                    reversed: selection.reversed,
 968                                    start: selection.start + delta,
 969                                    end: selection.end + delta,
 970                                };
 971                            }
 972                        }
 973                        selection
 974                    })
 975                    .collect::<Vec<_>>();
 976                self.update_selection_set(*selection_set_id, &new_selections, cx)
 977                    .unwrap();
 978            }
 979        }
 980
 981        self.end_transaction(selection_set_ids.iter().copied(), cx)
 982            .unwrap();
 983    }
 984
 985    pub fn indent_column_for_line(&self, row: u32) -> u32 {
 986        self.content().indent_column_for_line(row)
 987    }
 988
 989    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
 990        let current_column = self.indent_column_for_line(row);
 991        if column > current_column {
 992            let offset = Point::new(row, 0).to_offset(&*self);
 993            self.edit(
 994                [offset..offset],
 995                " ".repeat((column - current_column) as usize),
 996                cx,
 997            );
 998        } else if column < current_column {
 999            self.edit(
1000                [Point::new(row, 0)..Point::new(row, current_column - column)],
1001                "",
1002                cx,
1003            );
1004        }
1005    }
1006
1007    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1008        if let Some(tree) = self.syntax_tree() {
1009            let root = tree.root_node();
1010            let range = range.start.to_offset(self)..range.end.to_offset(self);
1011            let mut node = root.descendant_for_byte_range(range.start, range.end);
1012            while node.map_or(false, |n| n.byte_range() == range) {
1013                node = node.unwrap().parent();
1014            }
1015            node.map(|n| n.byte_range())
1016        } else {
1017            None
1018        }
1019    }
1020
1021    pub fn enclosing_bracket_ranges<T: ToOffset>(
1022        &self,
1023        range: Range<T>,
1024    ) -> Option<(Range<usize>, Range<usize>)> {
1025        let (lang, tree) = self.language.as_ref().zip(self.syntax_tree())?;
1026        let open_capture_ix = lang.brackets_query.capture_index_for_name("open")?;
1027        let close_capture_ix = lang.brackets_query.capture_index_for_name("close")?;
1028
1029        // Find bracket pairs that *inclusively* contain the given range.
1030        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1031        let mut cursor = QueryCursorHandle::new();
1032        let matches = cursor.set_byte_range(range).matches(
1033            &lang.brackets_query,
1034            tree.root_node(),
1035            TextProvider(self.as_rope()),
1036        );
1037
1038        // Get the ranges of the innermost pair of brackets.
1039        matches
1040            .filter_map(|mat| {
1041                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1042                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1043                Some((open.byte_range(), close.byte_range()))
1044            })
1045            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1046    }
1047
1048    fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1049        // TODO: it would be nice to not allocate here.
1050        let old_text = self.text();
1051        let base_version = self.version();
1052        cx.background().spawn(async move {
1053            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1054                .iter_all_changes()
1055                .map(|c| (c.tag(), c.value().len()))
1056                .collect::<Vec<_>>();
1057            Diff {
1058                base_version,
1059                new_text,
1060                changes,
1061            }
1062        })
1063    }
1064
1065    fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1066        if self.version == diff.base_version {
1067            self.start_transaction(None).unwrap();
1068            let mut offset = 0;
1069            for (tag, len) in diff.changes {
1070                let range = offset..(offset + len);
1071                match tag {
1072                    ChangeTag::Equal => offset += len,
1073                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1074                    ChangeTag::Insert => {
1075                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1076                        offset += len;
1077                    }
1078                }
1079            }
1080            self.end_transaction(None, cx).unwrap();
1081            true
1082        } else {
1083            false
1084        }
1085    }
1086
1087    pub fn is_dirty(&self) -> bool {
1088        self.version > self.saved_version
1089            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1090    }
1091
1092    pub fn has_conflict(&self) -> bool {
1093        self.version > self.saved_version
1094            && self
1095                .file
1096                .as_ref()
1097                .map_or(false, |file| file.mtime() > self.saved_mtime)
1098    }
1099
1100    pub fn start_transaction(
1101        &mut self,
1102        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1103    ) -> Result<()> {
1104        self.start_transaction_at(selection_set_ids, Instant::now())
1105    }
1106
1107    fn start_transaction_at(
1108        &mut self,
1109        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1110        now: Instant,
1111    ) -> Result<()> {
1112        self.text.start_transaction_at(selection_set_ids, now)
1113    }
1114
1115    pub fn end_transaction(
1116        &mut self,
1117        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1118        cx: &mut ModelContext<Self>,
1119    ) -> Result<()> {
1120        self.end_transaction_at(selection_set_ids, Instant::now(), cx)
1121    }
1122
1123    fn end_transaction_at(
1124        &mut self,
1125        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1126        now: Instant,
1127        cx: &mut ModelContext<Self>,
1128    ) -> Result<()> {
1129        if let Some(start_version) = self.text.end_transaction_at(selection_set_ids, now) {
1130            let was_dirty = start_version != self.saved_version;
1131            self.did_edit(&start_version, was_dirty, cx);
1132        }
1133        Ok(())
1134    }
1135
1136    fn update_language_server(&mut self) {
1137        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1138            language_server
1139        } else {
1140            return;
1141        };
1142        let abs_path = self
1143            .file
1144            .as_ref()
1145            .map_or(Path::new("/").to_path_buf(), |file| {
1146                file.abs_path().unwrap()
1147            });
1148
1149        let version = post_inc(&mut language_server.next_version);
1150        let snapshot = LanguageServerSnapshot {
1151            buffer_snapshot: self.text.snapshot(),
1152            version,
1153            path: Arc::from(abs_path),
1154        };
1155        language_server
1156            .pending_snapshots
1157            .insert(version, snapshot.clone());
1158        let _ = language_server
1159            .latest_snapshot
1160            .blocking_send(Some(snapshot));
1161    }
1162
1163    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1164    where
1165        I: IntoIterator<Item = Range<S>>,
1166        S: ToOffset,
1167        T: Into<String>,
1168    {
1169        self.edit_internal(ranges_iter, new_text, false, cx)
1170    }
1171
1172    pub fn edit_with_autoindent<I, S, T>(
1173        &mut self,
1174        ranges_iter: I,
1175        new_text: T,
1176        cx: &mut ModelContext<Self>,
1177    ) where
1178        I: IntoIterator<Item = Range<S>>,
1179        S: ToOffset,
1180        T: Into<String>,
1181    {
1182        self.edit_internal(ranges_iter, new_text, true, cx)
1183    }
1184
1185    pub fn edit_internal<I, S, T>(
1186        &mut self,
1187        ranges_iter: I,
1188        new_text: T,
1189        autoindent: bool,
1190        cx: &mut ModelContext<Self>,
1191    ) where
1192        I: IntoIterator<Item = Range<S>>,
1193        S: ToOffset,
1194        T: Into<String>,
1195    {
1196        let new_text = new_text.into();
1197
1198        // Skip invalid ranges and coalesce contiguous ones.
1199        let mut ranges: Vec<Range<usize>> = Vec::new();
1200        for range in ranges_iter {
1201            let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1202            if !new_text.is_empty() || !range.is_empty() {
1203                if let Some(prev_range) = ranges.last_mut() {
1204                    if prev_range.end >= range.start {
1205                        prev_range.end = cmp::max(prev_range.end, range.end);
1206                    } else {
1207                        ranges.push(range);
1208                    }
1209                } else {
1210                    ranges.push(range);
1211                }
1212            }
1213        }
1214        if ranges.is_empty() {
1215            return;
1216        }
1217
1218        self.start_transaction(None).unwrap();
1219        self.pending_autoindent.take();
1220        let autoindent_request = if autoindent && self.language.is_some() {
1221            let before_edit = self.snapshot();
1222            let edited = self.content().anchor_set(ranges.iter().filter_map(|range| {
1223                let start = range.start.to_point(&*self);
1224                if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1225                    None
1226                } else {
1227                    Some((range.start, Bias::Left))
1228                }
1229            }));
1230            Some((before_edit, edited))
1231        } else {
1232            None
1233        };
1234
1235        let first_newline_ix = new_text.find('\n');
1236        let new_text_len = new_text.len();
1237
1238        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1239
1240        if let Some((before_edit, edited)) = autoindent_request {
1241            let mut inserted = None;
1242            if let Some(first_newline_ix) = first_newline_ix {
1243                let mut delta = 0isize;
1244                inserted = Some(self.content().anchor_range_set(ranges.iter().map(|range| {
1245                    let start = (delta + range.start as isize) as usize + first_newline_ix + 1;
1246                    let end = (delta + range.start as isize) as usize + new_text_len;
1247                    delta += (range.end as isize - range.start as isize) + new_text_len as isize;
1248                    (start, Bias::Left)..(end, Bias::Right)
1249                })));
1250            }
1251
1252            let selection_set_ids = self
1253                .text
1254                .peek_undo_stack()
1255                .unwrap()
1256                .starting_selection_set_ids()
1257                .collect();
1258            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1259                selection_set_ids,
1260                before_edit,
1261                edited,
1262                inserted,
1263            }));
1264        }
1265
1266        self.end_transaction(None, cx).unwrap();
1267        self.send_operation(Operation::Buffer(buffer::Operation::Edit(edit)), cx);
1268    }
1269
1270    fn did_edit(
1271        &mut self,
1272        old_version: &clock::Global,
1273        was_dirty: bool,
1274        cx: &mut ModelContext<Self>,
1275    ) {
1276        if self.edits_since::<usize>(old_version).next().is_none() {
1277            return;
1278        }
1279
1280        self.reparse(cx);
1281        self.update_language_server();
1282
1283        cx.emit(Event::Edited);
1284        if !was_dirty {
1285            cx.emit(Event::Dirtied);
1286        }
1287        cx.notify();
1288    }
1289
1290    pub fn add_selection_set<T: ToOffset>(
1291        &mut self,
1292        selections: &[Selection<T>],
1293        cx: &mut ModelContext<Self>,
1294    ) -> SelectionSetId {
1295        let operation = self.text.add_selection_set(selections);
1296        if let buffer::Operation::UpdateSelections { set_id, .. } = &operation {
1297            let set_id = *set_id;
1298            cx.notify();
1299            self.send_operation(Operation::Buffer(operation), cx);
1300            set_id
1301        } else {
1302            unreachable!()
1303        }
1304    }
1305
1306    pub fn update_selection_set<T: ToOffset>(
1307        &mut self,
1308        set_id: SelectionSetId,
1309        selections: &[Selection<T>],
1310        cx: &mut ModelContext<Self>,
1311    ) -> Result<()> {
1312        let operation = self.text.update_selection_set(set_id, selections)?;
1313        cx.notify();
1314        self.send_operation(Operation::Buffer(operation), cx);
1315        Ok(())
1316    }
1317
1318    pub fn set_active_selection_set(
1319        &mut self,
1320        set_id: Option<SelectionSetId>,
1321        cx: &mut ModelContext<Self>,
1322    ) -> Result<()> {
1323        let operation = self.text.set_active_selection_set(set_id)?;
1324        self.send_operation(Operation::Buffer(operation), cx);
1325        Ok(())
1326    }
1327
1328    pub fn remove_selection_set(
1329        &mut self,
1330        set_id: SelectionSetId,
1331        cx: &mut ModelContext<Self>,
1332    ) -> Result<()> {
1333        let operation = self.text.remove_selection_set(set_id)?;
1334        cx.notify();
1335        self.send_operation(Operation::Buffer(operation), cx);
1336        Ok(())
1337    }
1338
1339    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1340        &mut self,
1341        ops: I,
1342        cx: &mut ModelContext<Self>,
1343    ) -> Result<()> {
1344        self.pending_autoindent.take();
1345        let was_dirty = self.is_dirty();
1346        let old_version = self.version.clone();
1347        let buffer_ops = ops
1348            .into_iter()
1349            .filter_map(|op| match op {
1350                Operation::Buffer(op) => Some(op),
1351                Operation::UpdateDiagnostics(diagnostics) => {
1352                    self.apply_diagnostic_update(diagnostics, cx);
1353                    None
1354                }
1355            })
1356            .collect::<Vec<_>>();
1357        self.text.apply_ops(buffer_ops)?;
1358        self.did_edit(&old_version, was_dirty, cx);
1359        // Notify independently of whether the buffer was edited as the operations could include a
1360        // selection update.
1361        cx.notify();
1362        Ok(())
1363    }
1364
1365    fn apply_diagnostic_update(
1366        &mut self,
1367        diagnostics: AnchorRangeMultimap<Diagnostic>,
1368        cx: &mut ModelContext<Self>,
1369    ) {
1370        self.diagnostics = diagnostics;
1371        self.diagnostics_update_count += 1;
1372        cx.notify();
1373    }
1374
1375    #[cfg(not(test))]
1376    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1377        if let Some(file) = &self.file {
1378            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1379        }
1380    }
1381
1382    #[cfg(test)]
1383    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1384        self.operations.push(operation);
1385    }
1386
1387    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1388        self.text.remove_peer(replica_id);
1389        cx.notify();
1390    }
1391
1392    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
1393        let was_dirty = self.is_dirty();
1394        let old_version = self.version.clone();
1395
1396        for operation in self.text.undo() {
1397            self.send_operation(Operation::Buffer(operation), cx);
1398        }
1399
1400        self.did_edit(&old_version, was_dirty, cx);
1401    }
1402
1403    pub fn redo(&mut self, cx: &mut ModelContext<Self>) {
1404        let was_dirty = self.is_dirty();
1405        let old_version = self.version.clone();
1406
1407        for operation in self.text.redo() {
1408            self.send_operation(Operation::Buffer(operation), cx);
1409        }
1410
1411        self.did_edit(&old_version, was_dirty, cx);
1412    }
1413}
1414
1415#[cfg(any(test, feature = "test-support"))]
1416impl Buffer {
1417    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize)
1418    where
1419        T: rand::Rng,
1420    {
1421        self.text.randomly_edit(rng, old_range_count);
1422    }
1423
1424    pub fn randomly_mutate<T>(&mut self, rng: &mut T)
1425    where
1426        T: rand::Rng,
1427    {
1428        self.text.randomly_mutate(rng);
1429    }
1430}
1431
1432impl Entity for Buffer {
1433    type Event = Event;
1434
1435    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1436        if let Some(file) = self.file.as_ref() {
1437            file.buffer_removed(self.remote_id(), cx);
1438        }
1439    }
1440}
1441
1442// TODO: Do we need to clone a buffer?
1443impl Clone for Buffer {
1444    fn clone(&self) -> Self {
1445        Self {
1446            text: self.text.clone(),
1447            saved_version: self.saved_version.clone(),
1448            saved_mtime: self.saved_mtime,
1449            file: self.file.as_ref().map(|f| f.boxed_clone()),
1450            language: self.language.clone(),
1451            syntax_tree: Mutex::new(self.syntax_tree.lock().clone()),
1452            parsing_in_background: false,
1453            sync_parse_timeout: self.sync_parse_timeout,
1454            parse_count: self.parse_count,
1455            autoindent_requests: Default::default(),
1456            pending_autoindent: Default::default(),
1457            diagnostics: self.diagnostics.clone(),
1458            diagnostics_update_count: self.diagnostics_update_count,
1459            language_server: None,
1460            #[cfg(test)]
1461            operations: self.operations.clone(),
1462        }
1463    }
1464}
1465
1466impl Deref for Buffer {
1467    type Target = TextBuffer;
1468
1469    fn deref(&self) -> &Self::Target {
1470        &self.text
1471    }
1472}
1473
1474impl<'a> From<&'a Buffer> for Content<'a> {
1475    fn from(buffer: &'a Buffer) -> Self {
1476        Self::from(&buffer.text)
1477    }
1478}
1479
1480impl<'a> From<&'a mut Buffer> for Content<'a> {
1481    fn from(buffer: &'a mut Buffer) -> Self {
1482        Self::from(&buffer.text)
1483    }
1484}
1485
1486impl<'a> From<&'a Snapshot> for Content<'a> {
1487    fn from(snapshot: &'a Snapshot) -> Self {
1488        Self::from(&snapshot.text)
1489    }
1490}
1491
1492impl Snapshot {
1493    fn suggest_autoindents<'a>(
1494        &'a self,
1495        row_range: Range<u32>,
1496    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1497        let mut query_cursor = QueryCursorHandle::new();
1498        if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1499            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1500
1501            // Get the "indentation ranges" that intersect this row range.
1502            let indent_capture_ix = language.indents_query.capture_index_for_name("indent");
1503            let end_capture_ix = language.indents_query.capture_index_for_name("end");
1504            query_cursor.set_point_range(
1505                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1506                    ..Point::new(row_range.end, 0).to_ts_point(),
1507            );
1508            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1509            for mat in query_cursor.matches(
1510                &language.indents_query,
1511                tree.root_node(),
1512                TextProvider(self.as_rope()),
1513            ) {
1514                let mut node_kind = "";
1515                let mut start: Option<Point> = None;
1516                let mut end: Option<Point> = None;
1517                for capture in mat.captures {
1518                    if Some(capture.index) == indent_capture_ix {
1519                        node_kind = capture.node.kind();
1520                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1521                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1522                    } else if Some(capture.index) == end_capture_ix {
1523                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1524                    }
1525                }
1526
1527                if let Some((start, end)) = start.zip(end) {
1528                    if start.row == end.row {
1529                        continue;
1530                    }
1531
1532                    let range = start..end;
1533                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1534                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1535                        Ok(ix) => {
1536                            let prev_range = &mut indentation_ranges[ix];
1537                            prev_range.0.end = prev_range.0.end.max(range.end);
1538                        }
1539                    }
1540                }
1541            }
1542
1543            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1544            Some(row_range.map(move |row| {
1545                let row_start = Point::new(row, self.indent_column_for_line(row));
1546
1547                let mut indent_from_prev_row = false;
1548                let mut outdent_to_row = u32::MAX;
1549                for (range, _node_kind) in &indentation_ranges {
1550                    if range.start.row >= row {
1551                        break;
1552                    }
1553
1554                    if range.start.row == prev_row && range.end > row_start {
1555                        indent_from_prev_row = true;
1556                    }
1557                    if range.end.row >= prev_row && range.end <= row_start {
1558                        outdent_to_row = outdent_to_row.min(range.start.row);
1559                    }
1560                }
1561
1562                let suggestion = if outdent_to_row == prev_row {
1563                    IndentSuggestion {
1564                        basis_row: prev_row,
1565                        indent: false,
1566                    }
1567                } else if indent_from_prev_row {
1568                    IndentSuggestion {
1569                        basis_row: prev_row,
1570                        indent: true,
1571                    }
1572                } else if outdent_to_row < prev_row {
1573                    IndentSuggestion {
1574                        basis_row: outdent_to_row,
1575                        indent: false,
1576                    }
1577                } else {
1578                    IndentSuggestion {
1579                        basis_row: prev_row,
1580                        indent: false,
1581                    }
1582                };
1583
1584                prev_row = row;
1585                suggestion
1586            }))
1587        } else {
1588            None
1589        }
1590    }
1591
1592    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1593        while row > 0 {
1594            row -= 1;
1595            if !self.is_line_blank(row) {
1596                return Some(row);
1597            }
1598        }
1599        None
1600    }
1601
1602    fn is_line_blank(&self, row: u32) -> bool {
1603        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1604            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1605    }
1606
1607    pub fn highlighted_text_for_range<T: ToOffset>(
1608        &mut self,
1609        range: Range<T>,
1610    ) -> HighlightedChunks {
1611        let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1612
1613        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1614        for (_, range, diagnostic) in
1615            self.diagnostics
1616                .intersecting_ranges(range.clone(), self.content(), true)
1617        {
1618            diagnostic_endpoints.push(DiagnosticEndpoint {
1619                offset: range.start,
1620                is_start: true,
1621                severity: diagnostic.severity,
1622            });
1623            diagnostic_endpoints.push(DiagnosticEndpoint {
1624                offset: range.end,
1625                is_start: false,
1626                severity: diagnostic.severity,
1627            });
1628        }
1629        diagnostic_endpoints.sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1630        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1631
1632        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1633        let highlights =
1634            if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1635                let captures = self.query_cursor.set_byte_range(range.clone()).captures(
1636                    &language.highlights_query,
1637                    tree.root_node(),
1638                    TextProvider(self.text.as_rope()),
1639                );
1640
1641                Some(Highlights {
1642                    captures,
1643                    next_capture: None,
1644                    stack: Default::default(),
1645                    highlight_map: language.highlight_map(),
1646                })
1647            } else {
1648                None
1649            };
1650
1651        HighlightedChunks {
1652            range,
1653            chunks,
1654            diagnostic_endpoints,
1655            error_depth: 0,
1656            warning_depth: 0,
1657            information_depth: 0,
1658            hint_depth: 0,
1659            highlights,
1660        }
1661    }
1662}
1663
1664impl Clone for Snapshot {
1665    fn clone(&self) -> Self {
1666        Self {
1667            text: self.text.clone(),
1668            tree: self.tree.clone(),
1669            diagnostics: self.diagnostics.clone(),
1670            is_parsing: self.is_parsing,
1671            language: self.language.clone(),
1672            query_cursor: QueryCursorHandle::new(),
1673        }
1674    }
1675}
1676
1677impl Deref for Snapshot {
1678    type Target = buffer::Snapshot;
1679
1680    fn deref(&self) -> &Self::Target {
1681        &self.text
1682    }
1683}
1684
1685impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1686    type I = ByteChunks<'a>;
1687
1688    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1689        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1690    }
1691}
1692
1693struct ByteChunks<'a>(rope::Chunks<'a>);
1694
1695impl<'a> Iterator for ByteChunks<'a> {
1696    type Item = &'a [u8];
1697
1698    fn next(&mut self) -> Option<Self::Item> {
1699        self.0.next().map(str::as_bytes)
1700    }
1701}
1702
1703impl<'a> HighlightedChunks<'a> {
1704    pub fn seek(&mut self, offset: usize) {
1705        self.range.start = offset;
1706        self.chunks.seek(self.range.start);
1707        if let Some(highlights) = self.highlights.as_mut() {
1708            highlights
1709                .stack
1710                .retain(|(end_offset, _)| *end_offset > offset);
1711            if let Some((mat, capture_ix)) = &highlights.next_capture {
1712                let capture = mat.captures[*capture_ix as usize];
1713                if offset >= capture.node.start_byte() {
1714                    let next_capture_end = capture.node.end_byte();
1715                    if offset < next_capture_end {
1716                        highlights.stack.push((
1717                            next_capture_end,
1718                            highlights.highlight_map.get(capture.index),
1719                        ));
1720                    }
1721                    highlights.next_capture.take();
1722                }
1723            }
1724            highlights.captures.set_byte_range(self.range.clone());
1725        }
1726    }
1727
1728    pub fn offset(&self) -> usize {
1729        self.range.start
1730    }
1731
1732    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1733        let depth = match endpoint.severity {
1734            DiagnosticSeverity::ERROR => &mut self.error_depth,
1735            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1736            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1737            DiagnosticSeverity::HINT => &mut self.hint_depth,
1738            _ => return,
1739        };
1740        if endpoint.is_start {
1741            *depth += 1;
1742        } else {
1743            *depth -= 1;
1744        }
1745    }
1746
1747    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1748        if self.error_depth > 0 {
1749            Some(DiagnosticSeverity::ERROR)
1750        } else if self.warning_depth > 0 {
1751            Some(DiagnosticSeverity::WARNING)
1752        } else if self.information_depth > 0 {
1753            Some(DiagnosticSeverity::INFORMATION)
1754        } else if self.hint_depth > 0 {
1755            Some(DiagnosticSeverity::HINT)
1756        } else {
1757            None
1758        }
1759    }
1760}
1761
1762impl<'a> Iterator for HighlightedChunks<'a> {
1763    type Item = HighlightedChunk<'a>;
1764
1765    fn next(&mut self) -> Option<Self::Item> {
1766        let mut next_capture_start = usize::MAX;
1767        let mut next_diagnostic_endpoint = usize::MAX;
1768
1769        if let Some(highlights) = self.highlights.as_mut() {
1770            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1771                if *parent_capture_end <= self.range.start {
1772                    highlights.stack.pop();
1773                } else {
1774                    break;
1775                }
1776            }
1777
1778            if highlights.next_capture.is_none() {
1779                highlights.next_capture = highlights.captures.next();
1780            }
1781
1782            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1783                let capture = mat.captures[*capture_ix as usize];
1784                if self.range.start < capture.node.start_byte() {
1785                    next_capture_start = capture.node.start_byte();
1786                    break;
1787                } else {
1788                    let highlight_id = highlights.highlight_map.get(capture.index);
1789                    highlights
1790                        .stack
1791                        .push((capture.node.end_byte(), highlight_id));
1792                    highlights.next_capture = highlights.captures.next();
1793                }
1794            }
1795        }
1796
1797        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1798            if endpoint.offset <= self.range.start {
1799                self.update_diagnostic_depths(endpoint);
1800                self.diagnostic_endpoints.next();
1801            } else {
1802                next_diagnostic_endpoint = endpoint.offset;
1803                break;
1804            }
1805        }
1806
1807        if let Some(chunk) = self.chunks.peek() {
1808            let chunk_start = self.range.start;
1809            let mut chunk_end = (self.chunks.offset() + chunk.len())
1810                .min(next_capture_start)
1811                .min(next_diagnostic_endpoint);
1812            let mut highlight_id = HighlightId::default();
1813            if let Some((parent_capture_end, parent_highlight_id)) =
1814                self.highlights.as_ref().and_then(|h| h.stack.last())
1815            {
1816                chunk_end = chunk_end.min(*parent_capture_end);
1817                highlight_id = *parent_highlight_id;
1818            }
1819
1820            let slice =
1821                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1822            self.range.start = chunk_end;
1823            if self.range.start == self.chunks.offset() + chunk.len() {
1824                self.chunks.next().unwrap();
1825            }
1826
1827            Some(HighlightedChunk {
1828                text: slice,
1829                highlight_id,
1830                diagnostic: self.current_diagnostic_severity(),
1831            })
1832        } else {
1833            None
1834        }
1835    }
1836}
1837
1838impl QueryCursorHandle {
1839    fn new() -> Self {
1840        QueryCursorHandle(Some(
1841            QUERY_CURSORS
1842                .lock()
1843                .pop()
1844                .unwrap_or_else(|| QueryCursor::new()),
1845        ))
1846    }
1847}
1848
1849impl Deref for QueryCursorHandle {
1850    type Target = QueryCursor;
1851
1852    fn deref(&self) -> &Self::Target {
1853        self.0.as_ref().unwrap()
1854    }
1855}
1856
1857impl DerefMut for QueryCursorHandle {
1858    fn deref_mut(&mut self) -> &mut Self::Target {
1859        self.0.as_mut().unwrap()
1860    }
1861}
1862
1863impl Drop for QueryCursorHandle {
1864    fn drop(&mut self) {
1865        let mut cursor = self.0.take().unwrap();
1866        cursor.set_byte_range(0..usize::MAX);
1867        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
1868        QUERY_CURSORS.lock().push(cursor)
1869    }
1870}
1871
1872trait ToTreeSitterPoint {
1873    fn to_ts_point(self) -> tree_sitter::Point;
1874    fn from_ts_point(point: tree_sitter::Point) -> Self;
1875}
1876
1877impl ToTreeSitterPoint for Point {
1878    fn to_ts_point(self) -> tree_sitter::Point {
1879        tree_sitter::Point::new(self.row as usize, self.column as usize)
1880    }
1881
1882    fn from_ts_point(point: tree_sitter::Point) -> Self {
1883        Point::new(point.row as u32, point.column as u32)
1884    }
1885}
1886
1887fn contiguous_ranges(
1888    values: impl IntoIterator<Item = u32>,
1889    max_len: usize,
1890) -> impl Iterator<Item = Range<u32>> {
1891    let mut values = values.into_iter();
1892    let mut current_range: Option<Range<u32>> = None;
1893    std::iter::from_fn(move || loop {
1894        if let Some(value) = values.next() {
1895            if let Some(range) = &mut current_range {
1896                if value == range.end && range.len() < max_len {
1897                    range.end += 1;
1898                    continue;
1899                }
1900            }
1901
1902            let prev_range = current_range.clone();
1903            current_range = Some(value..(value + 1));
1904            if prev_range.is_some() {
1905                return prev_range;
1906            }
1907        } else {
1908            return current_range.take();
1909        }
1910    })
1911}