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