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