buffer.rs

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