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 diagnostic_group<'a, O>(
 816        &'a self,
 817        group_id: usize,
 818    ) -> impl Iterator<Item = (Range<O>, &Diagnostic)> + 'a
 819    where
 820        O: 'a + FromAnchor,
 821    {
 822        let content = self.content();
 823        self.diagnostics
 824            .filter(content, move |diagnostic| diagnostic.group_id == group_id)
 825            .map(move |(_, range, diagnostic)| (range, diagnostic))
 826    }
 827
 828    pub fn diagnostics_update_count(&self) -> usize {
 829        self.diagnostics_update_count
 830    }
 831
 832    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 833        if let Some(indent_columns) = self.compute_autoindents() {
 834            let indent_columns = cx.background().spawn(indent_columns);
 835            match cx
 836                .background()
 837                .block_with_timeout(Duration::from_micros(500), indent_columns)
 838            {
 839                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 840                Err(indent_columns) => {
 841                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 842                        let indent_columns = indent_columns.await;
 843                        this.update(&mut cx, |this, cx| {
 844                            this.apply_autoindents(indent_columns, cx);
 845                        });
 846                    }));
 847                }
 848            }
 849        }
 850    }
 851
 852    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 853        let max_rows_between_yields = 100;
 854        let snapshot = self.snapshot();
 855        if snapshot.language.is_none()
 856            || snapshot.tree.is_none()
 857            || self.autoindent_requests.is_empty()
 858        {
 859            return None;
 860        }
 861
 862        let autoindent_requests = self.autoindent_requests.clone();
 863        Some(async move {
 864            let mut indent_columns = BTreeMap::new();
 865            for request in autoindent_requests {
 866                let old_to_new_rows = request
 867                    .edited
 868                    .iter::<Point, _>(&request.before_edit)
 869                    .map(|point| point.row)
 870                    .zip(
 871                        request
 872                            .edited
 873                            .iter::<Point, _>(&snapshot)
 874                            .map(|point| point.row),
 875                    )
 876                    .collect::<BTreeMap<u32, u32>>();
 877
 878                let mut old_suggestions = HashMap::<u32, u32>::default();
 879                let old_edited_ranges =
 880                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 881                for old_edited_range in old_edited_ranges {
 882                    let suggestions = request
 883                        .before_edit
 884                        .suggest_autoindents(old_edited_range.clone())
 885                        .into_iter()
 886                        .flatten();
 887                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 888                        let indentation_basis = old_to_new_rows
 889                            .get(&suggestion.basis_row)
 890                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 891                            .unwrap_or_else(|| {
 892                                request
 893                                    .before_edit
 894                                    .indent_column_for_line(suggestion.basis_row)
 895                            });
 896                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 897                        old_suggestions.insert(
 898                            *old_to_new_rows.get(&old_row).unwrap(),
 899                            indentation_basis + delta,
 900                        );
 901                    }
 902                    yield_now().await;
 903                }
 904
 905                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 906                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 907                let new_edited_row_ranges =
 908                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 909                for new_edited_row_range in new_edited_row_ranges {
 910                    let suggestions = snapshot
 911                        .suggest_autoindents(new_edited_row_range.clone())
 912                        .into_iter()
 913                        .flatten();
 914                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 915                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 916                        let new_indentation = indent_columns
 917                            .get(&suggestion.basis_row)
 918                            .copied()
 919                            .unwrap_or_else(|| {
 920                                snapshot.indent_column_for_line(suggestion.basis_row)
 921                            })
 922                            + delta;
 923                        if old_suggestions
 924                            .get(&new_row)
 925                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 926                        {
 927                            indent_columns.insert(new_row, new_indentation);
 928                        }
 929                    }
 930                    yield_now().await;
 931                }
 932
 933                if let Some(inserted) = request.inserted.as_ref() {
 934                    let inserted_row_ranges = contiguous_ranges(
 935                        inserted
 936                            .ranges::<Point, _>(&snapshot)
 937                            .flat_map(|range| range.start.row..range.end.row + 1),
 938                        max_rows_between_yields,
 939                    );
 940                    for inserted_row_range in inserted_row_ranges {
 941                        let suggestions = snapshot
 942                            .suggest_autoindents(inserted_row_range.clone())
 943                            .into_iter()
 944                            .flatten();
 945                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
 946                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 947                            let new_indentation = indent_columns
 948                                .get(&suggestion.basis_row)
 949                                .copied()
 950                                .unwrap_or_else(|| {
 951                                    snapshot.indent_column_for_line(suggestion.basis_row)
 952                                })
 953                                + delta;
 954                            indent_columns.insert(row, new_indentation);
 955                        }
 956                        yield_now().await;
 957                    }
 958                }
 959            }
 960            indent_columns
 961        })
 962    }
 963
 964    fn apply_autoindents(
 965        &mut self,
 966        indent_columns: BTreeMap<u32, u32>,
 967        cx: &mut ModelContext<Self>,
 968    ) {
 969        let selection_set_ids = self
 970            .autoindent_requests
 971            .drain(..)
 972            .flat_map(|req| req.selection_set_ids.clone())
 973            .collect::<HashSet<_>>();
 974
 975        self.start_transaction(selection_set_ids.iter().copied())
 976            .unwrap();
 977        for (row, indent_column) in &indent_columns {
 978            self.set_indent_column_for_line(*row, *indent_column, cx);
 979        }
 980
 981        for selection_set_id in &selection_set_ids {
 982            if let Ok(set) = self.selection_set(*selection_set_id) {
 983                let new_selections = set
 984                    .selections::<Point, _>(&*self)
 985                    .map(|selection| {
 986                        if selection.start.column == 0 {
 987                            let delta = Point::new(
 988                                0,
 989                                indent_columns
 990                                    .get(&selection.start.row)
 991                                    .copied()
 992                                    .unwrap_or(0),
 993                            );
 994                            if delta.column > 0 {
 995                                return Selection {
 996                                    id: selection.id,
 997                                    goal: selection.goal,
 998                                    reversed: selection.reversed,
 999                                    start: selection.start + delta,
1000                                    end: selection.end + delta,
1001                                };
1002                            }
1003                        }
1004                        selection
1005                    })
1006                    .collect::<Vec<_>>();
1007                self.update_selection_set(*selection_set_id, &new_selections, cx)
1008                    .unwrap();
1009            }
1010        }
1011
1012        self.end_transaction(selection_set_ids.iter().copied(), cx)
1013            .unwrap();
1014    }
1015
1016    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1017        self.content().indent_column_for_line(row)
1018    }
1019
1020    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1021        let current_column = self.indent_column_for_line(row);
1022        if column > current_column {
1023            let offset = Point::new(row, 0).to_offset(&*self);
1024            self.edit(
1025                [offset..offset],
1026                " ".repeat((column - current_column) as usize),
1027                cx,
1028            );
1029        } else if column < current_column {
1030            self.edit(
1031                [Point::new(row, 0)..Point::new(row, current_column - column)],
1032                "",
1033                cx,
1034            );
1035        }
1036    }
1037
1038    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1039        if let Some(tree) = self.syntax_tree() {
1040            let root = tree.root_node();
1041            let range = range.start.to_offset(self)..range.end.to_offset(self);
1042            let mut node = root.descendant_for_byte_range(range.start, range.end);
1043            while node.map_or(false, |n| n.byte_range() == range) {
1044                node = node.unwrap().parent();
1045            }
1046            node.map(|n| n.byte_range())
1047        } else {
1048            None
1049        }
1050    }
1051
1052    pub fn enclosing_bracket_ranges<T: ToOffset>(
1053        &self,
1054        range: Range<T>,
1055    ) -> Option<(Range<usize>, Range<usize>)> {
1056        let (lang, tree) = self.language.as_ref().zip(self.syntax_tree())?;
1057        let open_capture_ix = lang.brackets_query.capture_index_for_name("open")?;
1058        let close_capture_ix = lang.brackets_query.capture_index_for_name("close")?;
1059
1060        // Find bracket pairs that *inclusively* contain the given range.
1061        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1062        let mut cursor = QueryCursorHandle::new();
1063        let matches = cursor.set_byte_range(range).matches(
1064            &lang.brackets_query,
1065            tree.root_node(),
1066            TextProvider(self.as_rope()),
1067        );
1068
1069        // Get the ranges of the innermost pair of brackets.
1070        matches
1071            .filter_map(|mat| {
1072                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1073                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1074                Some((open.byte_range(), close.byte_range()))
1075            })
1076            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1077    }
1078
1079    fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1080        // TODO: it would be nice to not allocate here.
1081        let old_text = self.text();
1082        let base_version = self.version();
1083        cx.background().spawn(async move {
1084            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1085                .iter_all_changes()
1086                .map(|c| (c.tag(), c.value().len()))
1087                .collect::<Vec<_>>();
1088            Diff {
1089                base_version,
1090                new_text,
1091                changes,
1092            }
1093        })
1094    }
1095
1096    fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1097        if self.version == diff.base_version {
1098            self.start_transaction(None).unwrap();
1099            let mut offset = 0;
1100            for (tag, len) in diff.changes {
1101                let range = offset..(offset + len);
1102                match tag {
1103                    ChangeTag::Equal => offset += len,
1104                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1105                    ChangeTag::Insert => {
1106                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1107                        offset += len;
1108                    }
1109                }
1110            }
1111            self.end_transaction(None, cx).unwrap();
1112            true
1113        } else {
1114            false
1115        }
1116    }
1117
1118    pub fn is_dirty(&self) -> bool {
1119        self.version > self.saved_version
1120            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1121    }
1122
1123    pub fn has_conflict(&self) -> bool {
1124        self.version > self.saved_version
1125            && self
1126                .file
1127                .as_ref()
1128                .map_or(false, |file| file.mtime() > self.saved_mtime)
1129    }
1130
1131    pub fn start_transaction(
1132        &mut self,
1133        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1134    ) -> Result<()> {
1135        self.start_transaction_at(selection_set_ids, Instant::now())
1136    }
1137
1138    fn start_transaction_at(
1139        &mut self,
1140        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1141        now: Instant,
1142    ) -> Result<()> {
1143        self.text.start_transaction_at(selection_set_ids, now)
1144    }
1145
1146    pub fn end_transaction(
1147        &mut self,
1148        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1149        cx: &mut ModelContext<Self>,
1150    ) -> Result<()> {
1151        self.end_transaction_at(selection_set_ids, Instant::now(), cx)
1152    }
1153
1154    fn end_transaction_at(
1155        &mut self,
1156        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1157        now: Instant,
1158        cx: &mut ModelContext<Self>,
1159    ) -> Result<()> {
1160        if let Some(start_version) = self.text.end_transaction_at(selection_set_ids, now) {
1161            let was_dirty = start_version != self.saved_version;
1162            self.did_edit(&start_version, was_dirty, cx);
1163        }
1164        Ok(())
1165    }
1166
1167    fn update_language_server(&mut self) {
1168        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1169            language_server
1170        } else {
1171            return;
1172        };
1173        let abs_path = self
1174            .file
1175            .as_ref()
1176            .map_or(Path::new("/").to_path_buf(), |file| {
1177                file.abs_path().unwrap()
1178            });
1179
1180        let version = post_inc(&mut language_server.next_version);
1181        let snapshot = LanguageServerSnapshot {
1182            buffer_snapshot: self.text.snapshot(),
1183            version,
1184            path: Arc::from(abs_path),
1185        };
1186        language_server
1187            .pending_snapshots
1188            .insert(version, snapshot.clone());
1189        let _ = language_server
1190            .latest_snapshot
1191            .blocking_send(Some(snapshot));
1192    }
1193
1194    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, 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, false, cx)
1201    }
1202
1203    pub fn edit_with_autoindent<I, S, T>(
1204        &mut self,
1205        ranges_iter: I,
1206        new_text: T,
1207        cx: &mut ModelContext<Self>,
1208    ) where
1209        I: IntoIterator<Item = Range<S>>,
1210        S: ToOffset,
1211        T: Into<String>,
1212    {
1213        self.edit_internal(ranges_iter, new_text, true, cx)
1214    }
1215
1216    pub fn edit_internal<I, S, T>(
1217        &mut self,
1218        ranges_iter: I,
1219        new_text: T,
1220        autoindent: bool,
1221        cx: &mut ModelContext<Self>,
1222    ) where
1223        I: IntoIterator<Item = Range<S>>,
1224        S: ToOffset,
1225        T: Into<String>,
1226    {
1227        let new_text = new_text.into();
1228
1229        // Skip invalid ranges and coalesce contiguous ones.
1230        let mut ranges: Vec<Range<usize>> = Vec::new();
1231        for range in ranges_iter {
1232            let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1233            if !new_text.is_empty() || !range.is_empty() {
1234                if let Some(prev_range) = ranges.last_mut() {
1235                    if prev_range.end >= range.start {
1236                        prev_range.end = cmp::max(prev_range.end, range.end);
1237                    } else {
1238                        ranges.push(range);
1239                    }
1240                } else {
1241                    ranges.push(range);
1242                }
1243            }
1244        }
1245        if ranges.is_empty() {
1246            return;
1247        }
1248
1249        self.start_transaction(None).unwrap();
1250        self.pending_autoindent.take();
1251        let autoindent_request = if autoindent && self.language.is_some() {
1252            let before_edit = self.snapshot();
1253            let edited = self.content().anchor_set(ranges.iter().filter_map(|range| {
1254                let start = range.start.to_point(&*self);
1255                if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1256                    None
1257                } else {
1258                    Some((range.start, Bias::Left))
1259                }
1260            }));
1261            Some((before_edit, edited))
1262        } else {
1263            None
1264        };
1265
1266        let first_newline_ix = new_text.find('\n');
1267        let new_text_len = new_text.len();
1268
1269        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1270
1271        if let Some((before_edit, edited)) = autoindent_request {
1272            let mut inserted = None;
1273            if let Some(first_newline_ix) = first_newline_ix {
1274                let mut delta = 0isize;
1275                inserted = Some(self.content().anchor_range_set(ranges.iter().map(|range| {
1276                    let start = (delta + range.start as isize) as usize + first_newline_ix + 1;
1277                    let end = (delta + range.start as isize) as usize + new_text_len;
1278                    delta += (range.end as isize - range.start as isize) + new_text_len as isize;
1279                    (start, Bias::Left)..(end, Bias::Right)
1280                })));
1281            }
1282
1283            let selection_set_ids = self
1284                .text
1285                .peek_undo_stack()
1286                .unwrap()
1287                .starting_selection_set_ids()
1288                .collect();
1289            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1290                selection_set_ids,
1291                before_edit,
1292                edited,
1293                inserted,
1294            }));
1295        }
1296
1297        self.end_transaction(None, cx).unwrap();
1298        self.send_operation(Operation::Buffer(buffer::Operation::Edit(edit)), cx);
1299    }
1300
1301    fn did_edit(
1302        &mut self,
1303        old_version: &clock::Global,
1304        was_dirty: bool,
1305        cx: &mut ModelContext<Self>,
1306    ) {
1307        if self.edits_since::<usize>(old_version).next().is_none() {
1308            return;
1309        }
1310
1311        self.reparse(cx);
1312        self.update_language_server();
1313
1314        cx.emit(Event::Edited);
1315        if !was_dirty {
1316            cx.emit(Event::Dirtied);
1317        }
1318        cx.notify();
1319    }
1320
1321    pub fn add_selection_set<T: ToOffset>(
1322        &mut self,
1323        selections: &[Selection<T>],
1324        cx: &mut ModelContext<Self>,
1325    ) -> SelectionSetId {
1326        let operation = self.text.add_selection_set(selections);
1327        if let buffer::Operation::UpdateSelections { set_id, .. } = &operation {
1328            let set_id = *set_id;
1329            cx.notify();
1330            self.send_operation(Operation::Buffer(operation), cx);
1331            set_id
1332        } else {
1333            unreachable!()
1334        }
1335    }
1336
1337    pub fn update_selection_set<T: ToOffset>(
1338        &mut self,
1339        set_id: SelectionSetId,
1340        selections: &[Selection<T>],
1341        cx: &mut ModelContext<Self>,
1342    ) -> Result<()> {
1343        let operation = self.text.update_selection_set(set_id, selections)?;
1344        cx.notify();
1345        self.send_operation(Operation::Buffer(operation), cx);
1346        Ok(())
1347    }
1348
1349    pub fn set_active_selection_set(
1350        &mut self,
1351        set_id: Option<SelectionSetId>,
1352        cx: &mut ModelContext<Self>,
1353    ) -> Result<()> {
1354        let operation = self.text.set_active_selection_set(set_id)?;
1355        self.send_operation(Operation::Buffer(operation), cx);
1356        Ok(())
1357    }
1358
1359    pub fn remove_selection_set(
1360        &mut self,
1361        set_id: SelectionSetId,
1362        cx: &mut ModelContext<Self>,
1363    ) -> Result<()> {
1364        let operation = self.text.remove_selection_set(set_id)?;
1365        cx.notify();
1366        self.send_operation(Operation::Buffer(operation), cx);
1367        Ok(())
1368    }
1369
1370    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1371        &mut self,
1372        ops: I,
1373        cx: &mut ModelContext<Self>,
1374    ) -> Result<()> {
1375        self.pending_autoindent.take();
1376        let was_dirty = self.is_dirty();
1377        let old_version = self.version.clone();
1378        let buffer_ops = ops
1379            .into_iter()
1380            .filter_map(|op| match op {
1381                Operation::Buffer(op) => Some(op),
1382                Operation::UpdateDiagnostics(diagnostics) => {
1383                    self.apply_diagnostic_update(diagnostics, cx);
1384                    None
1385                }
1386            })
1387            .collect::<Vec<_>>();
1388        self.text.apply_ops(buffer_ops)?;
1389        self.did_edit(&old_version, was_dirty, cx);
1390        // Notify independently of whether the buffer was edited as the operations could include a
1391        // selection update.
1392        cx.notify();
1393        Ok(())
1394    }
1395
1396    fn apply_diagnostic_update(
1397        &mut self,
1398        diagnostics: AnchorRangeMultimap<Diagnostic>,
1399        cx: &mut ModelContext<Self>,
1400    ) {
1401        self.diagnostics = diagnostics;
1402        self.diagnostics_update_count += 1;
1403        cx.notify();
1404    }
1405
1406    #[cfg(not(test))]
1407    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1408        if let Some(file) = &self.file {
1409            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1410        }
1411    }
1412
1413    #[cfg(test)]
1414    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1415        self.operations.push(operation);
1416    }
1417
1418    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1419        self.text.remove_peer(replica_id);
1420        cx.notify();
1421    }
1422
1423    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
1424        let was_dirty = self.is_dirty();
1425        let old_version = self.version.clone();
1426
1427        for operation in self.text.undo() {
1428            self.send_operation(Operation::Buffer(operation), cx);
1429        }
1430
1431        self.did_edit(&old_version, was_dirty, cx);
1432    }
1433
1434    pub fn redo(&mut self, cx: &mut ModelContext<Self>) {
1435        let was_dirty = self.is_dirty();
1436        let old_version = self.version.clone();
1437
1438        for operation in self.text.redo() {
1439            self.send_operation(Operation::Buffer(operation), cx);
1440        }
1441
1442        self.did_edit(&old_version, was_dirty, cx);
1443    }
1444}
1445
1446#[cfg(any(test, feature = "test-support"))]
1447impl Buffer {
1448    pub fn randomly_edit<T>(&mut self, rng: &mut T, old_range_count: usize)
1449    where
1450        T: rand::Rng,
1451    {
1452        self.text.randomly_edit(rng, old_range_count);
1453    }
1454
1455    pub fn randomly_mutate<T>(&mut self, rng: &mut T)
1456    where
1457        T: rand::Rng,
1458    {
1459        self.text.randomly_mutate(rng);
1460    }
1461}
1462
1463impl Entity for Buffer {
1464    type Event = Event;
1465
1466    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1467        if let Some(file) = self.file.as_ref() {
1468            file.buffer_removed(self.remote_id(), cx);
1469        }
1470    }
1471}
1472
1473// TODO: Do we need to clone a buffer?
1474impl Clone for Buffer {
1475    fn clone(&self) -> Self {
1476        Self {
1477            text: self.text.clone(),
1478            saved_version: self.saved_version.clone(),
1479            saved_mtime: self.saved_mtime,
1480            file: self.file.as_ref().map(|f| f.boxed_clone()),
1481            language: self.language.clone(),
1482            syntax_tree: Mutex::new(self.syntax_tree.lock().clone()),
1483            parsing_in_background: false,
1484            sync_parse_timeout: self.sync_parse_timeout,
1485            parse_count: self.parse_count,
1486            autoindent_requests: Default::default(),
1487            pending_autoindent: Default::default(),
1488            diagnostics: self.diagnostics.clone(),
1489            diagnostics_update_count: self.diagnostics_update_count,
1490            language_server: None,
1491            #[cfg(test)]
1492            operations: self.operations.clone(),
1493        }
1494    }
1495}
1496
1497impl Deref for Buffer {
1498    type Target = TextBuffer;
1499
1500    fn deref(&self) -> &Self::Target {
1501        &self.text
1502    }
1503}
1504
1505impl<'a> From<&'a Buffer> for Content<'a> {
1506    fn from(buffer: &'a Buffer) -> Self {
1507        Self::from(&buffer.text)
1508    }
1509}
1510
1511impl<'a> From<&'a mut Buffer> for Content<'a> {
1512    fn from(buffer: &'a mut Buffer) -> Self {
1513        Self::from(&buffer.text)
1514    }
1515}
1516
1517impl<'a> From<&'a Snapshot> for Content<'a> {
1518    fn from(snapshot: &'a Snapshot) -> Self {
1519        Self::from(&snapshot.text)
1520    }
1521}
1522
1523impl Snapshot {
1524    fn suggest_autoindents<'a>(
1525        &'a self,
1526        row_range: Range<u32>,
1527    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1528        let mut query_cursor = QueryCursorHandle::new();
1529        if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1530            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1531
1532            // Get the "indentation ranges" that intersect this row range.
1533            let indent_capture_ix = language.indents_query.capture_index_for_name("indent");
1534            let end_capture_ix = language.indents_query.capture_index_for_name("end");
1535            query_cursor.set_point_range(
1536                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1537                    ..Point::new(row_range.end, 0).to_ts_point(),
1538            );
1539            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1540            for mat in query_cursor.matches(
1541                &language.indents_query,
1542                tree.root_node(),
1543                TextProvider(self.as_rope()),
1544            ) {
1545                let mut node_kind = "";
1546                let mut start: Option<Point> = None;
1547                let mut end: Option<Point> = None;
1548                for capture in mat.captures {
1549                    if Some(capture.index) == indent_capture_ix {
1550                        node_kind = capture.node.kind();
1551                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1552                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1553                    } else if Some(capture.index) == end_capture_ix {
1554                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1555                    }
1556                }
1557
1558                if let Some((start, end)) = start.zip(end) {
1559                    if start.row == end.row {
1560                        continue;
1561                    }
1562
1563                    let range = start..end;
1564                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1565                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1566                        Ok(ix) => {
1567                            let prev_range = &mut indentation_ranges[ix];
1568                            prev_range.0.end = prev_range.0.end.max(range.end);
1569                        }
1570                    }
1571                }
1572            }
1573
1574            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1575            Some(row_range.map(move |row| {
1576                let row_start = Point::new(row, self.indent_column_for_line(row));
1577
1578                let mut indent_from_prev_row = false;
1579                let mut outdent_to_row = u32::MAX;
1580                for (range, _node_kind) in &indentation_ranges {
1581                    if range.start.row >= row {
1582                        break;
1583                    }
1584
1585                    if range.start.row == prev_row && range.end > row_start {
1586                        indent_from_prev_row = true;
1587                    }
1588                    if range.end.row >= prev_row && range.end <= row_start {
1589                        outdent_to_row = outdent_to_row.min(range.start.row);
1590                    }
1591                }
1592
1593                let suggestion = if outdent_to_row == prev_row {
1594                    IndentSuggestion {
1595                        basis_row: prev_row,
1596                        indent: false,
1597                    }
1598                } else if indent_from_prev_row {
1599                    IndentSuggestion {
1600                        basis_row: prev_row,
1601                        indent: true,
1602                    }
1603                } else if outdent_to_row < prev_row {
1604                    IndentSuggestion {
1605                        basis_row: outdent_to_row,
1606                        indent: false,
1607                    }
1608                } else {
1609                    IndentSuggestion {
1610                        basis_row: prev_row,
1611                        indent: false,
1612                    }
1613                };
1614
1615                prev_row = row;
1616                suggestion
1617            }))
1618        } else {
1619            None
1620        }
1621    }
1622
1623    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1624        while row > 0 {
1625            row -= 1;
1626            if !self.is_line_blank(row) {
1627                return Some(row);
1628            }
1629        }
1630        None
1631    }
1632
1633    fn is_line_blank(&self, row: u32) -> bool {
1634        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1635            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1636    }
1637
1638    pub fn highlighted_text_for_range<T: ToOffset>(
1639        &mut self,
1640        range: Range<T>,
1641    ) -> HighlightedChunks {
1642        let range = range.start.to_offset(&*self)..range.end.to_offset(&*self);
1643
1644        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1645        for (_, range, diagnostic) in
1646            self.diagnostics
1647                .intersecting_ranges(range.clone(), self.content(), true)
1648        {
1649            diagnostic_endpoints.push(DiagnosticEndpoint {
1650                offset: range.start,
1651                is_start: true,
1652                severity: diagnostic.severity,
1653            });
1654            diagnostic_endpoints.push(DiagnosticEndpoint {
1655                offset: range.end,
1656                is_start: false,
1657                severity: diagnostic.severity,
1658            });
1659        }
1660        diagnostic_endpoints.sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1661        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1662
1663        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1664        let highlights =
1665            if let Some((language, tree)) = self.language.as_ref().zip(self.tree.as_ref()) {
1666                let captures = self.query_cursor.set_byte_range(range.clone()).captures(
1667                    &language.highlights_query,
1668                    tree.root_node(),
1669                    TextProvider(self.text.as_rope()),
1670                );
1671
1672                Some(Highlights {
1673                    captures,
1674                    next_capture: None,
1675                    stack: Default::default(),
1676                    highlight_map: language.highlight_map(),
1677                })
1678            } else {
1679                None
1680            };
1681
1682        HighlightedChunks {
1683            range,
1684            chunks,
1685            diagnostic_endpoints,
1686            error_depth: 0,
1687            warning_depth: 0,
1688            information_depth: 0,
1689            hint_depth: 0,
1690            highlights,
1691        }
1692    }
1693}
1694
1695impl Clone for Snapshot {
1696    fn clone(&self) -> Self {
1697        Self {
1698            text: self.text.clone(),
1699            tree: self.tree.clone(),
1700            diagnostics: self.diagnostics.clone(),
1701            is_parsing: self.is_parsing,
1702            language: self.language.clone(),
1703            query_cursor: QueryCursorHandle::new(),
1704        }
1705    }
1706}
1707
1708impl Deref for Snapshot {
1709    type Target = buffer::Snapshot;
1710
1711    fn deref(&self) -> &Self::Target {
1712        &self.text
1713    }
1714}
1715
1716impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1717    type I = ByteChunks<'a>;
1718
1719    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1720        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1721    }
1722}
1723
1724struct ByteChunks<'a>(rope::Chunks<'a>);
1725
1726impl<'a> Iterator for ByteChunks<'a> {
1727    type Item = &'a [u8];
1728
1729    fn next(&mut self) -> Option<Self::Item> {
1730        self.0.next().map(str::as_bytes)
1731    }
1732}
1733
1734impl<'a> HighlightedChunks<'a> {
1735    pub fn seek(&mut self, offset: usize) {
1736        self.range.start = offset;
1737        self.chunks.seek(self.range.start);
1738        if let Some(highlights) = self.highlights.as_mut() {
1739            highlights
1740                .stack
1741                .retain(|(end_offset, _)| *end_offset > offset);
1742            if let Some((mat, capture_ix)) = &highlights.next_capture {
1743                let capture = mat.captures[*capture_ix as usize];
1744                if offset >= capture.node.start_byte() {
1745                    let next_capture_end = capture.node.end_byte();
1746                    if offset < next_capture_end {
1747                        highlights.stack.push((
1748                            next_capture_end,
1749                            highlights.highlight_map.get(capture.index),
1750                        ));
1751                    }
1752                    highlights.next_capture.take();
1753                }
1754            }
1755            highlights.captures.set_byte_range(self.range.clone());
1756        }
1757    }
1758
1759    pub fn offset(&self) -> usize {
1760        self.range.start
1761    }
1762
1763    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1764        let depth = match endpoint.severity {
1765            DiagnosticSeverity::ERROR => &mut self.error_depth,
1766            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1767            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1768            DiagnosticSeverity::HINT => &mut self.hint_depth,
1769            _ => return,
1770        };
1771        if endpoint.is_start {
1772            *depth += 1;
1773        } else {
1774            *depth -= 1;
1775        }
1776    }
1777
1778    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1779        if self.error_depth > 0 {
1780            Some(DiagnosticSeverity::ERROR)
1781        } else if self.warning_depth > 0 {
1782            Some(DiagnosticSeverity::WARNING)
1783        } else if self.information_depth > 0 {
1784            Some(DiagnosticSeverity::INFORMATION)
1785        } else if self.hint_depth > 0 {
1786            Some(DiagnosticSeverity::HINT)
1787        } else {
1788            None
1789        }
1790    }
1791}
1792
1793impl<'a> Iterator for HighlightedChunks<'a> {
1794    type Item = HighlightedChunk<'a>;
1795
1796    fn next(&mut self) -> Option<Self::Item> {
1797        let mut next_capture_start = usize::MAX;
1798        let mut next_diagnostic_endpoint = usize::MAX;
1799
1800        if let Some(highlights) = self.highlights.as_mut() {
1801            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1802                if *parent_capture_end <= self.range.start {
1803                    highlights.stack.pop();
1804                } else {
1805                    break;
1806                }
1807            }
1808
1809            if highlights.next_capture.is_none() {
1810                highlights.next_capture = highlights.captures.next();
1811            }
1812
1813            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1814                let capture = mat.captures[*capture_ix as usize];
1815                if self.range.start < capture.node.start_byte() {
1816                    next_capture_start = capture.node.start_byte();
1817                    break;
1818                } else {
1819                    let highlight_id = highlights.highlight_map.get(capture.index);
1820                    highlights
1821                        .stack
1822                        .push((capture.node.end_byte(), highlight_id));
1823                    highlights.next_capture = highlights.captures.next();
1824                }
1825            }
1826        }
1827
1828        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1829            if endpoint.offset <= self.range.start {
1830                self.update_diagnostic_depths(endpoint);
1831                self.diagnostic_endpoints.next();
1832            } else {
1833                next_diagnostic_endpoint = endpoint.offset;
1834                break;
1835            }
1836        }
1837
1838        if let Some(chunk) = self.chunks.peek() {
1839            let chunk_start = self.range.start;
1840            let mut chunk_end = (self.chunks.offset() + chunk.len())
1841                .min(next_capture_start)
1842                .min(next_diagnostic_endpoint);
1843            let mut highlight_id = HighlightId::default();
1844            if let Some((parent_capture_end, parent_highlight_id)) =
1845                self.highlights.as_ref().and_then(|h| h.stack.last())
1846            {
1847                chunk_end = chunk_end.min(*parent_capture_end);
1848                highlight_id = *parent_highlight_id;
1849            }
1850
1851            let slice =
1852                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1853            self.range.start = chunk_end;
1854            if self.range.start == self.chunks.offset() + chunk.len() {
1855                self.chunks.next().unwrap();
1856            }
1857
1858            Some(HighlightedChunk {
1859                text: slice,
1860                highlight_id,
1861                diagnostic: self.current_diagnostic_severity(),
1862            })
1863        } else {
1864            None
1865        }
1866    }
1867}
1868
1869impl QueryCursorHandle {
1870    fn new() -> Self {
1871        QueryCursorHandle(Some(
1872            QUERY_CURSORS
1873                .lock()
1874                .pop()
1875                .unwrap_or_else(|| QueryCursor::new()),
1876        ))
1877    }
1878}
1879
1880impl Deref for QueryCursorHandle {
1881    type Target = QueryCursor;
1882
1883    fn deref(&self) -> &Self::Target {
1884        self.0.as_ref().unwrap()
1885    }
1886}
1887
1888impl DerefMut for QueryCursorHandle {
1889    fn deref_mut(&mut self) -> &mut Self::Target {
1890        self.0.as_mut().unwrap()
1891    }
1892}
1893
1894impl Drop for QueryCursorHandle {
1895    fn drop(&mut self) {
1896        let mut cursor = self.0.take().unwrap();
1897        cursor.set_byte_range(0..usize::MAX);
1898        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
1899        QUERY_CURSORS.lock().push(cursor)
1900    }
1901}
1902
1903trait ToTreeSitterPoint {
1904    fn to_ts_point(self) -> tree_sitter::Point;
1905    fn from_ts_point(point: tree_sitter::Point) -> Self;
1906}
1907
1908impl ToTreeSitterPoint for Point {
1909    fn to_ts_point(self) -> tree_sitter::Point {
1910        tree_sitter::Point::new(self.row as usize, self.column as usize)
1911    }
1912
1913    fn from_ts_point(point: tree_sitter::Point) -> Self {
1914        Point::new(point.row as u32, point.column as u32)
1915    }
1916}
1917
1918trait ToPointUtf16 {
1919    fn to_point_utf16(self) -> PointUtf16;
1920}
1921
1922impl ToPointUtf16 for lsp::Position {
1923    fn to_point_utf16(self) -> PointUtf16 {
1924        PointUtf16::new(self.line, self.character)
1925    }
1926}
1927
1928fn diagnostic_ranges<'a>(
1929    diagnostic: &'a lsp::Diagnostic,
1930    abs_path: Option<&'a Path>,
1931) -> impl 'a + Iterator<Item = Range<PointUtf16>> {
1932    diagnostic
1933        .related_information
1934        .iter()
1935        .flatten()
1936        .filter_map(move |info| {
1937            if info.location.uri.to_file_path().ok()? == abs_path? {
1938                let info_start = PointUtf16::new(
1939                    info.location.range.start.line,
1940                    info.location.range.start.character,
1941                );
1942                let info_end = PointUtf16::new(
1943                    info.location.range.end.line,
1944                    info.location.range.end.character,
1945                );
1946                Some(info_start..info_end)
1947            } else {
1948                None
1949            }
1950        })
1951        .chain(Some(
1952            diagnostic.range.start.to_point_utf16()..diagnostic.range.end.to_point_utf16(),
1953        ))
1954}
1955
1956fn contiguous_ranges(
1957    values: impl IntoIterator<Item = u32>,
1958    max_len: usize,
1959) -> impl Iterator<Item = Range<u32>> {
1960    let mut values = values.into_iter();
1961    let mut current_range: Option<Range<u32>> = None;
1962    std::iter::from_fn(move || loop {
1963        if let Some(value) = values.next() {
1964            if let Some(range) = &mut current_range {
1965                if value == range.end && range.len() < max_len {
1966                    range.end += 1;
1967                    continue;
1968                }
1969            }
1970
1971            let prev_range = current_range.clone();
1972            current_range = Some(value..(value + 1));
1973            if prev_range.is_some() {
1974                return prev_range;
1975            }
1976        } else {
1977            return current_range.take();
1978        }
1979    })
1980}