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