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