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