buffer.rs

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