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