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