buffer.rs

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