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