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, HashSet},
  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 source: Option<String>,
  91    pub code: Option<String>,
  92    pub severity: DiagnosticSeverity,
  93    pub message: String,
  94    pub group_id: usize,
  95    pub is_valid: bool,
  96    pub is_primary: 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.source.cmp(&b.source))
 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 empty_set = HashSet::new();
 764        let disk_based_sources = self
 765            .language
 766            .as_ref()
 767            .and_then(|language| language.disk_based_diagnostic_sources())
 768            .unwrap_or(&empty_set);
 769
 770        let mut edits_since_save = content
 771            .edits_since::<PointUtf16>(&self.saved_version)
 772            .peekable();
 773        let mut last_edit_old_end = PointUtf16::zero();
 774        let mut last_edit_new_end = PointUtf16::zero();
 775        let mut ix = 0;
 776        'outer: while ix < diagnostics.len() {
 777            let entry = &mut diagnostics[ix];
 778            let mut start = entry.range.start;
 779            let mut end = entry.range.end;
 780
 781            // Some diagnostics are based on files on disk instead of buffers'
 782            // current contents. Adjust these diagnostics' ranges to reflect
 783            // any unsaved edits.
 784            if entry
 785                .diagnostic
 786                .source
 787                .as_ref()
 788                .map_or(false, |source| disk_based_sources.contains(source))
 789            {
 790                while let Some(edit) = edits_since_save.peek() {
 791                    if edit.old.end <= start {
 792                        last_edit_old_end = edit.old.end;
 793                        last_edit_new_end = edit.new.end;
 794                        edits_since_save.next();
 795                    } else if edit.old.start <= end && edit.old.end >= start {
 796                        diagnostics.remove(ix);
 797                        continue 'outer;
 798                    } else {
 799                        break;
 800                    }
 801                }
 802
 803                start = last_edit_new_end + (start - last_edit_old_end);
 804                end = last_edit_new_end + (end - last_edit_old_end);
 805            }
 806
 807            entry.range = content.clip_point_utf16(start, Bias::Left)
 808                ..content.clip_point_utf16(end, Bias::Right);
 809
 810            // Expand empty ranges by one character
 811            if entry.range.start == entry.range.end {
 812                entry.range.end.column += 1;
 813                entry.range.end = content.clip_point_utf16(entry.range.end, Bias::Right);
 814                if entry.range.start == entry.range.end && entry.range.end.column > 0 {
 815                    entry.range.start.column -= 1;
 816                    entry.range.start = content.clip_point_utf16(entry.range.start, Bias::Left);
 817                }
 818            }
 819            ix += 1;
 820        }
 821        drop(edits_since_save);
 822        self.diagnostics = DiagnosticSet::new(diagnostics, content);
 823        self.diagnostics_update_count += 1;
 824        cx.notify();
 825        cx.emit(Event::DiagnosticsUpdated);
 826        Ok(Operation::UpdateDiagnostics {
 827            diagnostics: Arc::from(self.diagnostics.iter().cloned().collect::<Vec<_>>()),
 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.start_transaction();
 971        for (row, indent_column) in &indent_columns {
 972            self.set_indent_column_for_line(*row, *indent_column, cx);
 973        }
 974        self.end_transaction(cx);
 975    }
 976
 977    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
 978        let current_column = self.indent_column_for_line(row);
 979        if column > current_column {
 980            let offset = Point::new(row, 0).to_offset(&*self);
 981            self.edit(
 982                [offset..offset],
 983                " ".repeat((column - current_column) as usize),
 984                cx,
 985            );
 986        } else if column < current_column {
 987            self.edit(
 988                [Point::new(row, 0)..Point::new(row, current_column - column)],
 989                "",
 990                cx,
 991            );
 992        }
 993    }
 994
 995    pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
 996        // TODO: it would be nice to not allocate here.
 997        let old_text = self.text();
 998        let base_version = self.version();
 999        cx.background().spawn(async move {
1000            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1001                .iter_all_changes()
1002                .map(|c| (c.tag(), c.value().len()))
1003                .collect::<Vec<_>>();
1004            Diff {
1005                base_version,
1006                new_text,
1007                changes,
1008            }
1009        })
1010    }
1011
1012    pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1013        if self.version == diff.base_version {
1014            self.start_transaction();
1015            let mut offset = 0;
1016            for (tag, len) in diff.changes {
1017                let range = offset..(offset + len);
1018                match tag {
1019                    ChangeTag::Equal => offset += len,
1020                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1021                    ChangeTag::Insert => {
1022                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1023                        offset += len;
1024                    }
1025                }
1026            }
1027            self.end_transaction(cx);
1028            true
1029        } else {
1030            false
1031        }
1032    }
1033
1034    pub fn is_dirty(&self) -> bool {
1035        !self.saved_version.ge(&self.version)
1036            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1037    }
1038
1039    pub fn has_conflict(&self) -> bool {
1040        !self.saved_version.ge(&self.version)
1041            && self
1042                .file
1043                .as_ref()
1044                .map_or(false, |file| file.mtime() > self.saved_mtime)
1045    }
1046
1047    pub fn subscribe(&mut self) -> Subscription {
1048        self.text.subscribe()
1049    }
1050
1051    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1052        self.start_transaction_at(Instant::now())
1053    }
1054
1055    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1056        self.text.start_transaction_at(now)
1057    }
1058
1059    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1060        self.end_transaction_at(Instant::now(), cx)
1061    }
1062
1063    pub fn end_transaction_at(
1064        &mut self,
1065        now: Instant,
1066        cx: &mut ModelContext<Self>,
1067    ) -> Option<TransactionId> {
1068        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1069            let was_dirty = start_version != self.saved_version;
1070            self.did_edit(&start_version, was_dirty, cx);
1071            Some(transaction_id)
1072        } else {
1073            None
1074        }
1075    }
1076
1077    pub fn set_active_selections(
1078        &mut self,
1079        selections: Arc<[Selection<Anchor>]>,
1080        cx: &mut ModelContext<Self>,
1081    ) {
1082        let lamport_timestamp = self.text.lamport_clock.tick();
1083        self.remote_selections
1084            .insert(self.text.replica_id(), selections.clone());
1085        self.send_operation(
1086            Operation::UpdateSelections {
1087                replica_id: self.text.replica_id(),
1088                selections,
1089                lamport_timestamp,
1090            },
1091            cx,
1092        );
1093    }
1094
1095    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1096        let lamport_timestamp = self.text.lamport_clock.tick();
1097        self.send_operation(
1098            Operation::RemoveSelections {
1099                replica_id: self.text.replica_id(),
1100                lamport_timestamp,
1101            },
1102            cx,
1103        );
1104    }
1105
1106    fn update_language_server(&mut self) {
1107        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1108            language_server
1109        } else {
1110            return;
1111        };
1112        let abs_path = self
1113            .file
1114            .as_ref()
1115            .map_or(Path::new("/").to_path_buf(), |file| {
1116                file.abs_path().unwrap()
1117            });
1118
1119        let version = post_inc(&mut language_server.next_version);
1120        let snapshot = LanguageServerSnapshot {
1121            buffer_snapshot: self.text.snapshot(),
1122            version,
1123            path: Arc::from(abs_path),
1124        };
1125        language_server
1126            .pending_snapshots
1127            .insert(version, snapshot.clone());
1128        let _ = language_server
1129            .latest_snapshot
1130            .blocking_send(Some(snapshot));
1131    }
1132
1133    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1134    where
1135        I: IntoIterator<Item = Range<S>>,
1136        S: ToOffset,
1137        T: Into<String>,
1138    {
1139        self.edit_internal(ranges_iter, new_text, false, cx)
1140    }
1141
1142    pub fn edit_with_autoindent<I, S, T>(
1143        &mut self,
1144        ranges_iter: I,
1145        new_text: T,
1146        cx: &mut ModelContext<Self>,
1147    ) where
1148        I: IntoIterator<Item = Range<S>>,
1149        S: ToOffset,
1150        T: Into<String>,
1151    {
1152        self.edit_internal(ranges_iter, new_text, true, cx)
1153    }
1154
1155    pub fn edit_internal<I, S, T>(
1156        &mut self,
1157        ranges_iter: I,
1158        new_text: T,
1159        autoindent: bool,
1160        cx: &mut ModelContext<Self>,
1161    ) where
1162        I: IntoIterator<Item = Range<S>>,
1163        S: ToOffset,
1164        T: Into<String>,
1165    {
1166        let new_text = new_text.into();
1167
1168        // Skip invalid ranges and coalesce contiguous ones.
1169        let mut ranges: Vec<Range<usize>> = Vec::new();
1170        for range in ranges_iter {
1171            let range = range.start.to_offset(self)..range.end.to_offset(self);
1172            if !new_text.is_empty() || !range.is_empty() {
1173                if let Some(prev_range) = ranges.last_mut() {
1174                    if prev_range.end >= range.start {
1175                        prev_range.end = cmp::max(prev_range.end, range.end);
1176                    } else {
1177                        ranges.push(range);
1178                    }
1179                } else {
1180                    ranges.push(range);
1181                }
1182            }
1183        }
1184        if ranges.is_empty() {
1185            return;
1186        }
1187
1188        self.start_transaction();
1189        self.pending_autoindent.take();
1190        let autoindent_request = if autoindent && self.language.is_some() {
1191            let before_edit = self.snapshot();
1192            let edited = ranges
1193                .iter()
1194                .filter_map(|range| {
1195                    let start = range.start.to_point(self);
1196                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1197                        None
1198                    } else {
1199                        Some(self.anchor_before(range.start))
1200                    }
1201                })
1202                .collect();
1203            Some((before_edit, edited))
1204        } else {
1205            None
1206        };
1207
1208        let first_newline_ix = new_text.find('\n');
1209        let new_text_len = new_text.len();
1210
1211        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1212
1213        if let Some((before_edit, edited)) = autoindent_request {
1214            let mut inserted = None;
1215            if let Some(first_newline_ix) = first_newline_ix {
1216                let mut delta = 0isize;
1217                inserted = Some(
1218                    ranges
1219                        .iter()
1220                        .map(|range| {
1221                            let start =
1222                                (delta + range.start as isize) as usize + first_newline_ix + 1;
1223                            let end = (delta + range.start as isize) as usize + new_text_len;
1224                            delta +=
1225                                (range.end as isize - range.start as isize) + new_text_len as isize;
1226                            self.anchor_before(start)..self.anchor_after(end)
1227                        })
1228                        .collect(),
1229                );
1230            }
1231
1232            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1233                before_edit,
1234                edited,
1235                inserted,
1236            }));
1237        }
1238
1239        self.end_transaction(cx);
1240        self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1241    }
1242
1243    fn did_edit(
1244        &mut self,
1245        old_version: &clock::Global,
1246        was_dirty: bool,
1247        cx: &mut ModelContext<Self>,
1248    ) {
1249        if self.edits_since::<usize>(old_version).next().is_none() {
1250            return;
1251        }
1252
1253        self.reparse(cx);
1254        self.update_language_server();
1255
1256        cx.emit(Event::Edited);
1257        if !was_dirty {
1258            cx.emit(Event::Dirtied);
1259        }
1260        cx.notify();
1261    }
1262
1263    fn grammar(&self) -> Option<&Arc<Grammar>> {
1264        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1265    }
1266
1267    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1268        &mut self,
1269        ops: I,
1270        cx: &mut ModelContext<Self>,
1271    ) -> Result<()> {
1272        self.pending_autoindent.take();
1273        let was_dirty = self.is_dirty();
1274        let old_version = self.version.clone();
1275        let mut deferred_ops = Vec::new();
1276        let buffer_ops = ops
1277            .into_iter()
1278            .filter_map(|op| match op {
1279                Operation::Buffer(op) => Some(op),
1280                _ => {
1281                    if self.can_apply_op(&op) {
1282                        self.apply_op(op, cx);
1283                    } else {
1284                        deferred_ops.push(op);
1285                    }
1286                    None
1287                }
1288            })
1289            .collect::<Vec<_>>();
1290        self.text.apply_ops(buffer_ops)?;
1291        self.flush_deferred_ops(cx);
1292        self.did_edit(&old_version, was_dirty, cx);
1293        // Notify independently of whether the buffer was edited as the operations could include a
1294        // selection update.
1295        cx.notify();
1296        Ok(())
1297    }
1298
1299    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1300        let mut deferred_ops = Vec::new();
1301        for op in self.deferred_ops.drain().iter().cloned() {
1302            if self.can_apply_op(&op) {
1303                self.apply_op(op, cx);
1304            } else {
1305                deferred_ops.push(op);
1306            }
1307        }
1308        self.deferred_ops.insert(deferred_ops);
1309    }
1310
1311    fn can_apply_op(&self, operation: &Operation) -> bool {
1312        match operation {
1313            Operation::Buffer(_) => {
1314                unreachable!("buffer operations should never be applied at this layer")
1315            }
1316            Operation::UpdateDiagnostics { diagnostics, .. } => {
1317                diagnostics.iter().all(|diagnostic| {
1318                    self.text.can_resolve(&diagnostic.range.start)
1319                        && self.text.can_resolve(&diagnostic.range.end)
1320                })
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 { diagnostics, .. } => {
1335                self.apply_diagnostic_update(diagnostics, cx);
1336            }
1337            Operation::UpdateSelections {
1338                replica_id,
1339                selections,
1340                lamport_timestamp,
1341            } => {
1342                self.remote_selections.insert(replica_id, selections);
1343                self.text.lamport_clock.observe(lamport_timestamp);
1344            }
1345            Operation::RemoveSelections {
1346                replica_id,
1347                lamport_timestamp,
1348            } => {
1349                self.remote_selections.remove(&replica_id);
1350                self.text.lamport_clock.observe(lamport_timestamp);
1351            }
1352        }
1353    }
1354
1355    fn apply_diagnostic_update(
1356        &mut self,
1357        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
1358        cx: &mut ModelContext<Self>,
1359    ) {
1360        self.diagnostics = DiagnosticSet::from_sorted_entries(diagnostics.iter().cloned(), self);
1361        self.diagnostics_update_count += 1;
1362        cx.notify();
1363    }
1364
1365    #[cfg(not(test))]
1366    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1367        if let Some(file) = &self.file {
1368            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1369        }
1370    }
1371
1372    #[cfg(test)]
1373    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1374        self.operations.push(operation);
1375    }
1376
1377    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1378        self.remote_selections.remove(&replica_id);
1379        cx.notify();
1380    }
1381
1382    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1383        let was_dirty = self.is_dirty();
1384        let old_version = self.version.clone();
1385
1386        if let Some((transaction_id, operation)) = self.text.undo() {
1387            self.send_operation(Operation::Buffer(operation), cx);
1388            self.did_edit(&old_version, was_dirty, cx);
1389            Some(transaction_id)
1390        } else {
1391            None
1392        }
1393    }
1394
1395    pub fn undo_transaction(
1396        &mut self,
1397        transaction_id: TransactionId,
1398        cx: &mut ModelContext<Self>,
1399    ) -> bool {
1400        let was_dirty = self.is_dirty();
1401        let old_version = self.version.clone();
1402
1403        if let Some(operation) = self.text.undo_transaction(transaction_id) {
1404            self.send_operation(Operation::Buffer(operation), cx);
1405            self.did_edit(&old_version, was_dirty, cx);
1406            true
1407        } else {
1408            false
1409        }
1410    }
1411
1412    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1413        let was_dirty = self.is_dirty();
1414        let old_version = self.version.clone();
1415
1416        if let Some((transaction_id, operation)) = self.text.redo() {
1417            self.send_operation(Operation::Buffer(operation), cx);
1418            self.did_edit(&old_version, was_dirty, cx);
1419            Some(transaction_id)
1420        } else {
1421            None
1422        }
1423    }
1424
1425    pub fn redo_transaction(
1426        &mut self,
1427        transaction_id: TransactionId,
1428        cx: &mut ModelContext<Self>,
1429    ) -> bool {
1430        let was_dirty = self.is_dirty();
1431        let old_version = self.version.clone();
1432
1433        if let Some(operation) = self.text.redo_transaction(transaction_id) {
1434            self.send_operation(Operation::Buffer(operation), cx);
1435            self.did_edit(&old_version, was_dirty, cx);
1436            true
1437        } else {
1438            false
1439        }
1440    }
1441}
1442
1443#[cfg(any(test, feature = "test-support"))]
1444impl Buffer {
1445    pub fn randomly_edit<T>(
1446        &mut self,
1447        rng: &mut T,
1448        old_range_count: usize,
1449        cx: &mut ModelContext<Self>,
1450    ) where
1451        T: rand::Rng,
1452    {
1453        self.start_transaction();
1454        self.text.randomly_edit(rng, old_range_count);
1455        self.end_transaction(cx);
1456    }
1457}
1458
1459impl Entity for Buffer {
1460    type Event = Event;
1461
1462    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1463        if let Some(file) = self.file.as_ref() {
1464            file.buffer_removed(self.remote_id(), cx);
1465        }
1466    }
1467}
1468
1469impl Deref for Buffer {
1470    type Target = TextBuffer;
1471
1472    fn deref(&self) -> &Self::Target {
1473        &self.text
1474    }
1475}
1476
1477impl BufferSnapshot {
1478    fn suggest_autoindents<'a>(
1479        &'a self,
1480        row_range: Range<u32>,
1481    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1482        let mut query_cursor = QueryCursorHandle::new();
1483        if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1484            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1485
1486            // Get the "indentation ranges" that intersect this row range.
1487            let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
1488            let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
1489            query_cursor.set_point_range(
1490                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1491                    ..Point::new(row_range.end, 0).to_ts_point(),
1492            );
1493            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1494            for mat in query_cursor.matches(
1495                &grammar.indents_query,
1496                tree.root_node(),
1497                TextProvider(self.as_rope()),
1498            ) {
1499                let mut node_kind = "";
1500                let mut start: Option<Point> = None;
1501                let mut end: Option<Point> = None;
1502                for capture in mat.captures {
1503                    if Some(capture.index) == indent_capture_ix {
1504                        node_kind = capture.node.kind();
1505                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1506                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1507                    } else if Some(capture.index) == end_capture_ix {
1508                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1509                    }
1510                }
1511
1512                if let Some((start, end)) = start.zip(end) {
1513                    if start.row == end.row {
1514                        continue;
1515                    }
1516
1517                    let range = start..end;
1518                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1519                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1520                        Ok(ix) => {
1521                            let prev_range = &mut indentation_ranges[ix];
1522                            prev_range.0.end = prev_range.0.end.max(range.end);
1523                        }
1524                    }
1525                }
1526            }
1527
1528            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1529            Some(row_range.map(move |row| {
1530                let row_start = Point::new(row, self.indent_column_for_line(row));
1531
1532                let mut indent_from_prev_row = false;
1533                let mut outdent_to_row = u32::MAX;
1534                for (range, _node_kind) in &indentation_ranges {
1535                    if range.start.row >= row {
1536                        break;
1537                    }
1538
1539                    if range.start.row == prev_row && range.end > row_start {
1540                        indent_from_prev_row = true;
1541                    }
1542                    if range.end.row >= prev_row && range.end <= row_start {
1543                        outdent_to_row = outdent_to_row.min(range.start.row);
1544                    }
1545                }
1546
1547                let suggestion = if outdent_to_row == prev_row {
1548                    IndentSuggestion {
1549                        basis_row: prev_row,
1550                        indent: false,
1551                    }
1552                } else if indent_from_prev_row {
1553                    IndentSuggestion {
1554                        basis_row: prev_row,
1555                        indent: true,
1556                    }
1557                } else if outdent_to_row < prev_row {
1558                    IndentSuggestion {
1559                        basis_row: outdent_to_row,
1560                        indent: false,
1561                    }
1562                } else {
1563                    IndentSuggestion {
1564                        basis_row: prev_row,
1565                        indent: false,
1566                    }
1567                };
1568
1569                prev_row = row;
1570                suggestion
1571            }))
1572        } else {
1573            None
1574        }
1575    }
1576
1577    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1578        while row > 0 {
1579            row -= 1;
1580            if !self.is_line_blank(row) {
1581                return Some(row);
1582            }
1583        }
1584        None
1585    }
1586
1587    pub fn chunks<'a, T: ToOffset>(
1588        &'a self,
1589        range: Range<T>,
1590        theme: Option<&'a SyntaxTheme>,
1591    ) -> BufferChunks<'a> {
1592        let range = range.start.to_offset(self)..range.end.to_offset(self);
1593
1594        let mut highlights = None;
1595        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1596        if let Some(theme) = theme {
1597            for entry in self
1598                .diagnostics
1599                .range::<_, usize>(range.clone(), self, true)
1600            {
1601                diagnostic_endpoints.push(DiagnosticEndpoint {
1602                    offset: entry.range.start,
1603                    is_start: true,
1604                    severity: entry.diagnostic.severity,
1605                });
1606                diagnostic_endpoints.push(DiagnosticEndpoint {
1607                    offset: entry.range.end,
1608                    is_start: false,
1609                    severity: entry.diagnostic.severity,
1610                });
1611            }
1612            diagnostic_endpoints
1613                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1614
1615            if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1616                let mut query_cursor = QueryCursorHandle::new();
1617
1618                // TODO - add a Tree-sitter API to remove the need for this.
1619                let cursor = unsafe {
1620                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1621                };
1622                let captures = cursor.set_byte_range(range.clone()).captures(
1623                    &grammar.highlights_query,
1624                    tree.root_node(),
1625                    TextProvider(self.text.as_rope()),
1626                );
1627                highlights = Some(BufferChunkHighlights {
1628                    captures,
1629                    next_capture: None,
1630                    stack: Default::default(),
1631                    highlight_map: grammar.highlight_map(),
1632                    _query_cursor: query_cursor,
1633                    theme,
1634                })
1635            }
1636        }
1637
1638        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1639        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1640
1641        BufferChunks {
1642            range,
1643            chunks,
1644            diagnostic_endpoints,
1645            error_depth: 0,
1646            warning_depth: 0,
1647            information_depth: 0,
1648            hint_depth: 0,
1649            highlights,
1650        }
1651    }
1652
1653    pub fn language(&self) -> Option<&Arc<Language>> {
1654        self.language.as_ref()
1655    }
1656
1657    fn grammar(&self) -> Option<&Arc<Grammar>> {
1658        self.language
1659            .as_ref()
1660            .and_then(|language| language.grammar.as_ref())
1661    }
1662
1663    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1664        if let Some(tree) = self.tree.as_ref() {
1665            let root = tree.root_node();
1666            let range = range.start.to_offset(self)..range.end.to_offset(self);
1667            let mut node = root.descendant_for_byte_range(range.start, range.end);
1668            while node.map_or(false, |n| n.byte_range() == range) {
1669                node = node.unwrap().parent();
1670            }
1671            node.map(|n| n.byte_range())
1672        } else {
1673            None
1674        }
1675    }
1676
1677    pub fn enclosing_bracket_ranges<T: ToOffset>(
1678        &self,
1679        range: Range<T>,
1680    ) -> Option<(Range<usize>, Range<usize>)> {
1681        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
1682        let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
1683        let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
1684
1685        // Find bracket pairs that *inclusively* contain the given range.
1686        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1687        let mut cursor = QueryCursorHandle::new();
1688        let matches = cursor.set_byte_range(range).matches(
1689            &grammar.brackets_query,
1690            tree.root_node(),
1691            TextProvider(self.as_rope()),
1692        );
1693
1694        // Get the ranges of the innermost pair of brackets.
1695        matches
1696            .filter_map(|mat| {
1697                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1698                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1699                Some((open.byte_range(), close.byte_range()))
1700            })
1701            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1702    }
1703
1704    pub fn remote_selections_in_range<'a>(
1705        &'a self,
1706        range: Range<Anchor>,
1707    ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
1708    {
1709        self.remote_selections
1710            .iter()
1711            .filter(|(replica_id, _)| **replica_id != self.text.replica_id())
1712            .map(move |(replica_id, selections)| {
1713                let start_ix = match selections
1714                    .binary_search_by(|probe| probe.end.cmp(&range.start, self).unwrap())
1715                {
1716                    Ok(ix) | Err(ix) => ix,
1717                };
1718                let end_ix = match selections
1719                    .binary_search_by(|probe| probe.start.cmp(&range.end, self).unwrap())
1720                {
1721                    Ok(ix) | Err(ix) => ix,
1722                };
1723
1724                (*replica_id, selections[start_ix..end_ix].iter())
1725            })
1726    }
1727
1728    pub fn diagnostics_in_range<'a, T, O>(
1729        &'a self,
1730        search_range: Range<T>,
1731    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1732    where
1733        T: 'a + ToOffset,
1734        O: 'a + FromAnchor,
1735    {
1736        self.diagnostics.range(search_range, self, true)
1737    }
1738
1739    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
1740        self.diagnostics.groups(self)
1741    }
1742
1743    pub fn diagnostic_group<'a, O>(
1744        &'a self,
1745        group_id: usize,
1746    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1747    where
1748        O: 'a + FromAnchor,
1749    {
1750        self.diagnostics.group(group_id, self)
1751    }
1752
1753    pub fn diagnostics_update_count(&self) -> usize {
1754        self.diagnostics_update_count
1755    }
1756
1757    pub fn parse_count(&self) -> usize {
1758        self.parse_count
1759    }
1760}
1761
1762impl Clone for BufferSnapshot {
1763    fn clone(&self) -> Self {
1764        Self {
1765            text: self.text.clone(),
1766            tree: self.tree.clone(),
1767            remote_selections: self.remote_selections.clone(),
1768            diagnostics: self.diagnostics.clone(),
1769            diagnostics_update_count: self.diagnostics_update_count,
1770            is_parsing: self.is_parsing,
1771            language: self.language.clone(),
1772            parse_count: self.parse_count,
1773        }
1774    }
1775}
1776
1777impl Deref for BufferSnapshot {
1778    type Target = text::BufferSnapshot;
1779
1780    fn deref(&self) -> &Self::Target {
1781        &self.text
1782    }
1783}
1784
1785impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1786    type I = ByteChunks<'a>;
1787
1788    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1789        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1790    }
1791}
1792
1793struct ByteChunks<'a>(rope::Chunks<'a>);
1794
1795impl<'a> Iterator for ByteChunks<'a> {
1796    type Item = &'a [u8];
1797
1798    fn next(&mut self) -> Option<Self::Item> {
1799        self.0.next().map(str::as_bytes)
1800    }
1801}
1802
1803unsafe impl<'a> Send for BufferChunks<'a> {}
1804
1805impl<'a> BufferChunks<'a> {
1806    pub fn seek(&mut self, offset: usize) {
1807        self.range.start = offset;
1808        self.chunks.seek(self.range.start);
1809        if let Some(highlights) = self.highlights.as_mut() {
1810            highlights
1811                .stack
1812                .retain(|(end_offset, _)| *end_offset > offset);
1813            if let Some((mat, capture_ix)) = &highlights.next_capture {
1814                let capture = mat.captures[*capture_ix as usize];
1815                if offset >= capture.node.start_byte() {
1816                    let next_capture_end = capture.node.end_byte();
1817                    if offset < next_capture_end {
1818                        highlights.stack.push((
1819                            next_capture_end,
1820                            highlights.highlight_map.get(capture.index),
1821                        ));
1822                    }
1823                    highlights.next_capture.take();
1824                }
1825            }
1826            highlights.captures.set_byte_range(self.range.clone());
1827        }
1828    }
1829
1830    pub fn offset(&self) -> usize {
1831        self.range.start
1832    }
1833
1834    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1835        let depth = match endpoint.severity {
1836            DiagnosticSeverity::ERROR => &mut self.error_depth,
1837            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1838            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1839            DiagnosticSeverity::HINT => &mut self.hint_depth,
1840            _ => return,
1841        };
1842        if endpoint.is_start {
1843            *depth += 1;
1844        } else {
1845            *depth -= 1;
1846        }
1847    }
1848
1849    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1850        if self.error_depth > 0 {
1851            Some(DiagnosticSeverity::ERROR)
1852        } else if self.warning_depth > 0 {
1853            Some(DiagnosticSeverity::WARNING)
1854        } else if self.information_depth > 0 {
1855            Some(DiagnosticSeverity::INFORMATION)
1856        } else if self.hint_depth > 0 {
1857            Some(DiagnosticSeverity::HINT)
1858        } else {
1859            None
1860        }
1861    }
1862}
1863
1864impl<'a> Iterator for BufferChunks<'a> {
1865    type Item = Chunk<'a>;
1866
1867    fn next(&mut self) -> Option<Self::Item> {
1868        let mut next_capture_start = usize::MAX;
1869        let mut next_diagnostic_endpoint = usize::MAX;
1870
1871        if let Some(highlights) = self.highlights.as_mut() {
1872            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1873                if *parent_capture_end <= self.range.start {
1874                    highlights.stack.pop();
1875                } else {
1876                    break;
1877                }
1878            }
1879
1880            if highlights.next_capture.is_none() {
1881                highlights.next_capture = highlights.captures.next();
1882            }
1883
1884            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1885                let capture = mat.captures[*capture_ix as usize];
1886                if self.range.start < capture.node.start_byte() {
1887                    next_capture_start = capture.node.start_byte();
1888                    break;
1889                } else {
1890                    let highlight_id = highlights.highlight_map.get(capture.index);
1891                    highlights
1892                        .stack
1893                        .push((capture.node.end_byte(), highlight_id));
1894                    highlights.next_capture = highlights.captures.next();
1895                }
1896            }
1897        }
1898
1899        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
1900            if endpoint.offset <= self.range.start {
1901                self.update_diagnostic_depths(endpoint);
1902                self.diagnostic_endpoints.next();
1903            } else {
1904                next_diagnostic_endpoint = endpoint.offset;
1905                break;
1906            }
1907        }
1908
1909        if let Some(chunk) = self.chunks.peek() {
1910            let chunk_start = self.range.start;
1911            let mut chunk_end = (self.chunks.offset() + chunk.len())
1912                .min(next_capture_start)
1913                .min(next_diagnostic_endpoint);
1914            let mut highlight_style = None;
1915            if let Some(highlights) = self.highlights.as_ref() {
1916                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
1917                    chunk_end = chunk_end.min(*parent_capture_end);
1918                    highlight_style = parent_highlight_id.style(highlights.theme);
1919                }
1920            }
1921
1922            let slice =
1923                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
1924            self.range.start = chunk_end;
1925            if self.range.start == self.chunks.offset() + chunk.len() {
1926                self.chunks.next().unwrap();
1927            }
1928
1929            Some(Chunk {
1930                text: slice,
1931                highlight_style,
1932                diagnostic: self.current_diagnostic_severity(),
1933            })
1934        } else {
1935            None
1936        }
1937    }
1938}
1939
1940impl QueryCursorHandle {
1941    fn new() -> Self {
1942        QueryCursorHandle(Some(
1943            QUERY_CURSORS
1944                .lock()
1945                .pop()
1946                .unwrap_or_else(|| QueryCursor::new()),
1947        ))
1948    }
1949}
1950
1951impl Deref for QueryCursorHandle {
1952    type Target = QueryCursor;
1953
1954    fn deref(&self) -> &Self::Target {
1955        self.0.as_ref().unwrap()
1956    }
1957}
1958
1959impl DerefMut for QueryCursorHandle {
1960    fn deref_mut(&mut self) -> &mut Self::Target {
1961        self.0.as_mut().unwrap()
1962    }
1963}
1964
1965impl Drop for QueryCursorHandle {
1966    fn drop(&mut self) {
1967        let mut cursor = self.0.take().unwrap();
1968        cursor.set_byte_range(0..usize::MAX);
1969        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
1970        QUERY_CURSORS.lock().push(cursor)
1971    }
1972}
1973
1974trait ToTreeSitterPoint {
1975    fn to_ts_point(self) -> tree_sitter::Point;
1976    fn from_ts_point(point: tree_sitter::Point) -> Self;
1977}
1978
1979impl ToTreeSitterPoint for Point {
1980    fn to_ts_point(self) -> tree_sitter::Point {
1981        tree_sitter::Point::new(self.row as usize, self.column as usize)
1982    }
1983
1984    fn from_ts_point(point: tree_sitter::Point) -> Self {
1985        Point::new(point.row as u32, point.column as u32)
1986    }
1987}
1988
1989impl operation_queue::Operation for Operation {
1990    fn lamport_timestamp(&self) -> clock::Lamport {
1991        match self {
1992            Operation::Buffer(_) => {
1993                unreachable!("buffer operations should never be deferred at this layer")
1994            }
1995            Operation::UpdateDiagnostics {
1996                lamport_timestamp, ..
1997            }
1998            | Operation::UpdateSelections {
1999                lamport_timestamp, ..
2000            }
2001            | Operation::RemoveSelections {
2002                lamport_timestamp, ..
2003            } => *lamport_timestamp,
2004        }
2005    }
2006}
2007
2008impl Default for Diagnostic {
2009    fn default() -> Self {
2010        Self {
2011            source: Default::default(),
2012            code: Default::default(),
2013            severity: DiagnosticSeverity::ERROR,
2014            message: Default::default(),
2015            group_id: Default::default(),
2016            is_primary: Default::default(),
2017            is_valid: true,
2018        }
2019    }
2020}
2021
2022pub fn contiguous_ranges(
2023    values: impl Iterator<Item = u32>,
2024    max_len: usize,
2025) -> impl Iterator<Item = Range<u32>> {
2026    let mut values = values.into_iter();
2027    let mut current_range: Option<Range<u32>> = None;
2028    std::iter::from_fn(move || loop {
2029        if let Some(value) = values.next() {
2030            if let Some(range) = &mut current_range {
2031                if value == range.end && range.len() < max_len {
2032                    range.end += 1;
2033                    continue;
2034                }
2035            }
2036
2037            let prev_range = current_range.clone();
2038            current_range = Some(value..(value + 1));
2039            if prev_range.is_some() {
2040                return prev_range;
2041            }
2042        } else {
2043            return current_range.take();
2044        }
2045    })
2046}