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