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