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: 'a + ToOffset>(
 784        &'a self,
 785        range: Range<T>,
 786    ) -> impl Iterator<Item = (Range<Point>, &Diagnostic)> + 'a {
 787        let content = self.content();
 788        self.diagnostics
 789            .intersecting_ranges(range, content, true)
 790            .map(move |(_, range, diagnostic)| (range, diagnostic))
 791    }
 792
 793    pub fn diagnostics_update_count(&self) -> usize {
 794        self.diagnostics_update_count
 795    }
 796
 797    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 798        if let Some(indent_columns) = self.compute_autoindents() {
 799            let indent_columns = cx.background().spawn(indent_columns);
 800            match cx
 801                .background()
 802                .block_with_timeout(Duration::from_micros(500), indent_columns)
 803            {
 804                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 805                Err(indent_columns) => {
 806                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 807                        let indent_columns = indent_columns.await;
 808                        this.update(&mut cx, |this, cx| {
 809                            this.apply_autoindents(indent_columns, cx);
 810                        });
 811                    }));
 812                }
 813            }
 814        }
 815    }
 816
 817    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 818        let max_rows_between_yields = 100;
 819        let snapshot = self.snapshot();
 820        if snapshot.language.is_none()
 821            || snapshot.tree.is_none()
 822            || self.autoindent_requests.is_empty()
 823        {
 824            return None;
 825        }
 826
 827        let autoindent_requests = self.autoindent_requests.clone();
 828        Some(async move {
 829            let mut indent_columns = BTreeMap::new();
 830            for request in autoindent_requests {
 831                let old_to_new_rows = request
 832                    .edited
 833                    .points(&request.before_edit)
 834                    .map(|point| point.row)
 835                    .zip(request.edited.points(&snapshot).map(|point| point.row))
 836                    .collect::<BTreeMap<u32, u32>>();
 837
 838                let mut old_suggestions = HashMap::<u32, u32>::default();
 839                let old_edited_ranges =
 840                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 841                for old_edited_range in old_edited_ranges {
 842                    let suggestions = request
 843                        .before_edit
 844                        .suggest_autoindents(old_edited_range.clone())
 845                        .into_iter()
 846                        .flatten();
 847                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 848                        let indentation_basis = old_to_new_rows
 849                            .get(&suggestion.basis_row)
 850                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 851                            .unwrap_or_else(|| {
 852                                request
 853                                    .before_edit
 854                                    .indent_column_for_line(suggestion.basis_row)
 855                            });
 856                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 857                        old_suggestions.insert(
 858                            *old_to_new_rows.get(&old_row).unwrap(),
 859                            indentation_basis + delta,
 860                        );
 861                    }
 862                    yield_now().await;
 863                }
 864
 865                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 866                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 867                let new_edited_row_ranges =
 868                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 869                for new_edited_row_range in new_edited_row_ranges {
 870                    let suggestions = snapshot
 871                        .suggest_autoindents(new_edited_row_range.clone())
 872                        .into_iter()
 873                        .flatten();
 874                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 875                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 876                        let new_indentation = indent_columns
 877                            .get(&suggestion.basis_row)
 878                            .copied()
 879                            .unwrap_or_else(|| {
 880                                snapshot.indent_column_for_line(suggestion.basis_row)
 881                            })
 882                            + delta;
 883                        if old_suggestions
 884                            .get(&new_row)
 885                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 886                        {
 887                            indent_columns.insert(new_row, new_indentation);
 888                        }
 889                    }
 890                    yield_now().await;
 891                }
 892
 893                if let Some(inserted) = request.inserted.as_ref() {
 894                    let inserted_row_ranges = contiguous_ranges(
 895                        inserted
 896                            .point_ranges(&snapshot)
 897                            .flat_map(|range| range.start.row..range.end.row + 1),
 898                        max_rows_between_yields,
 899                    );
 900                    for inserted_row_range in inserted_row_ranges {
 901                        let suggestions = snapshot
 902                            .suggest_autoindents(inserted_row_range.clone())
 903                            .into_iter()
 904                            .flatten();
 905                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
 906                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 907                            let new_indentation = indent_columns
 908                                .get(&suggestion.basis_row)
 909                                .copied()
 910                                .unwrap_or_else(|| {
 911                                    snapshot.indent_column_for_line(suggestion.basis_row)
 912                                })
 913                                + delta;
 914                            indent_columns.insert(row, new_indentation);
 915                        }
 916                        yield_now().await;
 917                    }
 918                }
 919            }
 920            indent_columns
 921        })
 922    }
 923
 924    fn apply_autoindents(
 925        &mut self,
 926        indent_columns: BTreeMap<u32, u32>,
 927        cx: &mut ModelContext<Self>,
 928    ) {
 929        let selection_set_ids = self
 930            .autoindent_requests
 931            .drain(..)
 932            .flat_map(|req| req.selection_set_ids.clone())
 933            .collect::<HashSet<_>>();
 934
 935        self.start_transaction(selection_set_ids.iter().copied())
 936            .unwrap();
 937        for (row, indent_column) in &indent_columns {
 938            self.set_indent_column_for_line(*row, *indent_column, cx);
 939        }
 940
 941        for selection_set_id in &selection_set_ids {
 942            if let Ok(set) = self.selection_set(*selection_set_id) {
 943                let new_selections = set
 944                    .point_selections(&*self)
 945                    .map(|selection| {
 946                        if selection.start.column == 0 {
 947                            let delta = Point::new(
 948                                0,
 949                                indent_columns
 950                                    .get(&selection.start.row)
 951                                    .copied()
 952                                    .unwrap_or(0),
 953                            );
 954                            if delta.column > 0 {
 955                                return Selection {
 956                                    id: selection.id,
 957                                    goal: selection.goal,
 958                                    reversed: selection.reversed,
 959                                    start: selection.start + delta,
 960                                    end: selection.end + delta,
 961                                };
 962                            }
 963                        }
 964                        selection
 965                    })
 966                    .collect::<Vec<_>>();
 967                self.update_selection_set(*selection_set_id, &new_selections, cx)
 968                    .unwrap();
 969            }
 970        }
 971
 972        self.end_transaction(selection_set_ids.iter().copied(), cx)
 973            .unwrap();
 974    }
 975
 976    pub fn indent_column_for_line(&self, row: u32) -> u32 {
 977        self.content().indent_column_for_line(row)
 978    }
 979
 980    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
 981        let current_column = self.indent_column_for_line(row);
 982        if column > current_column {
 983            let offset = Point::new(row, 0).to_offset(&*self);
 984            self.edit(
 985                [offset..offset],
 986                " ".repeat((column - current_column) as usize),
 987                cx,
 988            );
 989        } else if column < current_column {
 990            self.edit(
 991                [Point::new(row, 0)..Point::new(row, current_column - column)],
 992                "",
 993                cx,
 994            );
 995        }
 996    }
 997
 998    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
 999        if let Some(tree) = self.syntax_tree() {
1000            let root = tree.root_node();
1001            let range = range.start.to_offset(self)..range.end.to_offset(self);
1002            let mut node = root.descendant_for_byte_range(range.start, range.end);
1003            while node.map_or(false, |n| n.byte_range() == range) {
1004                node = node.unwrap().parent();
1005            }
1006            node.map(|n| n.byte_range())
1007        } else {
1008            None
1009        }
1010    }
1011
1012    pub fn enclosing_bracket_ranges<T: ToOffset>(
1013        &self,
1014        range: Range<T>,
1015    ) -> Option<(Range<usize>, Range<usize>)> {
1016        let (lang, tree) = self.language.as_ref().zip(self.syntax_tree())?;
1017        let open_capture_ix = lang.brackets_query.capture_index_for_name("open")?;
1018        let close_capture_ix = lang.brackets_query.capture_index_for_name("close")?;
1019
1020        // Find bracket pairs that *inclusively* contain the given range.
1021        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1022        let mut cursor = QueryCursorHandle::new();
1023        let matches = cursor.set_byte_range(range).matches(
1024            &lang.brackets_query,
1025            tree.root_node(),
1026            TextProvider(self.as_rope()),
1027        );
1028
1029        // Get the ranges of the innermost pair of brackets.
1030        matches
1031            .filter_map(|mat| {
1032                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1033                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1034                Some((open.byte_range(), close.byte_range()))
1035            })
1036            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1037    }
1038
1039    fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1040        // TODO: it would be nice to not allocate here.
1041        let old_text = self.text();
1042        let base_version = self.version();
1043        cx.background().spawn(async move {
1044            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1045                .iter_all_changes()
1046                .map(|c| (c.tag(), c.value().len()))
1047                .collect::<Vec<_>>();
1048            Diff {
1049                base_version,
1050                new_text,
1051                changes,
1052            }
1053        })
1054    }
1055
1056    fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1057        if self.version == diff.base_version {
1058            self.start_transaction(None).unwrap();
1059            let mut offset = 0;
1060            for (tag, len) in diff.changes {
1061                let range = offset..(offset + len);
1062                match tag {
1063                    ChangeTag::Equal => offset += len,
1064                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1065                    ChangeTag::Insert => {
1066                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1067                        offset += len;
1068                    }
1069                }
1070            }
1071            self.end_transaction(None, cx).unwrap();
1072            true
1073        } else {
1074            false
1075        }
1076    }
1077
1078    pub fn is_dirty(&self) -> bool {
1079        self.version > self.saved_version
1080            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1081    }
1082
1083    pub fn has_conflict(&self) -> bool {
1084        self.version > self.saved_version
1085            && self
1086                .file
1087                .as_ref()
1088                .map_or(false, |file| file.mtime() > self.saved_mtime)
1089    }
1090
1091    pub fn start_transaction(
1092        &mut self,
1093        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1094    ) -> Result<()> {
1095        self.start_transaction_at(selection_set_ids, Instant::now())
1096    }
1097
1098    fn start_transaction_at(
1099        &mut self,
1100        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1101        now: Instant,
1102    ) -> Result<()> {
1103        self.text.start_transaction_at(selection_set_ids, now)
1104    }
1105
1106    pub fn end_transaction(
1107        &mut self,
1108        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1109        cx: &mut ModelContext<Self>,
1110    ) -> Result<()> {
1111        self.end_transaction_at(selection_set_ids, Instant::now(), cx)
1112    }
1113
1114    fn end_transaction_at(
1115        &mut self,
1116        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1117        now: Instant,
1118        cx: &mut ModelContext<Self>,
1119    ) -> Result<()> {
1120        if let Some(start_version) = self.text.end_transaction_at(selection_set_ids, now) {
1121            let was_dirty = start_version != self.saved_version;
1122            self.did_edit(&start_version, was_dirty, cx);
1123        }
1124        Ok(())
1125    }
1126
1127    fn update_language_server(&mut self) {
1128        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1129            language_server
1130        } else {
1131            return;
1132        };
1133        let abs_path = self
1134            .file
1135            .as_ref()
1136            .map_or(Path::new("/").to_path_buf(), |file| {
1137                file.abs_path().unwrap()
1138            });
1139
1140        let version = post_inc(&mut language_server.next_version);
1141        let snapshot = LanguageServerSnapshot {
1142            buffer_snapshot: self.text.snapshot(),
1143            version,
1144            path: Arc::from(abs_path),
1145        };
1146        language_server
1147            .pending_snapshots
1148            .insert(version, snapshot.clone());
1149        let _ = language_server
1150            .latest_snapshot
1151            .blocking_send(Some(snapshot));
1152    }
1153
1154    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1155    where
1156        I: IntoIterator<Item = Range<S>>,
1157        S: ToOffset,
1158        T: Into<String>,
1159    {
1160        self.edit_internal(ranges_iter, new_text, false, cx)
1161    }
1162
1163    pub fn edit_with_autoindent<I, S, T>(
1164        &mut self,
1165        ranges_iter: I,
1166        new_text: T,
1167        cx: &mut ModelContext<Self>,
1168    ) where
1169        I: IntoIterator<Item = Range<S>>,
1170        S: ToOffset,
1171        T: Into<String>,
1172    {
1173        self.edit_internal(ranges_iter, new_text, true, cx)
1174    }
1175
1176    pub fn edit_internal<I, S, T>(
1177        &mut self,
1178        ranges_iter: I,
1179        new_text: T,
1180        autoindent: bool,
1181        cx: &mut ModelContext<Self>,
1182    ) where
1183        I: IntoIterator<Item = Range<S>>,
1184        S: ToOffset,
1185        T: Into<String>,
1186    {
1187        let new_text = new_text.into();
1188
1189        // Skip invalid ranges and coalesce contiguous ones.
1190        let mut ranges: Vec<Range<usize>> = Vec::new();
1191        for range in ranges_iter {
1192            let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1193            if !new_text.is_empty() || !range.is_empty() {
1194                if let Some(prev_range) = ranges.last_mut() {
1195                    if prev_range.end >= range.start {
1196                        prev_range.end = cmp::max(prev_range.end, range.end);
1197                    } else {
1198                        ranges.push(range);
1199                    }
1200                } else {
1201                    ranges.push(range);
1202                }
1203            }
1204        }
1205        if ranges.is_empty() {
1206            return;
1207        }
1208
1209        self.start_transaction(None).unwrap();
1210        self.pending_autoindent.take();
1211        let autoindent_request = if autoindent && self.language.is_some() {
1212            let before_edit = self.snapshot();
1213            let edited = self.content().anchor_set(ranges.iter().filter_map(|range| {
1214                let start = range.start.to_point(&*self);
1215                if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1216                    None
1217                } else {
1218                    Some((range.start, Bias::Left))
1219                }
1220            }));
1221            Some((before_edit, edited))
1222        } else {
1223            None
1224        };
1225
1226        let first_newline_ix = new_text.find('\n');
1227        let new_text_len = new_text.len();
1228
1229        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1230
1231        if let Some((before_edit, edited)) = autoindent_request {
1232            let mut inserted = None;
1233            if let Some(first_newline_ix) = first_newline_ix {
1234                let mut delta = 0isize;
1235                inserted = Some(self.content().anchor_range_set(ranges.iter().map(|range| {
1236                    let start = (delta + range.start as isize) as usize + first_newline_ix + 1;
1237                    let end = (delta + range.start as isize) as usize + new_text_len;
1238                    delta += (range.end as isize - range.start as isize) + new_text_len as isize;
1239                    (start, Bias::Left)..(end, Bias::Right)
1240                })));
1241            }
1242
1243            let selection_set_ids = self
1244                .text
1245                .peek_undo_stack()
1246                .unwrap()
1247                .starting_selection_set_ids()
1248                .collect();
1249            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1250                selection_set_ids,
1251                before_edit,
1252                edited,
1253                inserted,
1254            }));
1255        }
1256
1257        self.end_transaction(None, cx).unwrap();
1258        self.send_operation(Operation::Buffer(buffer::Operation::Edit(edit)), cx);
1259    }
1260
1261    fn did_edit(
1262        &mut self,
1263        old_version: &clock::Global,
1264        was_dirty: bool,
1265        cx: &mut ModelContext<Self>,
1266    ) {
1267        if self.edits_since::<usize>(old_version).next().is_none() {
1268            return;
1269        }
1270
1271        self.reparse(cx);
1272        self.update_language_server();
1273
1274        cx.emit(Event::Edited);
1275        if !was_dirty {
1276            cx.emit(Event::Dirtied);
1277        }
1278        cx.notify();
1279    }
1280
1281    pub fn add_selection_set<T: ToOffset>(
1282        &mut self,
1283        selections: &[Selection<T>],
1284        cx: &mut ModelContext<Self>,
1285    ) -> SelectionSetId {
1286        let operation = self.text.add_selection_set(selections);
1287        if let buffer::Operation::UpdateSelections { set_id, .. } = &operation {
1288            let set_id = *set_id;
1289            cx.notify();
1290            self.send_operation(Operation::Buffer(operation), cx);
1291            set_id
1292        } else {
1293            unreachable!()
1294        }
1295    }
1296
1297    pub fn update_selection_set<T: ToOffset>(
1298        &mut self,
1299        set_id: SelectionSetId,
1300        selections: &[Selection<T>],
1301        cx: &mut ModelContext<Self>,
1302    ) -> Result<()> {
1303        let operation = self.text.update_selection_set(set_id, selections)?;
1304        cx.notify();
1305        self.send_operation(Operation::Buffer(operation), cx);
1306        Ok(())
1307    }
1308
1309    pub fn set_active_selection_set(
1310        &mut self,
1311        set_id: Option<SelectionSetId>,
1312        cx: &mut ModelContext<Self>,
1313    ) -> Result<()> {
1314        let operation = self.text.set_active_selection_set(set_id)?;
1315        self.send_operation(Operation::Buffer(operation), cx);
1316        Ok(())
1317    }
1318
1319    pub fn remove_selection_set(
1320        &mut self,
1321        set_id: SelectionSetId,
1322        cx: &mut ModelContext<Self>,
1323    ) -> Result<()> {
1324        let operation = self.text.remove_selection_set(set_id)?;
1325        cx.notify();
1326        self.send_operation(Operation::Buffer(operation), cx);
1327        Ok(())
1328    }
1329
1330    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1331        &mut self,
1332        ops: I,
1333        cx: &mut ModelContext<Self>,
1334    ) -> Result<()> {
1335        self.pending_autoindent.take();
1336        let was_dirty = self.is_dirty();
1337        let old_version = self.version.clone();
1338        let buffer_ops = ops
1339            .into_iter()
1340            .filter_map(|op| match op {
1341                Operation::Buffer(op) => Some(op),
1342                Operation::UpdateDiagnostics(diagnostics) => {
1343                    self.apply_diagnostic_update(diagnostics, cx);
1344                    None
1345                }
1346            })
1347            .collect::<Vec<_>>();
1348        self.text.apply_ops(buffer_ops)?;
1349        self.did_edit(&old_version, was_dirty, cx);
1350        // Notify independently of whether the buffer was edited as the operations could include a
1351        // selection update.
1352        cx.notify();
1353        Ok(())
1354    }
1355
1356    fn apply_diagnostic_update(
1357        &mut self,
1358        diagnostics: AnchorRangeMultimap<Diagnostic>,
1359        cx: &mut ModelContext<Self>,
1360    ) {
1361        self.diagnostics = diagnostics;
1362        self.diagnostics_update_count += 1;
1363        cx.notify();
1364    }
1365
1366    #[cfg(not(test))]
1367    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1368        if let Some(file) = &self.file {
1369            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1370        }
1371    }
1372
1373    #[cfg(test)]
1374    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1375        self.operations.push(operation);
1376    }
1377
1378    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1379        self.text.remove_peer(replica_id);
1380        cx.notify();
1381    }
1382
1383    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
1384        let was_dirty = self.is_dirty();
1385        let old_version = self.version.clone();
1386
1387        for operation in self.text.undo() {
1388            self.send_operation(Operation::Buffer(operation), cx);
1389        }
1390
1391        self.did_edit(&old_version, was_dirty, cx);
1392    }
1393
1394    pub fn redo(&mut self, cx: &mut ModelContext<Self>) {
1395        let was_dirty = self.is_dirty();
1396        let old_version = self.version.clone();
1397
1398        for operation in self.text.redo() {
1399            self.send_operation(Operation::Buffer(operation), cx);
1400        }
1401
1402        self.did_edit(&old_version, was_dirty, cx);
1403    }
1404}
1405
1406#[cfg(any(test, feature = "test-support"))]
1407impl Buffer {
1408    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize)
1409    where
1410        T: rand::Rng,
1411    {
1412        self.text.randomly_edit(rng, old_range_count);
1413    }
1414
1415    pub fn randomly_mutate<T>(&mut self, rng: &mut T)
1416    where
1417        T: rand::Rng,
1418    {
1419        self.text.randomly_mutate(rng);
1420    }
1421}
1422
1423impl Entity for Buffer {
1424    type Event = Event;
1425
1426    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1427        if let Some(file) = self.file.as_ref() {
1428            file.buffer_removed(self.remote_id(), cx);
1429        }
1430    }
1431}
1432
1433// TODO: Do we need to clone a buffer?
1434impl Clone for Buffer {
1435    fn clone(&self) -> Self {
1436        Self {
1437            text: self.text.clone(),
1438            saved_version: self.saved_version.clone(),
1439            saved_mtime: self.saved_mtime,
1440            file: self.file.as_ref().map(|f| f.boxed_clone()),
1441            language: self.language.clone(),
1442            syntax_tree: Mutex::new(self.syntax_tree.lock().clone()),
1443            parsing_in_background: false,
1444            sync_parse_timeout: self.sync_parse_timeout,
1445            parse_count: self.parse_count,
1446            autoindent_requests: Default::default(),
1447            pending_autoindent: Default::default(),
1448            diagnostics: self.diagnostics.clone(),
1449            diagnostics_update_count: self.diagnostics_update_count,
1450            language_server: None,
1451            #[cfg(test)]
1452            operations: self.operations.clone(),
1453        }
1454    }
1455}
1456
1457impl Deref for Buffer {
1458    type Target = TextBuffer;
1459
1460    fn deref(&self) -> &Self::Target {
1461        &self.text
1462    }
1463}
1464
1465impl<'a> From<&'a Buffer> for Content<'a> {
1466    fn from(buffer: &'a Buffer) -> Self {
1467        Self::from(&buffer.text)
1468    }
1469}
1470
1471impl<'a> From<&'a mut Buffer> for Content<'a> {
1472    fn from(buffer: &'a mut Buffer) -> Self {
1473        Self::from(&buffer.text)
1474    }
1475}
1476
1477impl<'a> From<&'a Snapshot> for Content<'a> {
1478    fn from(snapshot: &'a Snapshot) -> Self {
1479        Self::from(&snapshot.text)
1480    }
1481}
1482
1483impl Snapshot {
1484    fn suggest_autoindents<'a>(
1485        &'a self,
1486        row_range: Range<u32>,
1487    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1488        let mut query_cursor = QueryCursorHandle::new();
1489        if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1490            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1491
1492            // Get the "indentation ranges" that intersect this row range.
1493            let indent_capture_ix = language.indents_query.capture_index_for_name("indent");
1494            let end_capture_ix = language.indents_query.capture_index_for_name("end");
1495            query_cursor.set_point_range(
1496                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1497                    ..Point::new(row_range.end, 0).to_ts_point(),
1498            );
1499            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1500            for mat in query_cursor.matches(
1501                &language.indents_query,
1502                tree.root_node(),
1503                TextProvider(self.as_rope()),
1504            ) {
1505                let mut node_kind = "";
1506                let mut start: Option<Point> = None;
1507                let mut end: Option<Point> = None;
1508                for capture in mat.captures {
1509                    if Some(capture.index) == indent_capture_ix {
1510                        node_kind = capture.node.kind();
1511                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1512                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1513                    } else if Some(capture.index) == end_capture_ix {
1514                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1515                    }
1516                }
1517
1518                if let Some((start, end)) = start.zip(end) {
1519                    if start.row == end.row {
1520                        continue;
1521                    }
1522
1523                    let range = start..end;
1524                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1525                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1526                        Ok(ix) => {
1527                            let prev_range = &mut indentation_ranges[ix];
1528                            prev_range.0.end = prev_range.0.end.max(range.end);
1529                        }
1530                    }
1531                }
1532            }
1533
1534            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1535            Some(row_range.map(move |row| {
1536                let row_start = Point::new(row, self.indent_column_for_line(row));
1537
1538                let mut indent_from_prev_row = false;
1539                let mut outdent_to_row = u32::MAX;
1540                for (range, _node_kind) in &indentation_ranges {
1541                    if range.start.row >= row {
1542                        break;
1543                    }
1544
1545                    if range.start.row == prev_row && range.end > row_start {
1546                        indent_from_prev_row = true;
1547                    }
1548                    if range.end.row >= prev_row && range.end <= row_start {
1549                        outdent_to_row = outdent_to_row.min(range.start.row);
1550                    }
1551                }
1552
1553                let suggestion = if outdent_to_row == prev_row {
1554                    IndentSuggestion {
1555                        basis_row: prev_row,
1556                        indent: false,
1557                    }
1558                } else if indent_from_prev_row {
1559                    IndentSuggestion {
1560                        basis_row: prev_row,
1561                        indent: true,
1562                    }
1563                } else if outdent_to_row < prev_row {
1564                    IndentSuggestion {
1565                        basis_row: outdent_to_row,
1566                        indent: false,
1567                    }
1568                } else {
1569                    IndentSuggestion {
1570                        basis_row: prev_row,
1571                        indent: false,
1572                    }
1573                };
1574
1575                prev_row = row;
1576                suggestion
1577            }))
1578        } else {
1579            None
1580        }
1581    }
1582
1583    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1584        while row > 0 {
1585            row -= 1;
1586            if !self.is_line_blank(row) {
1587                return Some(row);
1588            }
1589        }
1590        None
1591    }
1592
1593    fn is_line_blank(&self, row: u32) -> bool {
1594        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1595            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1596    }
1597
1598    pub fn highlighted_text_for_range<T: ToOffset>(
1599        &mut self,
1600        range: Range<T>,
1601    ) -> HighlightedChunks {
1602        let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1603
1604        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1605        for (_, range, diagnostic) in
1606            self.diagnostics
1607                .intersecting_ranges(range.clone(), self.content(), true)
1608        {
1609            diagnostic_endpoints.push(DiagnosticEndpoint {
1610                offset: range.start,
1611                is_start: true,
1612                severity: diagnostic.severity,
1613            });
1614            diagnostic_endpoints.push(DiagnosticEndpoint {
1615                offset: range.end,
1616                is_start: false,
1617                severity: diagnostic.severity,
1618            });
1619        }
1620        diagnostic_endpoints.sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1621        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1622
1623        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1624        let highlights =
1625            if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1626                let captures = self.query_cursor.set_byte_range(range.clone()).captures(
1627                    &language.highlights_query,
1628                    tree.root_node(),
1629                    TextProvider(self.text.as_rope()),
1630                );
1631
1632                Some(Highlights {
1633                    captures,
1634                    next_capture: None,
1635                    stack: Default::default(),
1636                    highlight_map: language.highlight_map(),
1637                })
1638            } else {
1639                None
1640            };
1641
1642        HighlightedChunks {
1643            range,
1644            chunks,
1645            diagnostic_endpoints,
1646            error_depth: 0,
1647            warning_depth: 0,
1648            information_depth: 0,
1649            hint_depth: 0,
1650            highlights,
1651        }
1652    }
1653}
1654
1655impl Clone for Snapshot {
1656    fn clone(&self) -> Self {
1657        Self {
1658            text: self.text.clone(),
1659            tree: self.tree.clone(),
1660            diagnostics: self.diagnostics.clone(),
1661            is_parsing: self.is_parsing,
1662            language: self.language.clone(),
1663            query_cursor: QueryCursorHandle::new(),
1664        }
1665    }
1666}
1667
1668impl Deref for Snapshot {
1669    type Target = buffer::Snapshot;
1670
1671    fn deref(&self) -> &Self::Target {
1672        &self.text
1673    }
1674}
1675
1676impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1677    type I = ByteChunks<'a>;
1678
1679    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1680        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1681    }
1682}
1683
1684struct ByteChunks<'a>(rope::Chunks<'a>);
1685
1686impl<'a> Iterator for ByteChunks<'a> {
1687    type Item = &'a [u8];
1688
1689    fn next(&mut self) -> Option<Self::Item> {
1690        self.0.next().map(str::as_bytes)
1691    }
1692}
1693
1694impl<'a> HighlightedChunks<'a> {
1695    pub fn seek(&mut self, offset: usize) {
1696        self.range.start = offset;
1697        self.chunks.seek(self.range.start);
1698        if let Some(highlights) = self.highlights.as_mut() {
1699            highlights
1700                .stack
1701                .retain(|(end_offset, _)| *end_offset > offset);
1702            if let Some((mat, capture_ix)) = &highlights.next_capture {
1703                let capture = mat.captures[*capture_ix as usize];
1704                if offset >= capture.node.start_byte() {
1705                    let next_capture_end = capture.node.end_byte();
1706                    if offset < next_capture_end {
1707                        highlights.stack.push((
1708                            next_capture_end,
1709                            highlights.highlight_map.get(capture.index),
1710                        ));
1711                    }
1712                    highlights.next_capture.take();
1713                }
1714            }
1715            highlights.captures.set_byte_range(self.range.clone());
1716        }
1717    }
1718
1719    pub fn offset(&self) -> usize {
1720        self.range.start
1721    }
1722
1723    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1724        let depth = match endpoint.severity {
1725            DiagnosticSeverity::ERROR => &mut self.error_depth,
1726            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1727            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1728            DiagnosticSeverity::HINT => &mut self.hint_depth,
1729            _ => return,
1730        };
1731        if endpoint.is_start {
1732            *depth += 1;
1733        } else {
1734            *depth -= 1;
1735        }
1736    }
1737
1738    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1739        if self.error_depth > 0 {
1740            Some(DiagnosticSeverity::ERROR)
1741        } else if self.warning_depth > 0 {
1742            Some(DiagnosticSeverity::WARNING)
1743        } else if self.information_depth > 0 {
1744            Some(DiagnosticSeverity::INFORMATION)
1745        } else if self.hint_depth > 0 {
1746            Some(DiagnosticSeverity::HINT)
1747        } else {
1748            None
1749        }
1750    }
1751}
1752
1753impl<'a> Iterator for HighlightedChunks<'a> {
1754    type Item = HighlightedChunk<'a>;
1755
1756    fn next(&mut self) -> Option<Self::Item> {
1757        let mut next_capture_start = usize::MAX;
1758        let mut next_diagnostic_endpoint = usize::MAX;
1759
1760        if let Some(highlights) = self.highlights.as_mut() {
1761            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1762                if *parent_capture_end <= self.range.start {
1763                    highlights.stack.pop();
1764                } else {
1765                    break;
1766                }
1767            }
1768
1769            if highlights.next_capture.is_none() {
1770                highlights.next_capture = highlights.captures.next();
1771            }
1772
1773            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1774                let capture = mat.captures[*capture_ix as usize];
1775                if self.range.start < capture.node.start_byte() {
1776                    next_capture_start = capture.node.start_byte();
1777                    break;
1778                } else {
1779                    let highlight_id = highlights.highlight_map.get(capture.index);
1780                    highlights
1781                        .stack
1782                        .push((capture.node.end_byte(), highlight_id));
1783                    highlights.next_capture = highlights.captures.next();
1784                }
1785            }
1786        }
1787
1788        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1789            if endpoint.offset <= self.range.start {
1790                self.update_diagnostic_depths(endpoint);
1791                self.diagnostic_endpoints.next();
1792            } else {
1793                next_diagnostic_endpoint = endpoint.offset;
1794                break;
1795            }
1796        }
1797
1798        if let Some(chunk) = self.chunks.peek() {
1799            let chunk_start = self.range.start;
1800            let mut chunk_end = (self.chunks.offset() + chunk.len())
1801                .min(next_capture_start)
1802                .min(next_diagnostic_endpoint);
1803            let mut highlight_id = HighlightId::default();
1804            if let Some((parent_capture_end, parent_highlight_id)) =
1805                self.highlights.as_ref().and_then(|h| h.stack.last())
1806            {
1807                chunk_end = chunk_end.min(*parent_capture_end);
1808                highlight_id = *parent_highlight_id;
1809            }
1810
1811            let slice =
1812                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1813            self.range.start = chunk_end;
1814            if self.range.start == self.chunks.offset() + chunk.len() {
1815                self.chunks.next().unwrap();
1816            }
1817
1818            Some(HighlightedChunk {
1819                text: slice,
1820                highlight_id,
1821                diagnostic: self.current_diagnostic_severity(),
1822            })
1823        } else {
1824            None
1825        }
1826    }
1827}
1828
1829impl QueryCursorHandle {
1830    fn new() -> Self {
1831        QueryCursorHandle(Some(
1832            QUERY_CURSORS
1833                .lock()
1834                .pop()
1835                .unwrap_or_else(|| QueryCursor::new()),
1836        ))
1837    }
1838}
1839
1840impl Deref for QueryCursorHandle {
1841    type Target = QueryCursor;
1842
1843    fn deref(&self) -> &Self::Target {
1844        self.0.as_ref().unwrap()
1845    }
1846}
1847
1848impl DerefMut for QueryCursorHandle {
1849    fn deref_mut(&mut self) -> &mut Self::Target {
1850        self.0.as_mut().unwrap()
1851    }
1852}
1853
1854impl Drop for QueryCursorHandle {
1855    fn drop(&mut self) {
1856        let mut cursor = self.0.take().unwrap();
1857        cursor.set_byte_range(0..usize::MAX);
1858        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
1859        QUERY_CURSORS.lock().push(cursor)
1860    }
1861}
1862
1863trait ToTreeSitterPoint {
1864    fn to_ts_point(self) -> tree_sitter::Point;
1865    fn from_ts_point(point: tree_sitter::Point) -> Self;
1866}
1867
1868impl ToTreeSitterPoint for Point {
1869    fn to_ts_point(self) -> tree_sitter::Point {
1870        tree_sitter::Point::new(self.row as usize, self.column as usize)
1871    }
1872
1873    fn from_ts_point(point: tree_sitter::Point) -> Self {
1874        Point::new(point.row as u32, point.column as u32)
1875    }
1876}
1877
1878fn contiguous_ranges(
1879    values: impl IntoIterator<Item = u32>,
1880    max_len: usize,
1881) -> impl Iterator<Item = Range<u32>> {
1882    let mut values = values.into_iter();
1883    let mut current_range: Option<Range<u32>> = None;
1884    std::iter::from_fn(move || loop {
1885        if let Some(value) = values.next() {
1886            if let Some(range) = &mut current_range {
1887                if value == range.end && range.len() < max_len {
1888                    range.end += 1;
1889                    continue;
1890                }
1891            }
1892
1893            let prev_range = current_range.clone();
1894            current_range = Some(value..(value + 1));
1895            if prev_range.is_some() {
1896                return prev_range;
1897            }
1898        } else {
1899            return current_range.take();
1900        }
1901    })
1902}