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