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