buffer.rs

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