lib.rs

   1mod highlight_map;
   2mod language;
   3pub mod proto;
   4#[cfg(test)]
   5mod tests;
   6
   7pub use self::{
   8    highlight_map::{HighlightId, HighlightMap},
   9    language::{BracketPair, Language, LanguageConfig, LanguageRegistry, LanguageServerConfig},
  10};
  11use anyhow::{anyhow, Result};
  12pub use buffer::{Buffer as TextBuffer, Operation as _, *};
  13use clock::ReplicaId;
  14use futures::FutureExt as _;
  15use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, MutableAppContext, Task};
  16use lazy_static::lazy_static;
  17use lsp::LanguageServer;
  18use parking_lot::Mutex;
  19use postage::{prelude::Stream, sink::Sink, watch};
  20use similar::{ChangeTag, TextDiff};
  21use smol::future::yield_now;
  22use std::{
  23    any::Any,
  24    cell::RefCell,
  25    cmp,
  26    collections::{BTreeMap, HashMap, HashSet},
  27    ffi::OsString,
  28    future::Future,
  29    iter::{Iterator, Peekable},
  30    ops::{Deref, DerefMut, Range},
  31    path::{Path, PathBuf},
  32    str,
  33    sync::Arc,
  34    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  35    vec,
  36};
  37use theme::SyntaxTheme;
  38use tree_sitter::{InputEdit, Parser, QueryCursor, Tree};
  39use util::{post_inc, TryFutureExt as _};
  40
  41#[cfg(any(test, feature = "test-support"))]
  42pub use tree_sitter_rust;
  43
  44pub use lsp::DiagnosticSeverity;
  45
  46thread_local! {
  47    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  48}
  49
  50lazy_static! {
  51    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  52}
  53
  54// TODO - Make this configurable
  55const INDENT_SIZE: u32 = 4;
  56
  57pub struct Buffer {
  58    text: TextBuffer,
  59    file: Option<Box<dyn File>>,
  60    saved_version: clock::Global,
  61    saved_mtime: SystemTime,
  62    language: Option<Arc<Language>>,
  63    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  64    pending_autoindent: Option<Task<()>>,
  65    sync_parse_timeout: Duration,
  66    syntax_tree: Mutex<Option<SyntaxTree>>,
  67    parsing_in_background: bool,
  68    parse_count: usize,
  69    diagnostics: AnchorRangeMultimap<Diagnostic>,
  70    diagnostics_update_count: usize,
  71    language_server: Option<LanguageServerState>,
  72    #[cfg(test)]
  73    operations: Vec<Operation>,
  74}
  75
  76pub struct Snapshot {
  77    text: buffer::Snapshot,
  78    tree: Option<Tree>,
  79    diagnostics: AnchorRangeMultimap<Diagnostic>,
  80    is_parsing: bool,
  81    language: Option<Arc<Language>>,
  82}
  83
  84#[derive(Clone, Debug, PartialEq, Eq)]
  85pub struct Diagnostic {
  86    pub severity: DiagnosticSeverity,
  87    pub message: String,
  88    pub group_id: usize,
  89    pub is_primary: bool,
  90}
  91
  92struct LanguageServerState {
  93    server: Arc<LanguageServer>,
  94    latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
  95    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
  96    next_version: usize,
  97    _maintain_server: Task<Option<()>>,
  98}
  99
 100#[derive(Clone)]
 101struct LanguageServerSnapshot {
 102    buffer_snapshot: buffer::Snapshot,
 103    version: usize,
 104    path: Arc<Path>,
 105}
 106
 107#[derive(Clone)]
 108pub enum Operation {
 109    Buffer(buffer::Operation),
 110    UpdateDiagnostics(AnchorRangeMultimap<Diagnostic>),
 111}
 112
 113#[derive(Clone, Debug, Eq, PartialEq)]
 114pub enum Event {
 115    Edited,
 116    Dirtied,
 117    Saved,
 118    FileHandleChanged,
 119    Reloaded,
 120    Reparsed,
 121    Closed,
 122}
 123
 124pub trait File {
 125    fn worktree_id(&self) -> usize;
 126
 127    fn entry_id(&self) -> Option<usize>;
 128
 129    fn mtime(&self) -> SystemTime;
 130
 131    /// Returns the path of this file relative to the worktree's root directory.
 132    fn path(&self) -> &Arc<Path>;
 133
 134    /// Returns the absolute path of this file.
 135    fn abs_path(&self) -> Option<PathBuf>;
 136
 137    /// Returns the path of this file relative to the worktree's parent directory (this means it
 138    /// includes the name of the worktree's root folder).
 139    fn full_path(&self) -> PathBuf;
 140
 141    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 142    /// of its worktree, then this method will return the name of the worktree itself.
 143    fn file_name(&self) -> Option<OsString>;
 144
 145    fn is_deleted(&self) -> bool;
 146
 147    fn save(
 148        &self,
 149        buffer_id: u64,
 150        text: Rope,
 151        version: clock::Global,
 152        cx: &mut MutableAppContext,
 153    ) -> Task<Result<(clock::Global, SystemTime)>>;
 154
 155    fn load_local(&self, cx: &AppContext) -> Option<Task<Result<String>>>;
 156
 157    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
 158
 159    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
 160
 161    fn boxed_clone(&self) -> Box<dyn File>;
 162
 163    fn as_any(&self) -> &dyn Any;
 164}
 165
 166struct QueryCursorHandle(Option<QueryCursor>);
 167
 168#[derive(Clone)]
 169struct SyntaxTree {
 170    tree: Tree,
 171    version: clock::Global,
 172}
 173
 174#[derive(Clone)]
 175struct AutoindentRequest {
 176    selection_set_ids: HashSet<SelectionSetId>,
 177    before_edit: Snapshot,
 178    edited: AnchorSet,
 179    inserted: Option<AnchorRangeSet>,
 180}
 181
 182#[derive(Debug)]
 183struct IndentSuggestion {
 184    basis_row: u32,
 185    indent: bool,
 186}
 187
 188struct TextProvider<'a>(&'a Rope);
 189
 190struct Highlights<'a> {
 191    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 192    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 193    stack: Vec<(usize, HighlightId)>,
 194    highlight_map: HighlightMap,
 195    theme: &'a SyntaxTheme,
 196    _query_cursor: QueryCursorHandle,
 197}
 198
 199pub struct Chunks<'a> {
 200    range: Range<usize>,
 201    chunks: rope::Chunks<'a>,
 202    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 203    error_depth: usize,
 204    warning_depth: usize,
 205    information_depth: usize,
 206    hint_depth: usize,
 207    highlights: Option<Highlights<'a>>,
 208}
 209
 210#[derive(Clone, Copy, Debug, Default)]
 211pub struct Chunk<'a> {
 212    pub text: &'a str,
 213    pub highlight_style: Option<HighlightStyle>,
 214    pub diagnostic: Option<DiagnosticSeverity>,
 215}
 216
 217struct Diff {
 218    base_version: clock::Global,
 219    new_text: Arc<str>,
 220    changes: Vec<(ChangeTag, usize)>,
 221}
 222
 223#[derive(Clone, Copy)]
 224struct DiagnosticEndpoint {
 225    offset: usize,
 226    is_start: bool,
 227    severity: DiagnosticSeverity,
 228}
 229
 230impl Buffer {
 231    pub fn new<T: Into<Arc<str>>>(
 232        replica_id: ReplicaId,
 233        base_text: T,
 234        cx: &mut ModelContext<Self>,
 235    ) -> Self {
 236        Self::build(
 237            TextBuffer::new(
 238                replica_id,
 239                cx.model_id() as u64,
 240                History::new(base_text.into()),
 241            ),
 242            None,
 243        )
 244    }
 245
 246    pub fn from_file<T: Into<Arc<str>>>(
 247        replica_id: ReplicaId,
 248        base_text: T,
 249        file: Box<dyn File>,
 250        cx: &mut ModelContext<Self>,
 251    ) -> Self {
 252        Self::build(
 253            TextBuffer::new(
 254                replica_id,
 255                cx.model_id() as u64,
 256                History::new(base_text.into()),
 257            ),
 258            Some(file),
 259        )
 260    }
 261
 262    pub fn from_proto(
 263        replica_id: ReplicaId,
 264        message: proto::Buffer,
 265        file: Option<Box<dyn File>>,
 266        cx: &mut ModelContext<Self>,
 267    ) -> Result<Self> {
 268        let mut buffer =
 269            buffer::Buffer::new(replica_id, message.id, History::new(message.content.into()));
 270        let ops = message
 271            .history
 272            .into_iter()
 273            .map(|op| buffer::Operation::Edit(proto::deserialize_edit_operation(op)));
 274        buffer.apply_ops(ops)?;
 275        for set in message.selections {
 276            let set = proto::deserialize_selection_set(set);
 277            buffer.add_raw_selection_set(set.id, set);
 278        }
 279        let mut this = Self::build(buffer, file);
 280        if let Some(diagnostics) = message.diagnostics {
 281            this.apply_diagnostic_update(proto::deserialize_diagnostics(diagnostics), cx);
 282        }
 283        Ok(this)
 284    }
 285
 286    pub fn to_proto(&self) -> proto::Buffer {
 287        proto::Buffer {
 288            id: self.remote_id(),
 289            content: self.text.base_text().to_string(),
 290            history: self
 291                .text
 292                .history()
 293                .map(proto::serialize_edit_operation)
 294                .collect(),
 295            selections: self
 296                .selection_sets()
 297                .map(|(_, set)| proto::serialize_selection_set(set))
 298                .collect(),
 299            diagnostics: Some(proto::serialize_diagnostics(&self.diagnostics)),
 300        }
 301    }
 302
 303    pub fn with_language(
 304        mut self,
 305        language: Option<Arc<Language>>,
 306        language_server: Option<Arc<LanguageServer>>,
 307        cx: &mut ModelContext<Self>,
 308    ) -> Self {
 309        self.set_language(language, language_server, cx);
 310        self
 311    }
 312
 313    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 314        let saved_mtime;
 315        if let Some(file) = file.as_ref() {
 316            saved_mtime = file.mtime();
 317        } else {
 318            saved_mtime = UNIX_EPOCH;
 319        }
 320
 321        Self {
 322            saved_mtime,
 323            saved_version: buffer.version(),
 324            text: buffer,
 325            file,
 326            syntax_tree: Mutex::new(None),
 327            parsing_in_background: false,
 328            parse_count: 0,
 329            sync_parse_timeout: Duration::from_millis(1),
 330            autoindent_requests: Default::default(),
 331            pending_autoindent: Default::default(),
 332            language: None,
 333            diagnostics: Default::default(),
 334            diagnostics_update_count: 0,
 335            language_server: None,
 336            #[cfg(test)]
 337            operations: Default::default(),
 338        }
 339    }
 340
 341    pub fn snapshot(&self) -> Snapshot {
 342        Snapshot {
 343            text: self.text.snapshot(),
 344            tree: self.syntax_tree(),
 345            diagnostics: self.diagnostics.clone(),
 346            is_parsing: self.parsing_in_background,
 347            language: self.language.clone(),
 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    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(language) = self.language.clone() {
 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 language = language.clone();
 603                async move { Self::parse_text(&text, old_tree, &language) }
 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 language_changed =
 620                                this.language.as_ref().map_or(true, |curr_language| {
 621                                    !Arc::ptr_eq(curr_language, &language)
 622                                });
 623                            let parse_again = this.version.gt(&parsed_version) || language_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>, language: &Language) -> Tree {
 640        PARSER.with(|parser| {
 641            let mut parser = parser.borrow_mut();
 642            parser
 643                .set_language(language.grammar)
 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.content()
 702        } else {
 703            self.content()
 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        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        let content = self.content();
 826        self.diagnostics
 827            .intersecting_ranges(search_range, content, 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        let content = self.content();
 839        self.diagnostics
 840            .filter(content, move |diagnostic| diagnostic.group_id == group_id)
 841            .map(move |(_, range, diagnostic)| (range, diagnostic))
 842    }
 843
 844    pub fn diagnostics_update_count(&self) -> usize {
 845        self.diagnostics_update_count
 846    }
 847
 848    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 849        if let Some(indent_columns) = self.compute_autoindents() {
 850            let indent_columns = cx.background().spawn(indent_columns);
 851            match cx
 852                .background()
 853                .block_with_timeout(Duration::from_micros(500), indent_columns)
 854            {
 855                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 856                Err(indent_columns) => {
 857                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 858                        let indent_columns = indent_columns.await;
 859                        this.update(&mut cx, |this, cx| {
 860                            this.apply_autoindents(indent_columns, cx);
 861                        });
 862                    }));
 863                }
 864            }
 865        }
 866    }
 867
 868    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 869        let max_rows_between_yields = 100;
 870        let snapshot = self.snapshot();
 871        if snapshot.language.is_none()
 872            || snapshot.tree.is_none()
 873            || self.autoindent_requests.is_empty()
 874        {
 875            return None;
 876        }
 877
 878        let autoindent_requests = self.autoindent_requests.clone();
 879        Some(async move {
 880            let mut indent_columns = BTreeMap::new();
 881            for request in autoindent_requests {
 882                let old_to_new_rows = request
 883                    .edited
 884                    .iter::<Point, _>(&request.before_edit)
 885                    .map(|point| point.row)
 886                    .zip(
 887                        request
 888                            .edited
 889                            .iter::<Point, _>(&snapshot)
 890                            .map(|point| point.row),
 891                    )
 892                    .collect::<BTreeMap<u32, u32>>();
 893
 894                let mut old_suggestions = HashMap::<u32, u32>::default();
 895                let old_edited_ranges =
 896                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 897                for old_edited_range in old_edited_ranges {
 898                    let suggestions = request
 899                        .before_edit
 900                        .suggest_autoindents(old_edited_range.clone())
 901                        .into_iter()
 902                        .flatten();
 903                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 904                        let indentation_basis = old_to_new_rows
 905                            .get(&suggestion.basis_row)
 906                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 907                            .unwrap_or_else(|| {
 908                                request
 909                                    .before_edit
 910                                    .indent_column_for_line(suggestion.basis_row)
 911                            });
 912                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 913                        old_suggestions.insert(
 914                            *old_to_new_rows.get(&old_row).unwrap(),
 915                            indentation_basis + delta,
 916                        );
 917                    }
 918                    yield_now().await;
 919                }
 920
 921                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 922                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 923                let new_edited_row_ranges =
 924                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 925                for new_edited_row_range in new_edited_row_ranges {
 926                    let suggestions = snapshot
 927                        .suggest_autoindents(new_edited_row_range.clone())
 928                        .into_iter()
 929                        .flatten();
 930                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 931                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 932                        let new_indentation = indent_columns
 933                            .get(&suggestion.basis_row)
 934                            .copied()
 935                            .unwrap_or_else(|| {
 936                                snapshot.indent_column_for_line(suggestion.basis_row)
 937                            })
 938                            + delta;
 939                        if old_suggestions
 940                            .get(&new_row)
 941                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 942                        {
 943                            indent_columns.insert(new_row, new_indentation);
 944                        }
 945                    }
 946                    yield_now().await;
 947                }
 948
 949                if let Some(inserted) = request.inserted.as_ref() {
 950                    let inserted_row_ranges = contiguous_ranges(
 951                        inserted
 952                            .ranges::<Point, _>(&snapshot)
 953                            .flat_map(|range| range.start.row..range.end.row + 1),
 954                        max_rows_between_yields,
 955                    );
 956                    for inserted_row_range in inserted_row_ranges {
 957                        let suggestions = snapshot
 958                            .suggest_autoindents(inserted_row_range.clone())
 959                            .into_iter()
 960                            .flatten();
 961                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
 962                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 963                            let new_indentation = indent_columns
 964                                .get(&suggestion.basis_row)
 965                                .copied()
 966                                .unwrap_or_else(|| {
 967                                    snapshot.indent_column_for_line(suggestion.basis_row)
 968                                })
 969                                + delta;
 970                            indent_columns.insert(row, new_indentation);
 971                        }
 972                        yield_now().await;
 973                    }
 974                }
 975            }
 976            indent_columns
 977        })
 978    }
 979
 980    fn apply_autoindents(
 981        &mut self,
 982        indent_columns: BTreeMap<u32, u32>,
 983        cx: &mut ModelContext<Self>,
 984    ) {
 985        let selection_set_ids = self
 986            .autoindent_requests
 987            .drain(..)
 988            .flat_map(|req| req.selection_set_ids.clone())
 989            .collect::<HashSet<_>>();
 990
 991        self.start_transaction(selection_set_ids.iter().copied())
 992            .unwrap();
 993        for (row, indent_column) in &indent_columns {
 994            self.set_indent_column_for_line(*row, *indent_column, cx);
 995        }
 996
 997        for selection_set_id in &selection_set_ids {
 998            if let Ok(set) = self.selection_set(*selection_set_id) {
 999                let new_selections = set
1000                    .selections::<Point, _>(&*self)
1001                    .map(|selection| {
1002                        if selection.start.column == 0 {
1003                            let delta = Point::new(
1004                                0,
1005                                indent_columns
1006                                    .get(&selection.start.row)
1007                                    .copied()
1008                                    .unwrap_or(0),
1009                            );
1010                            if delta.column > 0 {
1011                                return Selection {
1012                                    id: selection.id,
1013                                    goal: selection.goal,
1014                                    reversed: selection.reversed,
1015                                    start: selection.start + delta,
1016                                    end: selection.end + delta,
1017                                };
1018                            }
1019                        }
1020                        selection
1021                    })
1022                    .collect::<Vec<_>>();
1023                self.update_selection_set(*selection_set_id, &new_selections, cx)
1024                    .unwrap();
1025            }
1026        }
1027
1028        self.end_transaction(selection_set_ids.iter().copied(), cx)
1029            .unwrap();
1030    }
1031
1032    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1033        self.content().indent_column_for_line(row)
1034    }
1035
1036    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1037        let current_column = self.indent_column_for_line(row);
1038        if column > current_column {
1039            let offset = Point::new(row, 0).to_offset(&*self);
1040            self.edit(
1041                [offset..offset],
1042                " ".repeat((column - current_column) as usize),
1043                cx,
1044            );
1045        } else if column < current_column {
1046            self.edit(
1047                [Point::new(row, 0)..Point::new(row, current_column - column)],
1048                "",
1049                cx,
1050            );
1051        }
1052    }
1053
1054    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1055        if let Some(tree) = self.syntax_tree() {
1056            let root = tree.root_node();
1057            let range = range.start.to_offset(self)..range.end.to_offset(self);
1058            let mut node = root.descendant_for_byte_range(range.start, range.end);
1059            while node.map_or(false, |n| n.byte_range() == range) {
1060                node = node.unwrap().parent();
1061            }
1062            node.map(|n| n.byte_range())
1063        } else {
1064            None
1065        }
1066    }
1067
1068    pub fn enclosing_bracket_ranges<T: ToOffset>(
1069        &self,
1070        range: Range<T>,
1071    ) -> Option<(Range<usize>, Range<usize>)> {
1072        let (lang, tree) = self.language.as_ref().zip(self.syntax_tree())?;
1073        let open_capture_ix = lang.brackets_query.capture_index_for_name("open")?;
1074        let close_capture_ix = lang.brackets_query.capture_index_for_name("close")?;
1075
1076        // Find bracket pairs that *inclusively* contain the given range.
1077        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1078        let mut cursor = QueryCursorHandle::new();
1079        let matches = cursor.set_byte_range(range).matches(
1080            &lang.brackets_query,
1081            tree.root_node(),
1082            TextProvider(self.as_rope()),
1083        );
1084
1085        // Get the ranges of the innermost pair of brackets.
1086        matches
1087            .filter_map(|mat| {
1088                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1089                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1090                Some((open.byte_range(), close.byte_range()))
1091            })
1092            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1093    }
1094
1095    fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1096        // TODO: it would be nice to not allocate here.
1097        let old_text = self.text();
1098        let base_version = self.version();
1099        cx.background().spawn(async move {
1100            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1101                .iter_all_changes()
1102                .map(|c| (c.tag(), c.value().len()))
1103                .collect::<Vec<_>>();
1104            Diff {
1105                base_version,
1106                new_text,
1107                changes,
1108            }
1109        })
1110    }
1111
1112    fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1113        if self.version == diff.base_version {
1114            self.start_transaction(None).unwrap();
1115            let mut offset = 0;
1116            for (tag, len) in diff.changes {
1117                let range = offset..(offset + len);
1118                match tag {
1119                    ChangeTag::Equal => offset += len,
1120                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1121                    ChangeTag::Insert => {
1122                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1123                        offset += len;
1124                    }
1125                }
1126            }
1127            self.end_transaction(None, cx).unwrap();
1128            true
1129        } else {
1130            false
1131        }
1132    }
1133
1134    pub fn is_dirty(&self) -> bool {
1135        !self.saved_version.ge(&self.version)
1136            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1137    }
1138
1139    pub fn has_conflict(&self) -> bool {
1140        !self.saved_version.ge(&self.version)
1141            && self
1142                .file
1143                .as_ref()
1144                .map_or(false, |file| file.mtime() > self.saved_mtime)
1145    }
1146
1147    pub fn start_transaction(
1148        &mut self,
1149        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1150    ) -> Result<()> {
1151        self.start_transaction_at(selection_set_ids, Instant::now())
1152    }
1153
1154    fn start_transaction_at(
1155        &mut self,
1156        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1157        now: Instant,
1158    ) -> Result<()> {
1159        self.text.start_transaction_at(selection_set_ids, now)
1160    }
1161
1162    pub fn end_transaction(
1163        &mut self,
1164        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1165        cx: &mut ModelContext<Self>,
1166    ) -> Result<()> {
1167        self.end_transaction_at(selection_set_ids, Instant::now(), cx)
1168    }
1169
1170    fn end_transaction_at(
1171        &mut self,
1172        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1173        now: Instant,
1174        cx: &mut ModelContext<Self>,
1175    ) -> Result<()> {
1176        if let Some(start_version) = self.text.end_transaction_at(selection_set_ids, now) {
1177            let was_dirty = start_version != self.saved_version;
1178            self.did_edit(&start_version, was_dirty, cx);
1179        }
1180        Ok(())
1181    }
1182
1183    fn update_language_server(&mut self) {
1184        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1185            language_server
1186        } else {
1187            return;
1188        };
1189        let abs_path = self
1190            .file
1191            .as_ref()
1192            .map_or(Path::new("/").to_path_buf(), |file| {
1193                file.abs_path().unwrap()
1194            });
1195
1196        let version = post_inc(&mut language_server.next_version);
1197        let snapshot = LanguageServerSnapshot {
1198            buffer_snapshot: self.text.snapshot(),
1199            version,
1200            path: Arc::from(abs_path),
1201        };
1202        language_server
1203            .pending_snapshots
1204            .insert(version, snapshot.clone());
1205        let _ = language_server
1206            .latest_snapshot
1207            .blocking_send(Some(snapshot));
1208    }
1209
1210    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1211    where
1212        I: IntoIterator<Item = Range<S>>,
1213        S: ToOffset,
1214        T: Into<String>,
1215    {
1216        self.edit_internal(ranges_iter, new_text, false, cx)
1217    }
1218
1219    pub fn edit_with_autoindent<I, S, T>(
1220        &mut self,
1221        ranges_iter: I,
1222        new_text: T,
1223        cx: &mut ModelContext<Self>,
1224    ) where
1225        I: IntoIterator<Item = Range<S>>,
1226        S: ToOffset,
1227        T: Into<String>,
1228    {
1229        self.edit_internal(ranges_iter, new_text, true, cx)
1230    }
1231
1232    pub fn edit_internal<I, S, T>(
1233        &mut self,
1234        ranges_iter: I,
1235        new_text: T,
1236        autoindent: bool,
1237        cx: &mut ModelContext<Self>,
1238    ) where
1239        I: IntoIterator<Item = Range<S>>,
1240        S: ToOffset,
1241        T: Into<String>,
1242    {
1243        let new_text = new_text.into();
1244
1245        // Skip invalid ranges and coalesce contiguous ones.
1246        let mut ranges: Vec<Range<usize>> = Vec::new();
1247        for range in ranges_iter {
1248            let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1249            if !new_text.is_empty() || !range.is_empty() {
1250                if let Some(prev_range) = ranges.last_mut() {
1251                    if prev_range.end >= range.start {
1252                        prev_range.end = cmp::max(prev_range.end, range.end);
1253                    } else {
1254                        ranges.push(range);
1255                    }
1256                } else {
1257                    ranges.push(range);
1258                }
1259            }
1260        }
1261        if ranges.is_empty() {
1262            return;
1263        }
1264
1265        self.start_transaction(None).unwrap();
1266        self.pending_autoindent.take();
1267        let autoindent_request = if autoindent && self.language.is_some() {
1268            let before_edit = self.snapshot();
1269            let edited = self.content().anchor_set(
1270                Bias::Left,
1271                ranges.iter().filter_map(|range| {
1272                    let start = range.start.to_point(&*self);
1273                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1274                        None
1275                    } else {
1276                        Some(range.start)
1277                    }
1278                }),
1279            );
1280            Some((before_edit, edited))
1281        } else {
1282            None
1283        };
1284
1285        let first_newline_ix = new_text.find('\n');
1286        let new_text_len = new_text.len();
1287
1288        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1289
1290        if let Some((before_edit, edited)) = autoindent_request {
1291            let mut inserted = None;
1292            if let Some(first_newline_ix) = first_newline_ix {
1293                let mut delta = 0isize;
1294                inserted = Some(self.content().anchor_range_set(
1295                    Bias::Left,
1296                    Bias::Right,
1297                    ranges.iter().map(|range| {
1298                        let start = (delta + range.start as isize) as usize + first_newline_ix + 1;
1299                        let end = (delta + range.start as isize) as usize + new_text_len;
1300                        delta +=
1301                            (range.end as isize - range.start as isize) + new_text_len as isize;
1302                        start..end
1303                    }),
1304                ));
1305            }
1306
1307            let selection_set_ids = self
1308                .text
1309                .peek_undo_stack()
1310                .unwrap()
1311                .starting_selection_set_ids()
1312                .collect();
1313            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1314                selection_set_ids,
1315                before_edit,
1316                edited,
1317                inserted,
1318            }));
1319        }
1320
1321        self.end_transaction(None, cx).unwrap();
1322        self.send_operation(Operation::Buffer(buffer::Operation::Edit(edit)), cx);
1323    }
1324
1325    fn did_edit(
1326        &mut self,
1327        old_version: &clock::Global,
1328        was_dirty: bool,
1329        cx: &mut ModelContext<Self>,
1330    ) {
1331        if self.edits_since::<usize>(old_version).next().is_none() {
1332            return;
1333        }
1334
1335        self.reparse(cx);
1336        self.update_language_server();
1337
1338        cx.emit(Event::Edited);
1339        if !was_dirty {
1340            cx.emit(Event::Dirtied);
1341        }
1342        cx.notify();
1343    }
1344
1345    pub fn add_selection_set<T: ToOffset>(
1346        &mut self,
1347        selections: &[Selection<T>],
1348        cx: &mut ModelContext<Self>,
1349    ) -> SelectionSetId {
1350        let operation = self.text.add_selection_set(selections);
1351        if let buffer::Operation::UpdateSelections { set_id, .. } = &operation {
1352            let set_id = *set_id;
1353            cx.notify();
1354            self.send_operation(Operation::Buffer(operation), cx);
1355            set_id
1356        } else {
1357            unreachable!()
1358        }
1359    }
1360
1361    pub fn update_selection_set<T: ToOffset>(
1362        &mut self,
1363        set_id: SelectionSetId,
1364        selections: &[Selection<T>],
1365        cx: &mut ModelContext<Self>,
1366    ) -> Result<()> {
1367        let operation = self.text.update_selection_set(set_id, selections)?;
1368        cx.notify();
1369        self.send_operation(Operation::Buffer(operation), cx);
1370        Ok(())
1371    }
1372
1373    pub fn set_active_selection_set(
1374        &mut self,
1375        set_id: Option<SelectionSetId>,
1376        cx: &mut ModelContext<Self>,
1377    ) -> Result<()> {
1378        let operation = self.text.set_active_selection_set(set_id)?;
1379        self.send_operation(Operation::Buffer(operation), cx);
1380        Ok(())
1381    }
1382
1383    pub fn remove_selection_set(
1384        &mut self,
1385        set_id: SelectionSetId,
1386        cx: &mut ModelContext<Self>,
1387    ) -> Result<()> {
1388        let operation = self.text.remove_selection_set(set_id)?;
1389        cx.notify();
1390        self.send_operation(Operation::Buffer(operation), cx);
1391        Ok(())
1392    }
1393
1394    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1395        &mut self,
1396        ops: I,
1397        cx: &mut ModelContext<Self>,
1398    ) -> Result<()> {
1399        self.pending_autoindent.take();
1400        let was_dirty = self.is_dirty();
1401        let old_version = self.version.clone();
1402        let buffer_ops = ops
1403            .into_iter()
1404            .filter_map(|op| match op {
1405                Operation::Buffer(op) => Some(op),
1406                Operation::UpdateDiagnostics(diagnostics) => {
1407                    self.apply_diagnostic_update(diagnostics, cx);
1408                    None
1409                }
1410            })
1411            .collect::<Vec<_>>();
1412        self.text.apply_ops(buffer_ops)?;
1413        self.did_edit(&old_version, was_dirty, cx);
1414        // Notify independently of whether the buffer was edited as the operations could include a
1415        // selection update.
1416        cx.notify();
1417        Ok(())
1418    }
1419
1420    fn apply_diagnostic_update(
1421        &mut self,
1422        diagnostics: AnchorRangeMultimap<Diagnostic>,
1423        cx: &mut ModelContext<Self>,
1424    ) {
1425        self.diagnostics = diagnostics;
1426        self.diagnostics_update_count += 1;
1427        cx.notify();
1428    }
1429
1430    #[cfg(not(test))]
1431    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1432        if let Some(file) = &self.file {
1433            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1434        }
1435    }
1436
1437    #[cfg(test)]
1438    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1439        self.operations.push(operation);
1440    }
1441
1442    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1443        self.text.remove_peer(replica_id);
1444        cx.notify();
1445    }
1446
1447    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
1448        let was_dirty = self.is_dirty();
1449        let old_version = self.version.clone();
1450
1451        for operation in self.text.undo() {
1452            self.send_operation(Operation::Buffer(operation), cx);
1453        }
1454
1455        self.did_edit(&old_version, was_dirty, cx);
1456    }
1457
1458    pub fn redo(&mut self, cx: &mut ModelContext<Self>) {
1459        let was_dirty = self.is_dirty();
1460        let old_version = self.version.clone();
1461
1462        for operation in self.text.redo() {
1463            self.send_operation(Operation::Buffer(operation), cx);
1464        }
1465
1466        self.did_edit(&old_version, was_dirty, cx);
1467    }
1468}
1469
1470#[cfg(any(test, feature = "test-support"))]
1471impl Buffer {
1472    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize)
1473    where
1474        T: rand::Rng,
1475    {
1476        self.text.randomly_edit(rng, old_range_count);
1477    }
1478
1479    pub fn randomly_mutate<T>(&mut self, rng: &mut T)
1480    where
1481        T: rand::Rng,
1482    {
1483        self.text.randomly_mutate(rng);
1484    }
1485}
1486
1487impl Entity for Buffer {
1488    type Event = Event;
1489
1490    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1491        if let Some(file) = self.file.as_ref() {
1492            file.buffer_removed(self.remote_id(), cx);
1493        }
1494    }
1495}
1496
1497// TODO: Do we need to clone a buffer?
1498impl Clone for Buffer {
1499    fn clone(&self) -> Self {
1500        Self {
1501            text: self.text.clone(),
1502            saved_version: self.saved_version.clone(),
1503            saved_mtime: self.saved_mtime,
1504            file: self.file.as_ref().map(|f| f.boxed_clone()),
1505            language: self.language.clone(),
1506            syntax_tree: Mutex::new(self.syntax_tree.lock().clone()),
1507            parsing_in_background: false,
1508            sync_parse_timeout: self.sync_parse_timeout,
1509            parse_count: self.parse_count,
1510            autoindent_requests: Default::default(),
1511            pending_autoindent: Default::default(),
1512            diagnostics: self.diagnostics.clone(),
1513            diagnostics_update_count: self.diagnostics_update_count,
1514            language_server: None,
1515            #[cfg(test)]
1516            operations: self.operations.clone(),
1517        }
1518    }
1519}
1520
1521impl Deref for Buffer {
1522    type Target = TextBuffer;
1523
1524    fn deref(&self) -> &Self::Target {
1525        &self.text
1526    }
1527}
1528
1529impl<'a> From<&'a Buffer> for Content<'a> {
1530    fn from(buffer: &'a Buffer) -> Self {
1531        Self::from(&buffer.text)
1532    }
1533}
1534
1535impl<'a> From<&'a mut Buffer> for Content<'a> {
1536    fn from(buffer: &'a mut Buffer) -> Self {
1537        Self::from(&buffer.text)
1538    }
1539}
1540
1541impl<'a> From<&'a Snapshot> for Content<'a> {
1542    fn from(snapshot: &'a Snapshot) -> Self {
1543        Self::from(&snapshot.text)
1544    }
1545}
1546
1547impl Snapshot {
1548    fn suggest_autoindents<'a>(
1549        &'a self,
1550        row_range: Range<u32>,
1551    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1552        let mut query_cursor = QueryCursorHandle::new();
1553        if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1554            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1555
1556            // Get the "indentation ranges" that intersect this row range.
1557            let indent_capture_ix = language.indents_query.capture_index_for_name("indent");
1558            let end_capture_ix = language.indents_query.capture_index_for_name("end");
1559            query_cursor.set_point_range(
1560                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1561                    ..Point::new(row_range.end, 0).to_ts_point(),
1562            );
1563            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1564            for mat in query_cursor.matches(
1565                &language.indents_query,
1566                tree.root_node(),
1567                TextProvider(self.as_rope()),
1568            ) {
1569                let mut node_kind = "";
1570                let mut start: Option<Point> = None;
1571                let mut end: Option<Point> = None;
1572                for capture in mat.captures {
1573                    if Some(capture.index) == indent_capture_ix {
1574                        node_kind = capture.node.kind();
1575                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1576                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1577                    } else if Some(capture.index) == end_capture_ix {
1578                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1579                    }
1580                }
1581
1582                if let Some((start, end)) = start.zip(end) {
1583                    if start.row == end.row {
1584                        continue;
1585                    }
1586
1587                    let range = start..end;
1588                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1589                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1590                        Ok(ix) => {
1591                            let prev_range = &mut indentation_ranges[ix];
1592                            prev_range.0.end = prev_range.0.end.max(range.end);
1593                        }
1594                    }
1595                }
1596            }
1597
1598            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1599            Some(row_range.map(move |row| {
1600                let row_start = Point::new(row, self.indent_column_for_line(row));
1601
1602                let mut indent_from_prev_row = false;
1603                let mut outdent_to_row = u32::MAX;
1604                for (range, _node_kind) in &indentation_ranges {
1605                    if range.start.row >= row {
1606                        break;
1607                    }
1608
1609                    if range.start.row == prev_row && range.end > row_start {
1610                        indent_from_prev_row = true;
1611                    }
1612                    if range.end.row >= prev_row && range.end <= row_start {
1613                        outdent_to_row = outdent_to_row.min(range.start.row);
1614                    }
1615                }
1616
1617                let suggestion = if outdent_to_row == prev_row {
1618                    IndentSuggestion {
1619                        basis_row: prev_row,
1620                        indent: false,
1621                    }
1622                } else if indent_from_prev_row {
1623                    IndentSuggestion {
1624                        basis_row: prev_row,
1625                        indent: true,
1626                    }
1627                } else if outdent_to_row < prev_row {
1628                    IndentSuggestion {
1629                        basis_row: outdent_to_row,
1630                        indent: false,
1631                    }
1632                } else {
1633                    IndentSuggestion {
1634                        basis_row: prev_row,
1635                        indent: false,
1636                    }
1637                };
1638
1639                prev_row = row;
1640                suggestion
1641            }))
1642        } else {
1643            None
1644        }
1645    }
1646
1647    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1648        while row > 0 {
1649            row -= 1;
1650            if !self.is_line_blank(row) {
1651                return Some(row);
1652            }
1653        }
1654        None
1655    }
1656
1657    pub fn chunks<'a, T: ToOffset>(
1658        &'a self,
1659        range: Range<T>,
1660        theme: Option<&'a SyntaxTheme>,
1661    ) -> Chunks<'a> {
1662        let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1663
1664        let mut highlights = None;
1665        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1666        if let Some(theme) = theme {
1667            for (_, range, diagnostic) in
1668                self.diagnostics
1669                    .intersecting_ranges(range.clone(), self.content(), true)
1670            {
1671                diagnostic_endpoints.push(DiagnosticEndpoint {
1672                    offset: range.start,
1673                    is_start: true,
1674                    severity: diagnostic.severity,
1675                });
1676                diagnostic_endpoints.push(DiagnosticEndpoint {
1677                    offset: range.end,
1678                    is_start: false,
1679                    severity: diagnostic.severity,
1680                });
1681            }
1682            diagnostic_endpoints
1683                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1684
1685            if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1686                let mut query_cursor = QueryCursorHandle::new();
1687
1688                // TODO - add a Tree-sitter API to remove the need for this.
1689                let cursor = unsafe {
1690                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1691                };
1692                let captures = cursor.set_byte_range(range.clone()).captures(
1693                    &language.highlights_query,
1694                    tree.root_node(),
1695                    TextProvider(self.text.as_rope()),
1696                );
1697                highlights = Some(Highlights {
1698                    captures,
1699                    next_capture: None,
1700                    stack: Default::default(),
1701                    highlight_map: language.highlight_map(),
1702                    _query_cursor: query_cursor,
1703                    theme,
1704                })
1705            }
1706        }
1707
1708        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1709        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1710
1711        Chunks {
1712            range,
1713            chunks,
1714            diagnostic_endpoints,
1715            error_depth: 0,
1716            warning_depth: 0,
1717            information_depth: 0,
1718            hint_depth: 0,
1719            highlights,
1720        }
1721    }
1722}
1723
1724impl Clone for Snapshot {
1725    fn clone(&self) -> Self {
1726        Self {
1727            text: self.text.clone(),
1728            tree: self.tree.clone(),
1729            diagnostics: self.diagnostics.clone(),
1730            is_parsing: self.is_parsing,
1731            language: self.language.clone(),
1732        }
1733    }
1734}
1735
1736impl Deref for Snapshot {
1737    type Target = buffer::Snapshot;
1738
1739    fn deref(&self) -> &Self::Target {
1740        &self.text
1741    }
1742}
1743
1744impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1745    type I = ByteChunks<'a>;
1746
1747    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1748        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1749    }
1750}
1751
1752struct ByteChunks<'a>(rope::Chunks<'a>);
1753
1754impl<'a> Iterator for ByteChunks<'a> {
1755    type Item = &'a [u8];
1756
1757    fn next(&mut self) -> Option<Self::Item> {
1758        self.0.next().map(str::as_bytes)
1759    }
1760}
1761
1762unsafe impl<'a> Send for Chunks<'a> {}
1763
1764impl<'a> Chunks<'a> {
1765    pub fn seek(&mut self, offset: usize) {
1766        self.range.start = offset;
1767        self.chunks.seek(self.range.start);
1768        if let Some(highlights) = self.highlights.as_mut() {
1769            highlights
1770                .stack
1771                .retain(|(end_offset, _)| *end_offset > offset);
1772            if let Some((mat, capture_ix)) = &highlights.next_capture {
1773                let capture = mat.captures[*capture_ix as usize];
1774                if offset >= capture.node.start_byte() {
1775                    let next_capture_end = capture.node.end_byte();
1776                    if offset < next_capture_end {
1777                        highlights.stack.push((
1778                            next_capture_end,
1779                            highlights.highlight_map.get(capture.index),
1780                        ));
1781                    }
1782                    highlights.next_capture.take();
1783                }
1784            }
1785            highlights.captures.set_byte_range(self.range.clone());
1786        }
1787    }
1788
1789    pub fn offset(&self) -> usize {
1790        self.range.start
1791    }
1792
1793    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1794        let depth = match endpoint.severity {
1795            DiagnosticSeverity::ERROR => &mut self.error_depth,
1796            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1797            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1798            DiagnosticSeverity::HINT => &mut self.hint_depth,
1799            _ => return,
1800        };
1801        if endpoint.is_start {
1802            *depth += 1;
1803        } else {
1804            *depth -= 1;
1805        }
1806    }
1807
1808    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1809        if self.error_depth > 0 {
1810            Some(DiagnosticSeverity::ERROR)
1811        } else if self.warning_depth > 0 {
1812            Some(DiagnosticSeverity::WARNING)
1813        } else if self.information_depth > 0 {
1814            Some(DiagnosticSeverity::INFORMATION)
1815        } else if self.hint_depth > 0 {
1816            Some(DiagnosticSeverity::HINT)
1817        } else {
1818            None
1819        }
1820    }
1821}
1822
1823impl<'a> Iterator for Chunks<'a> {
1824    type Item = Chunk<'a>;
1825
1826    fn next(&mut self) -> Option<Self::Item> {
1827        let mut next_capture_start = usize::MAX;
1828        let mut next_diagnostic_endpoint = usize::MAX;
1829
1830        if let Some(highlights) = self.highlights.as_mut() {
1831            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1832                if *parent_capture_end <= self.range.start {
1833                    highlights.stack.pop();
1834                } else {
1835                    break;
1836                }
1837            }
1838
1839            if highlights.next_capture.is_none() {
1840                highlights.next_capture = highlights.captures.next();
1841            }
1842
1843            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1844                let capture = mat.captures[*capture_ix as usize];
1845                if self.range.start < capture.node.start_byte() {
1846                    next_capture_start = capture.node.start_byte();
1847                    break;
1848                } else {
1849                    let highlight_id = highlights.highlight_map.get(capture.index);
1850                    highlights
1851                        .stack
1852                        .push((capture.node.end_byte(), highlight_id));
1853                    highlights.next_capture = highlights.captures.next();
1854                }
1855            }
1856        }
1857
1858        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1859            if endpoint.offset <= self.range.start {
1860                self.update_diagnostic_depths(endpoint);
1861                self.diagnostic_endpoints.next();
1862            } else {
1863                next_diagnostic_endpoint = endpoint.offset;
1864                break;
1865            }
1866        }
1867
1868        if let Some(chunk) = self.chunks.peek() {
1869            let chunk_start = self.range.start;
1870            let mut chunk_end = (self.chunks.offset() + chunk.len())
1871                .min(next_capture_start)
1872                .min(next_diagnostic_endpoint);
1873            let mut highlight_style = None;
1874            if let Some(highlights) = self.highlights.as_ref() {
1875                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
1876                    chunk_end = chunk_end.min(*parent_capture_end);
1877                    highlight_style = parent_highlight_id.style(highlights.theme);
1878                }
1879            }
1880
1881            let slice =
1882                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1883            self.range.start = chunk_end;
1884            if self.range.start == self.chunks.offset() + chunk.len() {
1885                self.chunks.next().unwrap();
1886            }
1887
1888            Some(Chunk {
1889                text: slice,
1890                highlight_style,
1891                diagnostic: self.current_diagnostic_severity(),
1892            })
1893        } else {
1894            None
1895        }
1896    }
1897}
1898
1899impl QueryCursorHandle {
1900    fn new() -> Self {
1901        QueryCursorHandle(Some(
1902            QUERY_CURSORS
1903                .lock()
1904                .pop()
1905                .unwrap_or_else(|| QueryCursor::new()),
1906        ))
1907    }
1908}
1909
1910impl Deref for QueryCursorHandle {
1911    type Target = QueryCursor;
1912
1913    fn deref(&self) -> &Self::Target {
1914        self.0.as_ref().unwrap()
1915    }
1916}
1917
1918impl DerefMut for QueryCursorHandle {
1919    fn deref_mut(&mut self) -> &mut Self::Target {
1920        self.0.as_mut().unwrap()
1921    }
1922}
1923
1924impl Drop for QueryCursorHandle {
1925    fn drop(&mut self) {
1926        let mut cursor = self.0.take().unwrap();
1927        cursor.set_byte_range(0..usize::MAX);
1928        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
1929        QUERY_CURSORS.lock().push(cursor)
1930    }
1931}
1932
1933trait ToTreeSitterPoint {
1934    fn to_ts_point(self) -> tree_sitter::Point;
1935    fn from_ts_point(point: tree_sitter::Point) -> Self;
1936}
1937
1938impl ToTreeSitterPoint for Point {
1939    fn to_ts_point(self) -> tree_sitter::Point {
1940        tree_sitter::Point::new(self.row as usize, self.column as usize)
1941    }
1942
1943    fn from_ts_point(point: tree_sitter::Point) -> Self {
1944        Point::new(point.row as u32, point.column as u32)
1945    }
1946}
1947
1948trait ToPointUtf16 {
1949    fn to_point_utf16(self) -> PointUtf16;
1950}
1951
1952impl ToPointUtf16 for lsp::Position {
1953    fn to_point_utf16(self) -> PointUtf16 {
1954        PointUtf16::new(self.line, self.character)
1955    }
1956}
1957
1958fn diagnostic_ranges<'a>(
1959    diagnostic: &'a lsp::Diagnostic,
1960    abs_path: Option<&'a Path>,
1961) -> impl 'a + Iterator<Item = Range<PointUtf16>> {
1962    diagnostic
1963        .related_information
1964        .iter()
1965        .flatten()
1966        .filter_map(move |info| {
1967            if info.location.uri.to_file_path().ok()? == abs_path? {
1968                let info_start = PointUtf16::new(
1969                    info.location.range.start.line,
1970                    info.location.range.start.character,
1971                );
1972                let info_end = PointUtf16::new(
1973                    info.location.range.end.line,
1974                    info.location.range.end.character,
1975                );
1976                Some(info_start..info_end)
1977            } else {
1978                None
1979            }
1980        })
1981        .chain(Some(
1982            diagnostic.range.start.to_point_utf16()..diagnostic.range.end.to_point_utf16(),
1983        ))
1984}
1985
1986fn contiguous_ranges(
1987    values: impl IntoIterator<Item = u32>,
1988    max_len: usize,
1989) -> impl Iterator<Item = Range<u32>> {
1990    let mut values = values.into_iter();
1991    let mut current_range: Option<Range<u32>> = None;
1992    std::iter::from_fn(move || loop {
1993        if let Some(value) = values.next() {
1994            if let Some(range) = &mut current_range {
1995                if value == range.end && range.len() < max_len {
1996                    range.end += 1;
1997                    continue;
1998                }
1999            }
2000
2001            let prev_range = current_range.clone();
2002            current_range = Some(value..(value + 1));
2003            if prev_range.is_some() {
2004                return prev_range;
2005            }
2006        } else {
2007            return current_range.take();
2008        }
2009    })
2010}