buffer.rs

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