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