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(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, Bias::Left))
1275                }
1276            }));
1277            Some((before_edit, edited))
1278        } else {
1279            None
1280        };
1281
1282        let first_newline_ix = new_text.find('\n');
1283        let new_text_len = new_text.len();
1284
1285        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1286
1287        if let Some((before_edit, edited)) = autoindent_request {
1288            let mut inserted = None;
1289            if let Some(first_newline_ix) = first_newline_ix {
1290                let mut delta = 0isize;
1291                inserted = Some(self.content().anchor_range_set(ranges.iter().map(|range| {
1292                    let start = (delta + range.start as isize) as usize + first_newline_ix + 1;
1293                    let end = (delta + range.start as isize) as usize + new_text_len;
1294                    delta += (range.end as isize - range.start as isize) + new_text_len as isize;
1295                    (start, Bias::Left)..(end, Bias::Right)
1296                })));
1297            }
1298
1299            let selection_set_ids = self
1300                .text
1301                .peek_undo_stack()
1302                .unwrap()
1303                .starting_selection_set_ids()
1304                .collect();
1305            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1306                selection_set_ids,
1307                before_edit,
1308                edited,
1309                inserted,
1310            }));
1311        }
1312
1313        self.end_transaction(None, cx).unwrap();
1314        self.send_operation(Operation::Buffer(buffer::Operation::Edit(edit)), cx);
1315    }
1316
1317    fn did_edit(
1318        &mut self,
1319        old_version: &clock::Global,
1320        was_dirty: bool,
1321        cx: &mut ModelContext<Self>,
1322    ) {
1323        if self.edits_since::<usize>(old_version).next().is_none() {
1324            return;
1325        }
1326
1327        self.reparse(cx);
1328        self.update_language_server();
1329
1330        cx.emit(Event::Edited);
1331        if !was_dirty {
1332            cx.emit(Event::Dirtied);
1333        }
1334        cx.notify();
1335    }
1336
1337    pub fn add_selection_set<T: ToOffset>(
1338        &mut self,
1339        selections: &[Selection<T>],
1340        cx: &mut ModelContext<Self>,
1341    ) -> SelectionSetId {
1342        let operation = self.text.add_selection_set(selections);
1343        if let buffer::Operation::UpdateSelections { set_id, .. } = &operation {
1344            let set_id = *set_id;
1345            cx.notify();
1346            self.send_operation(Operation::Buffer(operation), cx);
1347            set_id
1348        } else {
1349            unreachable!()
1350        }
1351    }
1352
1353    pub fn update_selection_set<T: ToOffset>(
1354        &mut self,
1355        set_id: SelectionSetId,
1356        selections: &[Selection<T>],
1357        cx: &mut ModelContext<Self>,
1358    ) -> Result<()> {
1359        let operation = self.text.update_selection_set(set_id, selections)?;
1360        cx.notify();
1361        self.send_operation(Operation::Buffer(operation), cx);
1362        Ok(())
1363    }
1364
1365    pub fn set_active_selection_set(
1366        &mut self,
1367        set_id: Option<SelectionSetId>,
1368        cx: &mut ModelContext<Self>,
1369    ) -> Result<()> {
1370        let operation = self.text.set_active_selection_set(set_id)?;
1371        self.send_operation(Operation::Buffer(operation), cx);
1372        Ok(())
1373    }
1374
1375    pub fn remove_selection_set(
1376        &mut self,
1377        set_id: SelectionSetId,
1378        cx: &mut ModelContext<Self>,
1379    ) -> Result<()> {
1380        let operation = self.text.remove_selection_set(set_id)?;
1381        cx.notify();
1382        self.send_operation(Operation::Buffer(operation), cx);
1383        Ok(())
1384    }
1385
1386    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1387        &mut self,
1388        ops: I,
1389        cx: &mut ModelContext<Self>,
1390    ) -> Result<()> {
1391        self.pending_autoindent.take();
1392        let was_dirty = self.is_dirty();
1393        let old_version = self.version.clone();
1394        let buffer_ops = ops
1395            .into_iter()
1396            .filter_map(|op| match op {
1397                Operation::Buffer(op) => Some(op),
1398                Operation::UpdateDiagnostics(diagnostics) => {
1399                    self.apply_diagnostic_update(diagnostics, cx);
1400                    None
1401                }
1402            })
1403            .collect::<Vec<_>>();
1404        self.text.apply_ops(buffer_ops)?;
1405        self.did_edit(&old_version, was_dirty, cx);
1406        // Notify independently of whether the buffer was edited as the operations could include a
1407        // selection update.
1408        cx.notify();
1409        Ok(())
1410    }
1411
1412    fn apply_diagnostic_update(
1413        &mut self,
1414        diagnostics: AnchorRangeMultimap<Diagnostic>,
1415        cx: &mut ModelContext<Self>,
1416    ) {
1417        self.diagnostics = diagnostics;
1418        self.diagnostics_update_count += 1;
1419        cx.notify();
1420    }
1421
1422    #[cfg(not(test))]
1423    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1424        if let Some(file) = &self.file {
1425            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1426        }
1427    }
1428
1429    #[cfg(test)]
1430    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1431        self.operations.push(operation);
1432    }
1433
1434    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1435        self.text.remove_peer(replica_id);
1436        cx.notify();
1437    }
1438
1439    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
1440        let was_dirty = self.is_dirty();
1441        let old_version = self.version.clone();
1442
1443        for operation in self.text.undo() {
1444            self.send_operation(Operation::Buffer(operation), cx);
1445        }
1446
1447        self.did_edit(&old_version, was_dirty, cx);
1448    }
1449
1450    pub fn redo(&mut self, cx: &mut ModelContext<Self>) {
1451        let was_dirty = self.is_dirty();
1452        let old_version = self.version.clone();
1453
1454        for operation in self.text.redo() {
1455            self.send_operation(Operation::Buffer(operation), cx);
1456        }
1457
1458        self.did_edit(&old_version, was_dirty, cx);
1459    }
1460}
1461
1462#[cfg(any(test, feature = "test-support"))]
1463impl Buffer {
1464    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize)
1465    where
1466        T: rand::Rng,
1467    {
1468        self.text.randomly_edit(rng, old_range_count);
1469    }
1470
1471    pub fn randomly_mutate<T>(&mut self, rng: &mut T)
1472    where
1473        T: rand::Rng,
1474    {
1475        self.text.randomly_mutate(rng);
1476    }
1477}
1478
1479impl Entity for Buffer {
1480    type Event = Event;
1481
1482    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1483        if let Some(file) = self.file.as_ref() {
1484            file.buffer_removed(self.remote_id(), cx);
1485        }
1486    }
1487}
1488
1489// TODO: Do we need to clone a buffer?
1490impl Clone for Buffer {
1491    fn clone(&self) -> Self {
1492        Self {
1493            text: self.text.clone(),
1494            saved_version: self.saved_version.clone(),
1495            saved_mtime: self.saved_mtime,
1496            file: self.file.as_ref().map(|f| f.boxed_clone()),
1497            language: self.language.clone(),
1498            syntax_tree: Mutex::new(self.syntax_tree.lock().clone()),
1499            parsing_in_background: false,
1500            sync_parse_timeout: self.sync_parse_timeout,
1501            parse_count: self.parse_count,
1502            autoindent_requests: Default::default(),
1503            pending_autoindent: Default::default(),
1504            diagnostics: self.diagnostics.clone(),
1505            diagnostics_update_count: self.diagnostics_update_count,
1506            language_server: None,
1507            #[cfg(test)]
1508            operations: self.operations.clone(),
1509        }
1510    }
1511}
1512
1513impl Deref for Buffer {
1514    type Target = TextBuffer;
1515
1516    fn deref(&self) -> &Self::Target {
1517        &self.text
1518    }
1519}
1520
1521impl<'a> From<&'a Buffer> for Content<'a> {
1522    fn from(buffer: &'a Buffer) -> Self {
1523        Self::from(&buffer.text)
1524    }
1525}
1526
1527impl<'a> From<&'a mut Buffer> for Content<'a> {
1528    fn from(buffer: &'a mut Buffer) -> Self {
1529        Self::from(&buffer.text)
1530    }
1531}
1532
1533impl<'a> From<&'a Snapshot> for Content<'a> {
1534    fn from(snapshot: &'a Snapshot) -> Self {
1535        Self::from(&snapshot.text)
1536    }
1537}
1538
1539impl Snapshot {
1540    fn suggest_autoindents<'a>(
1541        &'a self,
1542        row_range: Range<u32>,
1543    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1544        let mut query_cursor = QueryCursorHandle::new();
1545        if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1546            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1547
1548            // Get the "indentation ranges" that intersect this row range.
1549            let indent_capture_ix = language.indents_query.capture_index_for_name("indent");
1550            let end_capture_ix = language.indents_query.capture_index_for_name("end");
1551            query_cursor.set_point_range(
1552                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1553                    ..Point::new(row_range.end, 0).to_ts_point(),
1554            );
1555            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1556            for mat in query_cursor.matches(
1557                &language.indents_query,
1558                tree.root_node(),
1559                TextProvider(self.as_rope()),
1560            ) {
1561                let mut node_kind = "";
1562                let mut start: Option<Point> = None;
1563                let mut end: Option<Point> = None;
1564                for capture in mat.captures {
1565                    if Some(capture.index) == indent_capture_ix {
1566                        node_kind = capture.node.kind();
1567                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1568                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1569                    } else if Some(capture.index) == end_capture_ix {
1570                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1571                    }
1572                }
1573
1574                if let Some((start, end)) = start.zip(end) {
1575                    if start.row == end.row {
1576                        continue;
1577                    }
1578
1579                    let range = start..end;
1580                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1581                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1582                        Ok(ix) => {
1583                            let prev_range = &mut indentation_ranges[ix];
1584                            prev_range.0.end = prev_range.0.end.max(range.end);
1585                        }
1586                    }
1587                }
1588            }
1589
1590            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1591            Some(row_range.map(move |row| {
1592                let row_start = Point::new(row, self.indent_column_for_line(row));
1593
1594                let mut indent_from_prev_row = false;
1595                let mut outdent_to_row = u32::MAX;
1596                for (range, _node_kind) in &indentation_ranges {
1597                    if range.start.row >= row {
1598                        break;
1599                    }
1600
1601                    if range.start.row == prev_row && range.end > row_start {
1602                        indent_from_prev_row = true;
1603                    }
1604                    if range.end.row >= prev_row && range.end <= row_start {
1605                        outdent_to_row = outdent_to_row.min(range.start.row);
1606                    }
1607                }
1608
1609                let suggestion = if outdent_to_row == prev_row {
1610                    IndentSuggestion {
1611                        basis_row: prev_row,
1612                        indent: false,
1613                    }
1614                } else if indent_from_prev_row {
1615                    IndentSuggestion {
1616                        basis_row: prev_row,
1617                        indent: true,
1618                    }
1619                } else if outdent_to_row < prev_row {
1620                    IndentSuggestion {
1621                        basis_row: outdent_to_row,
1622                        indent: false,
1623                    }
1624                } else {
1625                    IndentSuggestion {
1626                        basis_row: prev_row,
1627                        indent: false,
1628                    }
1629                };
1630
1631                prev_row = row;
1632                suggestion
1633            }))
1634        } else {
1635            None
1636        }
1637    }
1638
1639    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1640        while row > 0 {
1641            row -= 1;
1642            if !self.is_line_blank(row) {
1643                return Some(row);
1644            }
1645        }
1646        None
1647    }
1648
1649    fn is_line_blank(&self, row: u32) -> bool {
1650        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1651            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1652    }
1653
1654    pub fn chunks<'a, T: ToOffset>(
1655        &'a self,
1656        range: Range<T>,
1657        theme: Option<&'a SyntaxTheme>,
1658    ) -> Chunks<'a> {
1659        let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1660
1661        let mut highlights = None;
1662        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1663        if let Some(theme) = theme {
1664            for (_, range, diagnostic) in
1665                self.diagnostics
1666                    .intersecting_ranges(range.clone(), self.content(), true)
1667            {
1668                diagnostic_endpoints.push(DiagnosticEndpoint {
1669                    offset: range.start,
1670                    is_start: true,
1671                    severity: diagnostic.severity,
1672                });
1673                diagnostic_endpoints.push(DiagnosticEndpoint {
1674                    offset: range.end,
1675                    is_start: false,
1676                    severity: diagnostic.severity,
1677                });
1678            }
1679            diagnostic_endpoints
1680                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1681
1682            if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1683                let mut query_cursor = QueryCursorHandle::new();
1684
1685                // TODO - add a Tree-sitter API to remove the need for this.
1686                let cursor = unsafe {
1687                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1688                };
1689                let captures = cursor.set_byte_range(range.clone()).captures(
1690                    &language.highlights_query,
1691                    tree.root_node(),
1692                    TextProvider(self.text.as_rope()),
1693                );
1694                highlights = Some(Highlights {
1695                    captures,
1696                    next_capture: None,
1697                    stack: Default::default(),
1698                    highlight_map: language.highlight_map(),
1699                    _query_cursor: query_cursor,
1700                    theme,
1701                })
1702            }
1703        }
1704
1705        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1706        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1707
1708        Chunks {
1709            range,
1710            chunks,
1711            diagnostic_endpoints,
1712            error_depth: 0,
1713            warning_depth: 0,
1714            information_depth: 0,
1715            hint_depth: 0,
1716            highlights,
1717        }
1718    }
1719}
1720
1721impl Clone for Snapshot {
1722    fn clone(&self) -> Self {
1723        Self {
1724            text: self.text.clone(),
1725            tree: self.tree.clone(),
1726            diagnostics: self.diagnostics.clone(),
1727            is_parsing: self.is_parsing,
1728            language: self.language.clone(),
1729        }
1730    }
1731}
1732
1733impl Deref for Snapshot {
1734    type Target = buffer::Snapshot;
1735
1736    fn deref(&self) -> &Self::Target {
1737        &self.text
1738    }
1739}
1740
1741impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1742    type I = ByteChunks<'a>;
1743
1744    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1745        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1746    }
1747}
1748
1749struct ByteChunks<'a>(rope::Chunks<'a>);
1750
1751impl<'a> Iterator for ByteChunks<'a> {
1752    type Item = &'a [u8];
1753
1754    fn next(&mut self) -> Option<Self::Item> {
1755        self.0.next().map(str::as_bytes)
1756    }
1757}
1758
1759unsafe impl<'a> Send for Chunks<'a> {}
1760
1761impl<'a> Chunks<'a> {
1762    pub fn seek(&mut self, offset: usize) {
1763        self.range.start = offset;
1764        self.chunks.seek(self.range.start);
1765        if let Some(highlights) = self.highlights.as_mut() {
1766            highlights
1767                .stack
1768                .retain(|(end_offset, _)| *end_offset > offset);
1769            if let Some((mat, capture_ix)) = &highlights.next_capture {
1770                let capture = mat.captures[*capture_ix as usize];
1771                if offset >= capture.node.start_byte() {
1772                    let next_capture_end = capture.node.end_byte();
1773                    if offset < next_capture_end {
1774                        highlights.stack.push((
1775                            next_capture_end,
1776                            highlights.highlight_map.get(capture.index),
1777                        ));
1778                    }
1779                    highlights.next_capture.take();
1780                }
1781            }
1782            highlights.captures.set_byte_range(self.range.clone());
1783        }
1784    }
1785
1786    pub fn offset(&self) -> usize {
1787        self.range.start
1788    }
1789
1790    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1791        let depth = match endpoint.severity {
1792            DiagnosticSeverity::ERROR => &mut self.error_depth,
1793            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1794            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1795            DiagnosticSeverity::HINT => &mut self.hint_depth,
1796            _ => return,
1797        };
1798        if endpoint.is_start {
1799            *depth += 1;
1800        } else {
1801            *depth -= 1;
1802        }
1803    }
1804
1805    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1806        if self.error_depth > 0 {
1807            Some(DiagnosticSeverity::ERROR)
1808        } else if self.warning_depth > 0 {
1809            Some(DiagnosticSeverity::WARNING)
1810        } else if self.information_depth > 0 {
1811            Some(DiagnosticSeverity::INFORMATION)
1812        } else if self.hint_depth > 0 {
1813            Some(DiagnosticSeverity::HINT)
1814        } else {
1815            None
1816        }
1817    }
1818}
1819
1820impl<'a> Iterator for Chunks<'a> {
1821    type Item = Chunk<'a>;
1822
1823    fn next(&mut self) -> Option<Self::Item> {
1824        let mut next_capture_start = usize::MAX;
1825        let mut next_diagnostic_endpoint = usize::MAX;
1826
1827        if let Some(highlights) = self.highlights.as_mut() {
1828            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1829                if *parent_capture_end <= self.range.start {
1830                    highlights.stack.pop();
1831                } else {
1832                    break;
1833                }
1834            }
1835
1836            if highlights.next_capture.is_none() {
1837                highlights.next_capture = highlights.captures.next();
1838            }
1839
1840            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1841                let capture = mat.captures[*capture_ix as usize];
1842                if self.range.start < capture.node.start_byte() {
1843                    next_capture_start = capture.node.start_byte();
1844                    break;
1845                } else {
1846                    let highlight_id = highlights.highlight_map.get(capture.index);
1847                    highlights
1848                        .stack
1849                        .push((capture.node.end_byte(), highlight_id));
1850                    highlights.next_capture = highlights.captures.next();
1851                }
1852            }
1853        }
1854
1855        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1856            if endpoint.offset <= self.range.start {
1857                self.update_diagnostic_depths(endpoint);
1858                self.diagnostic_endpoints.next();
1859            } else {
1860                next_diagnostic_endpoint = endpoint.offset;
1861                break;
1862            }
1863        }
1864
1865        if let Some(chunk) = self.chunks.peek() {
1866            let chunk_start = self.range.start;
1867            let mut chunk_end = (self.chunks.offset() + chunk.len())
1868                .min(next_capture_start)
1869                .min(next_diagnostic_endpoint);
1870            let mut highlight_style = None;
1871            if let Some(highlights) = self.highlights.as_ref() {
1872                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
1873                    chunk_end = chunk_end.min(*parent_capture_end);
1874                    highlight_style = parent_highlight_id.style(highlights.theme);
1875                }
1876            }
1877
1878            let slice =
1879                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1880            self.range.start = chunk_end;
1881            if self.range.start == self.chunks.offset() + chunk.len() {
1882                self.chunks.next().unwrap();
1883            }
1884
1885            Some(Chunk {
1886                text: slice,
1887                highlight_style,
1888                diagnostic: self.current_diagnostic_severity(),
1889            })
1890        } else {
1891            None
1892        }
1893    }
1894}
1895
1896impl QueryCursorHandle {
1897    fn new() -> Self {
1898        QueryCursorHandle(Some(
1899            QUERY_CURSORS
1900                .lock()
1901                .pop()
1902                .unwrap_or_else(|| QueryCursor::new()),
1903        ))
1904    }
1905}
1906
1907impl Deref for QueryCursorHandle {
1908    type Target = QueryCursor;
1909
1910    fn deref(&self) -> &Self::Target {
1911        self.0.as_ref().unwrap()
1912    }
1913}
1914
1915impl DerefMut for QueryCursorHandle {
1916    fn deref_mut(&mut self) -> &mut Self::Target {
1917        self.0.as_mut().unwrap()
1918    }
1919}
1920
1921impl Drop for QueryCursorHandle {
1922    fn drop(&mut self) {
1923        let mut cursor = self.0.take().unwrap();
1924        cursor.set_byte_range(0..usize::MAX);
1925        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
1926        QUERY_CURSORS.lock().push(cursor)
1927    }
1928}
1929
1930trait ToTreeSitterPoint {
1931    fn to_ts_point(self) -> tree_sitter::Point;
1932    fn from_ts_point(point: tree_sitter::Point) -> Self;
1933}
1934
1935impl ToTreeSitterPoint for Point {
1936    fn to_ts_point(self) -> tree_sitter::Point {
1937        tree_sitter::Point::new(self.row as usize, self.column as usize)
1938    }
1939
1940    fn from_ts_point(point: tree_sitter::Point) -> Self {
1941        Point::new(point.row as u32, point.column as u32)
1942    }
1943}
1944
1945trait ToPointUtf16 {
1946    fn to_point_utf16(self) -> PointUtf16;
1947}
1948
1949impl ToPointUtf16 for lsp::Position {
1950    fn to_point_utf16(self) -> PointUtf16 {
1951        PointUtf16::new(self.line, self.character)
1952    }
1953}
1954
1955fn diagnostic_ranges<'a>(
1956    diagnostic: &'a lsp::Diagnostic,
1957    abs_path: Option<&'a Path>,
1958) -> impl 'a + Iterator<Item = Range<PointUtf16>> {
1959    diagnostic
1960        .related_information
1961        .iter()
1962        .flatten()
1963        .filter_map(move |info| {
1964            if info.location.uri.to_file_path().ok()? == abs_path? {
1965                let info_start = PointUtf16::new(
1966                    info.location.range.start.line,
1967                    info.location.range.start.character,
1968                );
1969                let info_end = PointUtf16::new(
1970                    info.location.range.end.line,
1971                    info.location.range.end.character,
1972                );
1973                Some(info_start..info_end)
1974            } else {
1975                None
1976            }
1977        })
1978        .chain(Some(
1979            diagnostic.range.start.to_point_utf16()..diagnostic.range.end.to_point_utf16(),
1980        ))
1981}
1982
1983fn contiguous_ranges(
1984    values: impl IntoIterator<Item = u32>,
1985    max_len: usize,
1986) -> impl Iterator<Item = Range<u32>> {
1987    let mut values = values.into_iter();
1988    let mut current_range: Option<Range<u32>> = None;
1989    std::iter::from_fn(move || loop {
1990        if let Some(value) = values.next() {
1991            if let Some(range) = &mut current_range {
1992                if value == range.end && range.len() < max_len {
1993                    range.end += 1;
1994                    continue;
1995                }
1996            }
1997
1998            let prev_range = current_range.clone();
1999            current_range = Some(value..(value + 1));
2000            if prev_range.is_some() {
2001                return prev_range;
2002            }
2003        } else {
2004            return current_range.take();
2005        }
2006    })
2007}