buffer.rs

   1pub use crate::{
   2    diagnostic_set::DiagnosticSet,
   3    highlight_map::{HighlightId, HighlightMap},
   4    proto, BracketPair, Grammar, Language, LanguageConfig, LanguageRegistry, PLAIN_TEXT,
   5};
   6use crate::{
   7    diagnostic_set::{DiagnosticEntry, DiagnosticGroup},
   8    outline::OutlineItem,
   9    syntax_map::{
  10        SyntaxMap, SyntaxMapCapture, SyntaxMapCaptures, SyntaxSnapshot, ToTreeSitterPoint,
  11    },
  12    CodeLabel, Outline,
  13};
  14use anyhow::{anyhow, Result};
  15use clock::ReplicaId;
  16use futures::FutureExt as _;
  17use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, MutableAppContext, Task};
  18use parking_lot::Mutex;
  19use settings::Settings;
  20use similar::{ChangeTag, TextDiff};
  21use smol::future::yield_now;
  22use std::{
  23    any::Any,
  24    cmp::{self, Ordering},
  25    collections::BTreeMap,
  26    ffi::OsStr,
  27    future::Future,
  28    iter::{self, Iterator, Peekable},
  29    mem,
  30    ops::{Deref, Range},
  31    path::{Path, PathBuf},
  32    str,
  33    sync::Arc,
  34    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  35    vec,
  36};
  37use sum_tree::TreeMap;
  38use text::operation_queue::OperationQueue;
  39pub use text::{Buffer as TextBuffer, BufferSnapshot as TextBufferSnapshot, Operation as _, *};
  40use theme::SyntaxTheme;
  41use util::TryFutureExt as _;
  42
  43#[cfg(any(test, feature = "test-support"))]
  44pub use {tree_sitter_rust, tree_sitter_typescript};
  45
  46pub use lsp::DiagnosticSeverity;
  47
  48pub struct Buffer {
  49    text: TextBuffer,
  50    file: Option<Arc<dyn File>>,
  51    saved_version: clock::Global,
  52    saved_version_fingerprint: String,
  53    saved_mtime: SystemTime,
  54    transaction_depth: usize,
  55    was_dirty_before_starting_transaction: Option<bool>,
  56    language: Option<Arc<Language>>,
  57    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  58    pending_autoindent: Option<Task<()>>,
  59    sync_parse_timeout: Duration,
  60    syntax_map: Mutex<SyntaxMap>,
  61    parsing_in_background: bool,
  62    parse_count: usize,
  63    diagnostics: DiagnosticSet,
  64    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  65    selections_update_count: usize,
  66    diagnostics_update_count: usize,
  67    diagnostics_timestamp: clock::Lamport,
  68    file_update_count: usize,
  69    completion_triggers: Vec<String>,
  70    completion_triggers_timestamp: clock::Lamport,
  71    deferred_ops: OperationQueue<Operation>,
  72}
  73
  74pub struct BufferSnapshot {
  75    text: text::BufferSnapshot,
  76    pub(crate) syntax: SyntaxSnapshot,
  77    file: Option<Arc<dyn File>>,
  78    diagnostics: DiagnosticSet,
  79    diagnostics_update_count: usize,
  80    file_update_count: usize,
  81    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  82    selections_update_count: usize,
  83    language: Option<Arc<Language>>,
  84    parse_count: usize,
  85}
  86
  87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
  88pub struct IndentSize {
  89    pub len: u32,
  90    pub kind: IndentKind,
  91}
  92
  93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
  94pub enum IndentKind {
  95    Space,
  96    Tab,
  97}
  98
  99#[derive(Clone, Debug)]
 100struct SelectionSet {
 101    line_mode: bool,
 102    selections: Arc<[Selection<Anchor>]>,
 103    lamport_timestamp: clock::Lamport,
 104}
 105
 106#[derive(Clone, Debug, PartialEq, Eq)]
 107pub struct GroupId {
 108    source: Arc<str>,
 109    id: usize,
 110}
 111
 112#[derive(Clone, Debug, PartialEq, Eq)]
 113pub struct Diagnostic {
 114    pub code: Option<String>,
 115    pub severity: DiagnosticSeverity,
 116    pub message: String,
 117    pub group_id: usize,
 118    pub is_valid: bool,
 119    pub is_primary: bool,
 120    pub is_disk_based: bool,
 121    pub is_unnecessary: bool,
 122}
 123
 124#[derive(Clone, Debug)]
 125pub struct Completion {
 126    pub old_range: Range<Anchor>,
 127    pub new_text: String,
 128    pub label: CodeLabel,
 129    pub lsp_completion: lsp::CompletionItem,
 130}
 131
 132#[derive(Clone, Debug)]
 133pub struct CodeAction {
 134    pub range: Range<Anchor>,
 135    pub lsp_action: lsp::CodeAction,
 136}
 137
 138#[derive(Clone, Debug, PartialEq, Eq)]
 139pub enum Operation {
 140    Buffer(text::Operation),
 141    UpdateDiagnostics {
 142        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 143        lamport_timestamp: clock::Lamport,
 144    },
 145    UpdateSelections {
 146        selections: Arc<[Selection<Anchor>]>,
 147        lamport_timestamp: clock::Lamport,
 148        line_mode: bool,
 149    },
 150    UpdateCompletionTriggers {
 151        triggers: Vec<String>,
 152        lamport_timestamp: clock::Lamport,
 153    },
 154}
 155
 156#[derive(Clone, Debug, PartialEq, Eq)]
 157pub enum Event {
 158    Operation(Operation),
 159    Edited,
 160    DirtyChanged,
 161    Saved,
 162    FileHandleChanged,
 163    Reloaded,
 164    Reparsed,
 165    DiagnosticsUpdated,
 166    Closed,
 167}
 168
 169pub trait File: Send + Sync {
 170    fn as_local(&self) -> Option<&dyn LocalFile>;
 171
 172    fn is_local(&self) -> bool {
 173        self.as_local().is_some()
 174    }
 175
 176    fn mtime(&self) -> SystemTime;
 177
 178    /// Returns the path of this file relative to the worktree's root directory.
 179    fn path(&self) -> &Arc<Path>;
 180
 181    /// Returns the path of this file relative to the worktree's parent directory (this means it
 182    /// includes the name of the worktree's root folder).
 183    fn full_path(&self, cx: &AppContext) -> PathBuf;
 184
 185    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 186    /// of its worktree, then this method will return the name of the worktree itself.
 187    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr;
 188
 189    fn is_deleted(&self) -> bool;
 190
 191    fn save(
 192        &self,
 193        buffer_id: u64,
 194        text: Rope,
 195        version: clock::Global,
 196        line_ending: LineEnding,
 197        cx: &mut MutableAppContext,
 198    ) -> Task<Result<(clock::Global, String, SystemTime)>>;
 199
 200    fn as_any(&self) -> &dyn Any;
 201
 202    fn to_proto(&self) -> rpc::proto::File;
 203}
 204
 205pub trait LocalFile: File {
 206    /// Returns the absolute path of this file.
 207    fn abs_path(&self, cx: &AppContext) -> PathBuf;
 208
 209    fn load(&self, cx: &AppContext) -> Task<Result<String>>;
 210
 211    fn buffer_reloaded(
 212        &self,
 213        buffer_id: u64,
 214        version: &clock::Global,
 215        fingerprint: String,
 216        line_ending: LineEnding,
 217        mtime: SystemTime,
 218        cx: &mut MutableAppContext,
 219    );
 220}
 221
 222#[derive(Clone, Debug)]
 223pub enum AutoindentMode {
 224    /// Indent each line of inserted text.
 225    EachLine,
 226    /// Apply the same indentation adjustment to all of the lines
 227    /// in a given insertion.
 228    Block {
 229        /// The original indentation level of the first line of each
 230        /// insertion, if it has been copied.
 231        original_indent_columns: Vec<u32>,
 232    },
 233}
 234
 235#[derive(Clone)]
 236struct AutoindentRequest {
 237    before_edit: BufferSnapshot,
 238    entries: Vec<AutoindentRequestEntry>,
 239    indent_size: IndentSize,
 240    is_block_mode: bool,
 241}
 242
 243#[derive(Clone)]
 244struct AutoindentRequestEntry {
 245    /// A range of the buffer whose indentation should be adjusted.
 246    range: Range<Anchor>,
 247    /// Whether or not these lines should be considered brand new, for the
 248    /// purpose of auto-indent. When text is not new, its indentation will
 249    /// only be adjusted if the suggested indentation level has *changed*
 250    /// since the edit was made.
 251    first_line_is_new: bool,
 252    original_indent_column: Option<u32>,
 253}
 254
 255#[derive(Debug)]
 256struct IndentSuggestion {
 257    basis_row: u32,
 258    delta: Ordering,
 259}
 260
 261struct BufferChunkHighlights<'a> {
 262    captures: SyntaxMapCaptures<'a>,
 263    next_capture: Option<SyntaxMapCapture<'a>>,
 264    stack: Vec<(usize, HighlightId)>,
 265    highlight_maps: Vec<HighlightMap>,
 266}
 267
 268pub struct BufferChunks<'a> {
 269    range: Range<usize>,
 270    chunks: rope::Chunks<'a>,
 271    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 272    error_depth: usize,
 273    warning_depth: usize,
 274    information_depth: usize,
 275    hint_depth: usize,
 276    unnecessary_depth: usize,
 277    highlights: Option<BufferChunkHighlights<'a>>,
 278}
 279
 280#[derive(Clone, Copy, Debug, Default)]
 281pub struct Chunk<'a> {
 282    pub text: &'a str,
 283    pub syntax_highlight_id: Option<HighlightId>,
 284    pub highlight_style: Option<HighlightStyle>,
 285    pub diagnostic_severity: Option<DiagnosticSeverity>,
 286    pub is_unnecessary: bool,
 287}
 288
 289pub struct Diff {
 290    base_version: clock::Global,
 291    new_text: Arc<str>,
 292    changes: Vec<(ChangeTag, usize)>,
 293    line_ending: LineEnding,
 294    start_offset: usize,
 295}
 296
 297#[derive(Clone, Copy)]
 298pub(crate) struct DiagnosticEndpoint {
 299    offset: usize,
 300    is_start: bool,
 301    severity: DiagnosticSeverity,
 302    is_unnecessary: bool,
 303}
 304
 305#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug)]
 306pub enum CharKind {
 307    Punctuation,
 308    Whitespace,
 309    Word,
 310}
 311
 312impl CharKind {
 313    pub fn coerce_punctuation(self, treat_punctuation_as_word: bool) -> Self {
 314        if treat_punctuation_as_word && self == CharKind::Punctuation {
 315            CharKind::Word
 316        } else {
 317            self
 318        }
 319    }
 320}
 321
 322impl Buffer {
 323    pub fn new<T: Into<String>>(
 324        replica_id: ReplicaId,
 325        base_text: T,
 326        cx: &mut ModelContext<Self>,
 327    ) -> Self {
 328        Self::build(
 329            TextBuffer::new(replica_id, cx.model_id() as u64, base_text.into()),
 330            None,
 331        )
 332    }
 333
 334    pub fn from_file<T: Into<String>>(
 335        replica_id: ReplicaId,
 336        base_text: T,
 337        file: Arc<dyn File>,
 338        cx: &mut ModelContext<Self>,
 339    ) -> Self {
 340        Self::build(
 341            TextBuffer::new(replica_id, cx.model_id() as u64, base_text.into()),
 342            Some(file),
 343        )
 344    }
 345
 346    pub fn from_proto(
 347        replica_id: ReplicaId,
 348        message: proto::BufferState,
 349        file: Option<Arc<dyn File>>,
 350    ) -> Result<Self> {
 351        let buffer = TextBuffer::new(replica_id, message.id, message.base_text);
 352        let mut this = Self::build(buffer, file);
 353        this.text.set_line_ending(proto::deserialize_line_ending(
 354            proto::LineEnding::from_i32(message.line_ending)
 355                .ok_or_else(|| anyhow!("missing line_ending"))?,
 356        ));
 357        Ok(this)
 358    }
 359
 360    pub fn to_proto(&self) -> proto::BufferState {
 361        proto::BufferState {
 362            id: self.remote_id(),
 363            file: self.file.as_ref().map(|f| f.to_proto()),
 364            base_text: self.base_text().to_string(),
 365            line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
 366        }
 367    }
 368
 369    pub fn serialize_ops(&self, cx: &AppContext) -> Task<Vec<proto::Operation>> {
 370        let mut operations = Vec::new();
 371        operations.extend(self.deferred_ops.iter().map(proto::serialize_operation));
 372        operations.extend(self.remote_selections.iter().map(|(_, set)| {
 373            proto::serialize_operation(&Operation::UpdateSelections {
 374                selections: set.selections.clone(),
 375                lamport_timestamp: set.lamport_timestamp,
 376                line_mode: set.line_mode,
 377            })
 378        }));
 379        operations.push(proto::serialize_operation(&Operation::UpdateDiagnostics {
 380            diagnostics: self.diagnostics.iter().cloned().collect(),
 381            lamport_timestamp: self.diagnostics_timestamp,
 382        }));
 383        operations.push(proto::serialize_operation(
 384            &Operation::UpdateCompletionTriggers {
 385                triggers: self.completion_triggers.clone(),
 386                lamport_timestamp: self.completion_triggers_timestamp,
 387            },
 388        ));
 389
 390        let text_operations = self.text.operations().clone();
 391        cx.background().spawn(async move {
 392            operations.extend(
 393                text_operations
 394                    .iter()
 395                    .map(|(_, op)| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 396            );
 397            operations.sort_unstable_by_key(proto::lamport_timestamp_for_operation);
 398            operations
 399        })
 400    }
 401
 402    pub fn with_language(mut self, language: Arc<Language>, cx: &mut ModelContext<Self>) -> Self {
 403        self.set_language(Some(language), cx);
 404        self
 405    }
 406
 407    fn build(buffer: TextBuffer, file: Option<Arc<dyn File>>) -> Self {
 408        let saved_mtime = if let Some(file) = file.as_ref() {
 409            file.mtime()
 410        } else {
 411            UNIX_EPOCH
 412        };
 413
 414        Self {
 415            saved_mtime,
 416            saved_version: buffer.version(),
 417            saved_version_fingerprint: buffer.as_rope().fingerprint(),
 418            transaction_depth: 0,
 419            was_dirty_before_starting_transaction: None,
 420            text: buffer,
 421            file,
 422            syntax_map: Mutex::new(SyntaxMap::new()),
 423            parsing_in_background: false,
 424            parse_count: 0,
 425            sync_parse_timeout: Duration::from_millis(1),
 426            autoindent_requests: Default::default(),
 427            pending_autoindent: Default::default(),
 428            language: None,
 429            remote_selections: Default::default(),
 430            selections_update_count: 0,
 431            diagnostics: Default::default(),
 432            diagnostics_update_count: 0,
 433            diagnostics_timestamp: Default::default(),
 434            file_update_count: 0,
 435            completion_triggers: Default::default(),
 436            completion_triggers_timestamp: Default::default(),
 437            deferred_ops: OperationQueue::new(),
 438        }
 439    }
 440
 441    pub fn snapshot(&self) -> BufferSnapshot {
 442        let text = self.text.snapshot();
 443        let mut syntax_map = self.syntax_map.lock();
 444        syntax_map.interpolate(&text);
 445        let syntax = syntax_map.snapshot();
 446
 447        BufferSnapshot {
 448            text,
 449            syntax,
 450            file: self.file.clone(),
 451            remote_selections: self.remote_selections.clone(),
 452            diagnostics: self.diagnostics.clone(),
 453            diagnostics_update_count: self.diagnostics_update_count,
 454            file_update_count: self.file_update_count,
 455            language: self.language.clone(),
 456            parse_count: self.parse_count,
 457            selections_update_count: self.selections_update_count,
 458        }
 459    }
 460
 461    pub fn as_text_snapshot(&self) -> &text::BufferSnapshot {
 462        &self.text
 463    }
 464
 465    pub fn text_snapshot(&self) -> text::BufferSnapshot {
 466        self.text.snapshot()
 467    }
 468
 469    pub fn file(&self) -> Option<&dyn File> {
 470        self.file.as_deref()
 471    }
 472
 473    pub fn save(
 474        &mut self,
 475        cx: &mut ModelContext<Self>,
 476    ) -> Task<Result<(clock::Global, String, SystemTime)>> {
 477        let file = if let Some(file) = self.file.as_ref() {
 478            file
 479        } else {
 480            return Task::ready(Err(anyhow!("buffer has no file")));
 481        };
 482        let text = self.as_rope().clone();
 483        let version = self.version();
 484        let save = file.save(
 485            self.remote_id(),
 486            text,
 487            version,
 488            self.line_ending(),
 489            cx.as_mut(),
 490        );
 491        cx.spawn(|this, mut cx| async move {
 492            let (version, fingerprint, mtime) = save.await?;
 493            this.update(&mut cx, |this, cx| {
 494                this.did_save(version.clone(), fingerprint.clone(), mtime, None, cx);
 495            });
 496            Ok((version, fingerprint, mtime))
 497        })
 498    }
 499
 500    pub fn saved_version(&self) -> &clock::Global {
 501        &self.saved_version
 502    }
 503
 504    pub fn set_language(&mut self, language: Option<Arc<Language>>, cx: &mut ModelContext<Self>) {
 505        self.syntax_map.lock().clear();
 506        self.language = language;
 507        self.reparse(cx);
 508    }
 509
 510    pub fn set_language_registry(&mut self, language_registry: Arc<LanguageRegistry>) {
 511        self.syntax_map
 512            .lock()
 513            .set_language_registry(language_registry);
 514    }
 515
 516    pub fn did_save(
 517        &mut self,
 518        version: clock::Global,
 519        fingerprint: String,
 520        mtime: SystemTime,
 521        new_file: Option<Arc<dyn File>>,
 522        cx: &mut ModelContext<Self>,
 523    ) {
 524        self.saved_version = version;
 525        self.saved_version_fingerprint = fingerprint;
 526        self.saved_mtime = mtime;
 527        if let Some(new_file) = new_file {
 528            self.file = Some(new_file);
 529            self.file_update_count += 1;
 530        }
 531        cx.emit(Event::Saved);
 532        cx.notify();
 533    }
 534
 535    pub fn reload(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Option<Transaction>>> {
 536        cx.spawn(|this, mut cx| async move {
 537            if let Some((new_mtime, new_text)) = this.read_with(&cx, |this, cx| {
 538                let file = this.file.as_ref()?.as_local()?;
 539                Some((file.mtime(), file.load(cx)))
 540            }) {
 541                let new_text = new_text.await?;
 542                let diff = this
 543                    .read_with(&cx, |this, cx| this.diff(new_text, cx))
 544                    .await;
 545                this.update(&mut cx, |this, cx| {
 546                    if let Some(transaction) = this.apply_diff(diff, cx).cloned() {
 547                        this.did_reload(
 548                            this.version(),
 549                            this.as_rope().fingerprint(),
 550                            this.line_ending(),
 551                            new_mtime,
 552                            cx,
 553                        );
 554                        Ok(Some(transaction))
 555                    } else {
 556                        Ok(None)
 557                    }
 558                })
 559            } else {
 560                Ok(None)
 561            }
 562        })
 563    }
 564
 565    pub fn did_reload(
 566        &mut self,
 567        version: clock::Global,
 568        fingerprint: String,
 569        line_ending: LineEnding,
 570        mtime: SystemTime,
 571        cx: &mut ModelContext<Self>,
 572    ) {
 573        self.saved_version = version;
 574        self.saved_version_fingerprint = fingerprint;
 575        self.text.set_line_ending(line_ending);
 576        self.saved_mtime = mtime;
 577        if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
 578            file.buffer_reloaded(
 579                self.remote_id(),
 580                &self.saved_version,
 581                self.saved_version_fingerprint.clone(),
 582                self.line_ending(),
 583                self.saved_mtime,
 584                cx,
 585            );
 586        }
 587        cx.emit(Event::Reloaded);
 588        cx.notify();
 589    }
 590
 591    pub fn file_updated(
 592        &mut self,
 593        new_file: Arc<dyn File>,
 594        cx: &mut ModelContext<Self>,
 595    ) -> Task<()> {
 596        let old_file = if let Some(file) = self.file.as_ref() {
 597            file
 598        } else {
 599            return Task::ready(());
 600        };
 601        let mut file_changed = false;
 602        let mut task = Task::ready(());
 603
 604        if new_file.path() != old_file.path() {
 605            file_changed = true;
 606        }
 607
 608        if new_file.is_deleted() {
 609            if !old_file.is_deleted() {
 610                file_changed = true;
 611                if !self.is_dirty() {
 612                    cx.emit(Event::DirtyChanged);
 613                }
 614            }
 615        } else {
 616            let new_mtime = new_file.mtime();
 617            if new_mtime != old_file.mtime() {
 618                file_changed = true;
 619
 620                if !self.is_dirty() {
 621                    let reload = self.reload(cx).log_err().map(drop);
 622                    task = cx.foreground().spawn(reload);
 623                }
 624            }
 625        }
 626
 627        if file_changed {
 628            self.file_update_count += 1;
 629            cx.emit(Event::FileHandleChanged);
 630            cx.notify();
 631        }
 632        self.file = Some(new_file);
 633        task
 634    }
 635
 636    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 637        cx.emit(Event::Closed);
 638    }
 639
 640    pub fn language(&self) -> Option<&Arc<Language>> {
 641        self.language.as_ref()
 642    }
 643
 644    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<Arc<Language>> {
 645        let offset = position.to_offset(self);
 646        self.syntax_map
 647            .lock()
 648            .layers_for_range(offset..offset, &self.text)
 649            .last()
 650            .map(|info| info.language.clone())
 651            .or_else(|| self.language.clone())
 652    }
 653
 654    pub fn parse_count(&self) -> usize {
 655        self.parse_count
 656    }
 657
 658    pub fn selections_update_count(&self) -> usize {
 659        self.selections_update_count
 660    }
 661
 662    pub fn diagnostics_update_count(&self) -> usize {
 663        self.diagnostics_update_count
 664    }
 665
 666    pub fn file_update_count(&self) -> usize {
 667        self.file_update_count
 668    }
 669
 670    #[cfg(any(test, feature = "test-support"))]
 671    pub fn is_parsing(&self) -> bool {
 672        self.parsing_in_background
 673    }
 674
 675    #[cfg(test)]
 676    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 677        self.sync_parse_timeout = timeout;
 678    }
 679
 680    fn reparse(&mut self, cx: &mut ModelContext<Self>) {
 681        if self.parsing_in_background {
 682            return;
 683        }
 684        let language = if let Some(language) = self.language.clone() {
 685            language
 686        } else {
 687            return;
 688        };
 689
 690        let text = self.text_snapshot();
 691        let parsed_version = self.version();
 692
 693        let mut syntax_map = self.syntax_map.lock();
 694        syntax_map.interpolate(&text);
 695        let language_registry = syntax_map.language_registry();
 696        let mut syntax_snapshot = syntax_map.snapshot();
 697        let syntax_map_version = syntax_map.parsed_version();
 698        drop(syntax_map);
 699
 700        let parse_task = cx.background().spawn({
 701            let language = language.clone();
 702            async move {
 703                syntax_snapshot.reparse(&syntax_map_version, &text, language_registry, language);
 704                syntax_snapshot
 705            }
 706        });
 707
 708        match cx
 709            .background()
 710            .block_with_timeout(self.sync_parse_timeout, parse_task)
 711        {
 712            Ok(new_syntax_snapshot) => {
 713                self.did_finish_parsing(new_syntax_snapshot, parsed_version, cx);
 714                return;
 715            }
 716            Err(parse_task) => {
 717                self.parsing_in_background = true;
 718                cx.spawn(move |this, mut cx| async move {
 719                    let new_syntax_map = parse_task.await;
 720                    this.update(&mut cx, move |this, cx| {
 721                        let grammar_changed =
 722                            this.language.as_ref().map_or(true, |current_language| {
 723                                !Arc::ptr_eq(&language, current_language)
 724                            });
 725                        let parse_again =
 726                            this.version.changed_since(&parsed_version) || grammar_changed;
 727                        this.did_finish_parsing(new_syntax_map, parsed_version, cx);
 728                        this.parsing_in_background = false;
 729                        if parse_again {
 730                            this.reparse(cx);
 731                        }
 732                    });
 733                })
 734                .detach();
 735            }
 736        }
 737    }
 738
 739    fn did_finish_parsing(
 740        &mut self,
 741        syntax_snapshot: SyntaxSnapshot,
 742        version: clock::Global,
 743        cx: &mut ModelContext<Self>,
 744    ) {
 745        self.parse_count += 1;
 746        self.syntax_map.lock().did_parse(syntax_snapshot, version);
 747        self.request_autoindent(cx);
 748        cx.emit(Event::Reparsed);
 749        cx.notify();
 750    }
 751
 752    pub fn update_diagnostics(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
 753        let lamport_timestamp = self.text.lamport_clock.tick();
 754        let op = Operation::UpdateDiagnostics {
 755            diagnostics: diagnostics.iter().cloned().collect(),
 756            lamport_timestamp,
 757        };
 758        self.apply_diagnostic_update(diagnostics, lamport_timestamp, cx);
 759        self.send_operation(op, cx);
 760    }
 761
 762    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 763        if let Some(indent_sizes) = self.compute_autoindents() {
 764            let indent_sizes = cx.background().spawn(indent_sizes);
 765            match cx
 766                .background()
 767                .block_with_timeout(Duration::from_micros(500), indent_sizes)
 768            {
 769                Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
 770                Err(indent_sizes) => {
 771                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 772                        let indent_sizes = indent_sizes.await;
 773                        this.update(&mut cx, |this, cx| {
 774                            this.apply_autoindents(indent_sizes, cx);
 775                        });
 776                    }));
 777                }
 778            }
 779        }
 780    }
 781
 782    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
 783        let max_rows_between_yields = 100;
 784        let snapshot = self.snapshot();
 785        if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
 786            return None;
 787        }
 788
 789        let autoindent_requests = self.autoindent_requests.clone();
 790        Some(async move {
 791            let mut indent_sizes = BTreeMap::new();
 792            for request in autoindent_requests {
 793                // Resolve each edited range to its row in the current buffer and in the
 794                // buffer before this batch of edits.
 795                let mut row_ranges = Vec::new();
 796                let mut old_to_new_rows = BTreeMap::new();
 797                for entry in &request.entries {
 798                    let position = entry.range.start;
 799                    let new_row = position.to_point(&snapshot).row;
 800                    let new_end_row = entry.range.end.to_point(&snapshot).row + 1;
 801                    if !entry.first_line_is_new {
 802                        let old_row = position.to_point(&request.before_edit).row;
 803                        old_to_new_rows.insert(old_row, new_row);
 804                    }
 805                    row_ranges.push((new_row..new_end_row, entry.original_indent_column));
 806                }
 807
 808                // Build a map containing the suggested indentation for each of the edited lines
 809                // with respect to the state of the buffer before these edits. This map is keyed
 810                // by the rows for these lines in the current state of the buffer.
 811                let mut old_suggestions = BTreeMap::<u32, IndentSize>::default();
 812                let old_edited_ranges =
 813                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 814                for old_edited_range in old_edited_ranges {
 815                    let suggestions = request
 816                        .before_edit
 817                        .suggest_autoindents(old_edited_range.clone())
 818                        .into_iter()
 819                        .flatten();
 820                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 821                        if let Some(suggestion) = suggestion {
 822                            let suggested_indent = old_to_new_rows
 823                                .get(&suggestion.basis_row)
 824                                .and_then(|from_row| old_suggestions.get(from_row).copied())
 825                                .unwrap_or_else(|| {
 826                                    request
 827                                        .before_edit
 828                                        .indent_size_for_line(suggestion.basis_row)
 829                                })
 830                                .with_delta(suggestion.delta, request.indent_size);
 831                            old_suggestions
 832                                .insert(*old_to_new_rows.get(&old_row).unwrap(), suggested_indent);
 833                        }
 834                    }
 835                    yield_now().await;
 836                }
 837
 838                // In block mode, only compute indentation suggestions for the first line
 839                // of each insertion. Otherwise, compute suggestions for every inserted line.
 840                let new_edited_row_ranges = contiguous_ranges(
 841                    row_ranges.iter().flat_map(|(range, _)| {
 842                        if request.is_block_mode {
 843                            range.start..range.start + 1
 844                        } else {
 845                            range.clone()
 846                        }
 847                    }),
 848                    max_rows_between_yields,
 849                );
 850
 851                // Compute new suggestions for each line, but only include them in the result
 852                // if they differ from the old suggestion for that line.
 853                for new_edited_row_range in new_edited_row_ranges {
 854                    let suggestions = snapshot
 855                        .suggest_autoindents(new_edited_row_range.clone())
 856                        .into_iter()
 857                        .flatten();
 858                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 859                        if let Some(suggestion) = suggestion {
 860                            let suggested_indent = indent_sizes
 861                                .get(&suggestion.basis_row)
 862                                .copied()
 863                                .unwrap_or_else(|| {
 864                                    snapshot.indent_size_for_line(suggestion.basis_row)
 865                                })
 866                                .with_delta(suggestion.delta, request.indent_size);
 867                            if old_suggestions
 868                                .get(&new_row)
 869                                .map_or(true, |old_indentation| {
 870                                    suggested_indent != *old_indentation
 871                                })
 872                            {
 873                                indent_sizes.insert(new_row, suggested_indent);
 874                            }
 875                        }
 876                    }
 877                    yield_now().await;
 878                }
 879
 880                // For each block of inserted text, adjust the indentation of the remaining
 881                // lines of the block by the same amount as the first line was adjusted.
 882                if request.is_block_mode {
 883                    for (row_range, original_indent_column) in
 884                        row_ranges
 885                            .into_iter()
 886                            .filter_map(|(range, original_indent_column)| {
 887                                if range.len() > 1 {
 888                                    Some((range, original_indent_column?))
 889                                } else {
 890                                    None
 891                                }
 892                            })
 893                    {
 894                        let new_indent = indent_sizes
 895                            .get(&row_range.start)
 896                            .copied()
 897                            .unwrap_or_else(|| snapshot.indent_size_for_line(row_range.start));
 898                        let delta = new_indent.len as i64 - original_indent_column as i64;
 899                        if delta != 0 {
 900                            for row in row_range.skip(1) {
 901                                indent_sizes.entry(row).or_insert_with(|| {
 902                                    let mut size = snapshot.indent_size_for_line(row);
 903                                    if size.kind == new_indent.kind {
 904                                        match delta.cmp(&0) {
 905                                            Ordering::Greater => size.len += delta as u32,
 906                                            Ordering::Less => {
 907                                                size.len = size.len.saturating_sub(-delta as u32)
 908                                            }
 909                                            Ordering::Equal => {}
 910                                        }
 911                                    }
 912                                    size
 913                                });
 914                            }
 915                        }
 916                    }
 917                }
 918            }
 919
 920            indent_sizes
 921        })
 922    }
 923
 924    fn apply_autoindents(
 925        &mut self,
 926        indent_sizes: BTreeMap<u32, IndentSize>,
 927        cx: &mut ModelContext<Self>,
 928    ) {
 929        self.autoindent_requests.clear();
 930
 931        let edits: Vec<_> = indent_sizes
 932            .into_iter()
 933            .filter_map(|(row, indent_size)| {
 934                let current_size = indent_size_for_line(self, row);
 935                Self::edit_for_indent_size_adjustment(row, current_size, indent_size)
 936            })
 937            .collect();
 938
 939        self.edit(edits, None, cx);
 940    }
 941
 942    pub fn edit_for_indent_size_adjustment(
 943        row: u32,
 944        current_size: IndentSize,
 945        new_size: IndentSize,
 946    ) -> Option<(Range<Point>, String)> {
 947        if new_size.kind != current_size.kind && current_size.len > 0 {
 948            return None;
 949        }
 950
 951        match new_size.len.cmp(&current_size.len) {
 952            Ordering::Greater => {
 953                let point = Point::new(row, 0);
 954                Some((
 955                    point..point,
 956                    iter::repeat(new_size.char())
 957                        .take((new_size.len - current_size.len) as usize)
 958                        .collect::<String>(),
 959                ))
 960            }
 961
 962            Ordering::Less => Some((
 963                Point::new(row, 0)..Point::new(row, current_size.len - new_size.len),
 964                String::new(),
 965            )),
 966
 967            Ordering::Equal => None,
 968        }
 969    }
 970
 971    pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
 972        let old_text = self.as_rope().clone();
 973        let base_version = self.version();
 974        cx.background().spawn(async move {
 975            let old_text = old_text.to_string();
 976            let line_ending = LineEnding::detect(&new_text);
 977            LineEnding::normalize(&mut new_text);
 978            let changes = TextDiff::from_chars(old_text.as_str(), new_text.as_str())
 979                .iter_all_changes()
 980                .map(|c| (c.tag(), c.value().len()))
 981                .collect::<Vec<_>>();
 982            Diff {
 983                base_version,
 984                new_text: new_text.into(),
 985                changes,
 986                line_ending,
 987                start_offset: 0,
 988            }
 989        })
 990    }
 991
 992    pub fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> Option<&Transaction> {
 993        if self.version == diff.base_version {
 994            self.finalize_last_transaction();
 995            self.start_transaction();
 996            self.text.set_line_ending(diff.line_ending);
 997            let mut offset = diff.start_offset;
 998            for (tag, len) in diff.changes {
 999                let range = offset..(offset + len);
1000                match tag {
1001                    ChangeTag::Equal => offset += len,
1002                    ChangeTag::Delete => {
1003                        self.edit([(range, "")], None, cx);
1004                    }
1005                    ChangeTag::Insert => {
1006                        self.edit(
1007                            [(
1008                                offset..offset,
1009                                &diff.new_text[range.start - diff.start_offset
1010                                    ..range.end - diff.start_offset],
1011                            )],
1012                            None,
1013                            cx,
1014                        );
1015                        offset += len;
1016                    }
1017                }
1018            }
1019            if self.end_transaction(cx).is_some() {
1020                self.finalize_last_transaction()
1021            } else {
1022                None
1023            }
1024        } else {
1025            None
1026        }
1027    }
1028
1029    pub fn is_dirty(&self) -> bool {
1030        self.saved_version_fingerprint != self.as_rope().fingerprint()
1031            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1032    }
1033
1034    pub fn has_conflict(&self) -> bool {
1035        self.saved_version_fingerprint != self.as_rope().fingerprint()
1036            && self
1037                .file
1038                .as_ref()
1039                .map_or(false, |file| file.mtime() > self.saved_mtime)
1040    }
1041
1042    pub fn subscribe(&mut self) -> Subscription {
1043        self.text.subscribe()
1044    }
1045
1046    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1047        self.start_transaction_at(Instant::now())
1048    }
1049
1050    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1051        self.transaction_depth += 1;
1052        if self.was_dirty_before_starting_transaction.is_none() {
1053            self.was_dirty_before_starting_transaction = Some(self.is_dirty());
1054        }
1055        self.text.start_transaction_at(now)
1056    }
1057
1058    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1059        self.end_transaction_at(Instant::now(), cx)
1060    }
1061
1062    pub fn end_transaction_at(
1063        &mut self,
1064        now: Instant,
1065        cx: &mut ModelContext<Self>,
1066    ) -> Option<TransactionId> {
1067        assert!(self.transaction_depth > 0);
1068        self.transaction_depth -= 1;
1069        let was_dirty = if self.transaction_depth == 0 {
1070            self.was_dirty_before_starting_transaction.take().unwrap()
1071        } else {
1072            false
1073        };
1074        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1075            self.did_edit(&start_version, was_dirty, cx);
1076            Some(transaction_id)
1077        } else {
1078            None
1079        }
1080    }
1081
1082    pub fn push_transaction(&mut self, transaction: Transaction, now: Instant) {
1083        self.text.push_transaction(transaction, now);
1084    }
1085
1086    pub fn finalize_last_transaction(&mut self) -> Option<&Transaction> {
1087        self.text.finalize_last_transaction()
1088    }
1089
1090    pub fn group_until_transaction(&mut self, transaction_id: TransactionId) {
1091        self.text.group_until_transaction(transaction_id);
1092    }
1093
1094    pub fn forget_transaction(&mut self, transaction_id: TransactionId) {
1095        self.text.forget_transaction(transaction_id);
1096    }
1097
1098    pub fn wait_for_edits(
1099        &mut self,
1100        edit_ids: impl IntoIterator<Item = clock::Local>,
1101    ) -> impl Future<Output = ()> {
1102        self.text.wait_for_edits(edit_ids)
1103    }
1104
1105    pub fn wait_for_anchors<'a>(
1106        &mut self,
1107        anchors: impl IntoIterator<Item = &'a Anchor>,
1108    ) -> impl Future<Output = ()> {
1109        self.text.wait_for_anchors(anchors)
1110    }
1111
1112    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = ()> {
1113        self.text.wait_for_version(version)
1114    }
1115
1116    pub fn set_active_selections(
1117        &mut self,
1118        selections: Arc<[Selection<Anchor>]>,
1119        line_mode: bool,
1120        cx: &mut ModelContext<Self>,
1121    ) {
1122        let lamport_timestamp = self.text.lamport_clock.tick();
1123        self.remote_selections.insert(
1124            self.text.replica_id(),
1125            SelectionSet {
1126                selections: selections.clone(),
1127                lamport_timestamp,
1128                line_mode,
1129            },
1130        );
1131        self.send_operation(
1132            Operation::UpdateSelections {
1133                selections,
1134                line_mode,
1135                lamport_timestamp,
1136            },
1137            cx,
1138        );
1139    }
1140
1141    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1142        self.set_active_selections(Arc::from([]), false, cx);
1143    }
1144
1145    pub fn set_text<T>(&mut self, text: T, cx: &mut ModelContext<Self>) -> Option<clock::Local>
1146    where
1147        T: Into<Arc<str>>,
1148    {
1149        self.edit([(0..self.len(), text)], None, cx)
1150    }
1151
1152    pub fn edit<I, S, T>(
1153        &mut self,
1154        edits_iter: I,
1155        autoindent_mode: Option<AutoindentMode>,
1156        cx: &mut ModelContext<Self>,
1157    ) -> Option<clock::Local>
1158    where
1159        I: IntoIterator<Item = (Range<S>, T)>,
1160        S: ToOffset,
1161        T: Into<Arc<str>>,
1162    {
1163        // Skip invalid edits and coalesce contiguous ones.
1164        let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
1165        for (range, new_text) in edits_iter {
1166            let mut range = range.start.to_offset(self)..range.end.to_offset(self);
1167            if range.start > range.end {
1168                mem::swap(&mut range.start, &mut range.end);
1169            }
1170            let new_text = new_text.into();
1171            if !new_text.is_empty() || !range.is_empty() {
1172                if let Some((prev_range, prev_text)) = edits.last_mut() {
1173                    if prev_range.end >= range.start {
1174                        prev_range.end = cmp::max(prev_range.end, range.end);
1175                        *prev_text = format!("{prev_text}{new_text}").into();
1176                    } else {
1177                        edits.push((range, new_text));
1178                    }
1179                } else {
1180                    edits.push((range, new_text));
1181                }
1182            }
1183        }
1184        if edits.is_empty() {
1185            return None;
1186        }
1187
1188        self.start_transaction();
1189        self.pending_autoindent.take();
1190        let autoindent_request = autoindent_mode
1191            .and_then(|mode| self.language.as_ref().map(|_| (self.snapshot(), mode)));
1192
1193        let edit_operation = self.text.edit(edits.iter().cloned());
1194        let edit_id = edit_operation.local_timestamp();
1195
1196        if let Some((before_edit, mode)) = autoindent_request {
1197            let indent_size = before_edit.single_indent_size(cx);
1198            let (start_columns, is_block_mode) = match mode {
1199                AutoindentMode::Block {
1200                    original_indent_columns: start_columns,
1201                } => (start_columns, true),
1202                AutoindentMode::EachLine => (Default::default(), false),
1203            };
1204
1205            let mut delta = 0isize;
1206            let entries = edits
1207                .into_iter()
1208                .enumerate()
1209                .zip(&edit_operation.as_edit().unwrap().new_text)
1210                .map(|((ix, (range, _)), new_text)| {
1211                    let new_text_len = new_text.len();
1212                    let old_start = range.start.to_point(&before_edit);
1213                    let new_start = (delta + range.start as isize) as usize;
1214                    delta += new_text_len as isize - (range.end as isize - range.start as isize);
1215
1216                    let mut range_of_insertion_to_indent = 0..new_text_len;
1217                    let mut first_line_is_new = false;
1218                    let mut start_column = None;
1219
1220                    // When inserting an entire line at the beginning of an existing line,
1221                    // treat the insertion as new.
1222                    if new_text.contains('\n')
1223                        && old_start.column <= before_edit.indent_size_for_line(old_start.row).len
1224                    {
1225                        first_line_is_new = true;
1226                    }
1227
1228                    // When inserting text starting with a newline, avoid auto-indenting the
1229                    // previous line.
1230                    if new_text[range_of_insertion_to_indent.clone()].starts_with('\n') {
1231                        range_of_insertion_to_indent.start += 1;
1232                        first_line_is_new = true;
1233                    }
1234
1235                    // Avoid auto-indenting after the insertion.
1236                    if is_block_mode {
1237                        start_column = start_columns.get(ix).copied();
1238                        if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') {
1239                            range_of_insertion_to_indent.end -= 1;
1240                        }
1241                    }
1242
1243                    AutoindentRequestEntry {
1244                        first_line_is_new,
1245                        original_indent_column: start_column,
1246                        range: self.anchor_before(new_start + range_of_insertion_to_indent.start)
1247                            ..self.anchor_after(new_start + range_of_insertion_to_indent.end),
1248                    }
1249                })
1250                .collect();
1251
1252            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1253                before_edit,
1254                entries,
1255                indent_size,
1256                is_block_mode,
1257            }));
1258        }
1259
1260        self.end_transaction(cx);
1261        self.send_operation(Operation::Buffer(edit_operation), cx);
1262        Some(edit_id)
1263    }
1264
1265    fn did_edit(
1266        &mut self,
1267        old_version: &clock::Global,
1268        was_dirty: bool,
1269        cx: &mut ModelContext<Self>,
1270    ) {
1271        if self.edits_since::<usize>(old_version).next().is_none() {
1272            return;
1273        }
1274
1275        self.reparse(cx);
1276
1277        cx.emit(Event::Edited);
1278        if was_dirty != self.is_dirty() {
1279            cx.emit(Event::DirtyChanged);
1280        }
1281        cx.notify();
1282    }
1283
1284    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1285        &mut self,
1286        ops: I,
1287        cx: &mut ModelContext<Self>,
1288    ) -> Result<()> {
1289        self.pending_autoindent.take();
1290        let was_dirty = self.is_dirty();
1291        let old_version = self.version.clone();
1292        let mut deferred_ops = Vec::new();
1293        let buffer_ops = ops
1294            .into_iter()
1295            .filter_map(|op| match op {
1296                Operation::Buffer(op) => Some(op),
1297                _ => {
1298                    if self.can_apply_op(&op) {
1299                        self.apply_op(op, cx);
1300                    } else {
1301                        deferred_ops.push(op);
1302                    }
1303                    None
1304                }
1305            })
1306            .collect::<Vec<_>>();
1307        self.text.apply_ops(buffer_ops)?;
1308        self.deferred_ops.insert(deferred_ops);
1309        self.flush_deferred_ops(cx);
1310        self.did_edit(&old_version, was_dirty, cx);
1311        // Notify independently of whether the buffer was edited as the operations could include a
1312        // selection update.
1313        cx.notify();
1314        Ok(())
1315    }
1316
1317    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1318        let mut deferred_ops = Vec::new();
1319        for op in self.deferred_ops.drain().iter().cloned() {
1320            if self.can_apply_op(&op) {
1321                self.apply_op(op, cx);
1322            } else {
1323                deferred_ops.push(op);
1324            }
1325        }
1326        self.deferred_ops.insert(deferred_ops);
1327    }
1328
1329    fn can_apply_op(&self, operation: &Operation) -> bool {
1330        match operation {
1331            Operation::Buffer(_) => {
1332                unreachable!("buffer operations should never be applied at this layer")
1333            }
1334            Operation::UpdateDiagnostics {
1335                diagnostics: diagnostic_set,
1336                ..
1337            } => diagnostic_set.iter().all(|diagnostic| {
1338                self.text.can_resolve(&diagnostic.range.start)
1339                    && self.text.can_resolve(&diagnostic.range.end)
1340            }),
1341            Operation::UpdateSelections { selections, .. } => selections
1342                .iter()
1343                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1344            Operation::UpdateCompletionTriggers { .. } => true,
1345        }
1346    }
1347
1348    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
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                lamport_timestamp,
1356            } => {
1357                let snapshot = self.snapshot();
1358                self.apply_diagnostic_update(
1359                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1360                    lamport_timestamp,
1361                    cx,
1362                );
1363            }
1364            Operation::UpdateSelections {
1365                selections,
1366                lamport_timestamp,
1367                line_mode,
1368            } => {
1369                if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) {
1370                    if set.lamport_timestamp > lamport_timestamp {
1371                        return;
1372                    }
1373                }
1374
1375                self.remote_selections.insert(
1376                    lamport_timestamp.replica_id,
1377                    SelectionSet {
1378                        selections,
1379                        lamport_timestamp,
1380                        line_mode,
1381                    },
1382                );
1383                self.text.lamport_clock.observe(lamport_timestamp);
1384                self.selections_update_count += 1;
1385            }
1386            Operation::UpdateCompletionTriggers {
1387                triggers,
1388                lamport_timestamp,
1389            } => {
1390                self.completion_triggers = triggers;
1391                self.text.lamport_clock.observe(lamport_timestamp);
1392            }
1393        }
1394    }
1395
1396    fn apply_diagnostic_update(
1397        &mut self,
1398        diagnostics: DiagnosticSet,
1399        lamport_timestamp: clock::Lamport,
1400        cx: &mut ModelContext<Self>,
1401    ) {
1402        if lamport_timestamp > self.diagnostics_timestamp {
1403            self.diagnostics = diagnostics;
1404            self.diagnostics_timestamp = lamport_timestamp;
1405            self.diagnostics_update_count += 1;
1406            self.text.lamport_clock.observe(lamport_timestamp);
1407            cx.notify();
1408            cx.emit(Event::DiagnosticsUpdated);
1409        }
1410    }
1411
1412    fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1413        cx.emit(Event::Operation(operation));
1414    }
1415
1416    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1417        self.remote_selections.remove(&replica_id);
1418        cx.notify();
1419    }
1420
1421    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1422        let was_dirty = self.is_dirty();
1423        let old_version = self.version.clone();
1424
1425        if let Some((transaction_id, operation)) = self.text.undo() {
1426            self.send_operation(Operation::Buffer(operation), cx);
1427            self.did_edit(&old_version, was_dirty, cx);
1428            Some(transaction_id)
1429        } else {
1430            None
1431        }
1432    }
1433
1434    pub fn undo_to_transaction(
1435        &mut self,
1436        transaction_id: TransactionId,
1437        cx: &mut ModelContext<Self>,
1438    ) -> bool {
1439        let was_dirty = self.is_dirty();
1440        let old_version = self.version.clone();
1441
1442        let operations = self.text.undo_to_transaction(transaction_id);
1443        let undone = !operations.is_empty();
1444        for operation in operations {
1445            self.send_operation(Operation::Buffer(operation), cx);
1446        }
1447        if undone {
1448            self.did_edit(&old_version, was_dirty, cx)
1449        }
1450        undone
1451    }
1452
1453    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1454        let was_dirty = self.is_dirty();
1455        let old_version = self.version.clone();
1456
1457        if let Some((transaction_id, operation)) = self.text.redo() {
1458            self.send_operation(Operation::Buffer(operation), cx);
1459            self.did_edit(&old_version, was_dirty, cx);
1460            Some(transaction_id)
1461        } else {
1462            None
1463        }
1464    }
1465
1466    pub fn redo_to_transaction(
1467        &mut self,
1468        transaction_id: TransactionId,
1469        cx: &mut ModelContext<Self>,
1470    ) -> bool {
1471        let was_dirty = self.is_dirty();
1472        let old_version = self.version.clone();
1473
1474        let operations = self.text.redo_to_transaction(transaction_id);
1475        let redone = !operations.is_empty();
1476        for operation in operations {
1477            self.send_operation(Operation::Buffer(operation), cx);
1478        }
1479        if redone {
1480            self.did_edit(&old_version, was_dirty, cx)
1481        }
1482        redone
1483    }
1484
1485    pub fn set_completion_triggers(&mut self, triggers: Vec<String>, cx: &mut ModelContext<Self>) {
1486        self.completion_triggers = triggers.clone();
1487        self.completion_triggers_timestamp = self.text.lamport_clock.tick();
1488        self.send_operation(
1489            Operation::UpdateCompletionTriggers {
1490                triggers,
1491                lamport_timestamp: self.completion_triggers_timestamp,
1492            },
1493            cx,
1494        );
1495        cx.notify();
1496    }
1497
1498    pub fn completion_triggers(&self) -> &[String] {
1499        &self.completion_triggers
1500    }
1501}
1502
1503#[cfg(any(test, feature = "test-support"))]
1504impl Buffer {
1505    pub fn set_group_interval(&mut self, group_interval: Duration) {
1506        self.text.set_group_interval(group_interval);
1507    }
1508
1509    pub fn randomly_edit<T>(
1510        &mut self,
1511        rng: &mut T,
1512        old_range_count: usize,
1513        cx: &mut ModelContext<Self>,
1514    ) where
1515        T: rand::Rng,
1516    {
1517        let mut edits: Vec<(Range<usize>, String)> = Vec::new();
1518        let mut last_end = None;
1519        for _ in 0..old_range_count {
1520            if last_end.map_or(false, |last_end| last_end >= self.len()) {
1521                break;
1522            }
1523
1524            let new_start = last_end.map_or(0, |last_end| last_end + 1);
1525            let mut range = self.random_byte_range(new_start, rng);
1526            if rng.gen_bool(0.2) {
1527                mem::swap(&mut range.start, &mut range.end);
1528            }
1529            last_end = Some(range.end);
1530
1531            let new_text_len = rng.gen_range(0..10);
1532            let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1533                .take(new_text_len)
1534                .collect();
1535
1536            edits.push((range, new_text));
1537        }
1538        log::info!("mutating buffer {} with {:?}", self.replica_id(), edits);
1539        self.edit(edits, None, cx);
1540    }
1541
1542    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1543        let was_dirty = self.is_dirty();
1544        let old_version = self.version.clone();
1545
1546        let ops = self.text.randomly_undo_redo(rng);
1547        if !ops.is_empty() {
1548            for op in ops {
1549                self.send_operation(Operation::Buffer(op), cx);
1550                self.did_edit(&old_version, was_dirty, cx);
1551            }
1552        }
1553    }
1554}
1555
1556impl Entity for Buffer {
1557    type Event = Event;
1558}
1559
1560impl Deref for Buffer {
1561    type Target = TextBuffer;
1562
1563    fn deref(&self) -> &Self::Target {
1564        &self.text
1565    }
1566}
1567
1568impl BufferSnapshot {
1569    pub fn indent_size_for_line(&self, row: u32) -> IndentSize {
1570        indent_size_for_line(self, row)
1571    }
1572
1573    pub fn single_indent_size(&self, cx: &AppContext) -> IndentSize {
1574        let language_name = self.language().map(|language| language.name());
1575        let settings = cx.global::<Settings>();
1576        if settings.hard_tabs(language_name.as_deref()) {
1577            IndentSize::tab()
1578        } else {
1579            IndentSize::spaces(settings.tab_size(language_name.as_deref()).get())
1580        }
1581    }
1582
1583    pub fn suggested_indents(
1584        &self,
1585        rows: impl Iterator<Item = u32>,
1586        single_indent_size: IndentSize,
1587    ) -> BTreeMap<u32, IndentSize> {
1588        let mut result = BTreeMap::new();
1589
1590        for row_range in contiguous_ranges(rows, 10) {
1591            let suggestions = match self.suggest_autoindents(row_range.clone()) {
1592                Some(suggestions) => suggestions,
1593                _ => break,
1594            };
1595
1596            for (row, suggestion) in row_range.zip(suggestions) {
1597                let indent_size = if let Some(suggestion) = suggestion {
1598                    result
1599                        .get(&suggestion.basis_row)
1600                        .copied()
1601                        .unwrap_or_else(|| self.indent_size_for_line(suggestion.basis_row))
1602                        .with_delta(suggestion.delta, single_indent_size)
1603                } else {
1604                    self.indent_size_for_line(row)
1605                };
1606
1607                result.insert(row, indent_size);
1608            }
1609        }
1610
1611        result
1612    }
1613
1614    fn suggest_autoindents(
1615        &self,
1616        row_range: Range<u32>,
1617    ) -> Option<impl Iterator<Item = Option<IndentSuggestion>> + '_> {
1618        let config = &self.language.as_ref()?.config;
1619        let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1620
1621        // Find the suggested indentation ranges based on the syntax tree.
1622        let start = Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0);
1623        let end = Point::new(row_range.end, 0);
1624        let range = (start..end).to_offset(&self.text);
1625        let mut matches = self.syntax.matches(range, &self.text, |grammar| {
1626            Some(&grammar.indents_config.as_ref()?.query)
1627        });
1628        let indent_configs = matches
1629            .grammars()
1630            .iter()
1631            .map(|grammar| grammar.indents_config.as_ref().unwrap())
1632            .collect::<Vec<_>>();
1633
1634        let mut indent_ranges = Vec::<Range<Point>>::new();
1635        while let Some(mat) = matches.peek() {
1636            let mut start: Option<Point> = None;
1637            let mut end: Option<Point> = None;
1638
1639            let config = &indent_configs[mat.grammar_index];
1640            for capture in mat.captures {
1641                if capture.index == config.indent_capture_ix {
1642                    start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1643                    end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1644                } else if Some(capture.index) == config.start_capture_ix {
1645                    start = Some(Point::from_ts_point(capture.node.end_position()));
1646                } else if Some(capture.index) == config.end_capture_ix {
1647                    end = Some(Point::from_ts_point(capture.node.start_position()));
1648                }
1649            }
1650
1651            matches.advance();
1652            if let Some((start, end)) = start.zip(end) {
1653                if start.row == end.row {
1654                    continue;
1655                }
1656
1657                let range = start..end;
1658                match indent_ranges.binary_search_by_key(&range.start, |r| r.start) {
1659                    Err(ix) => indent_ranges.insert(ix, range),
1660                    Ok(ix) => {
1661                        let prev_range = &mut indent_ranges[ix];
1662                        prev_range.end = prev_range.end.max(range.end);
1663                    }
1664                }
1665            }
1666        }
1667
1668        // Find the suggested indentation increases and decreased based on regexes.
1669        let mut indent_change_rows = Vec::<(u32, Ordering)>::new();
1670        self.for_each_line(
1671            Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0)
1672                ..Point::new(row_range.end, 0),
1673            |row, line| {
1674                if config
1675                    .decrease_indent_pattern
1676                    .as_ref()
1677                    .map_or(false, |regex| regex.is_match(line))
1678                {
1679                    indent_change_rows.push((row, Ordering::Less));
1680                }
1681                if config
1682                    .increase_indent_pattern
1683                    .as_ref()
1684                    .map_or(false, |regex| regex.is_match(line))
1685                {
1686                    indent_change_rows.push((row + 1, Ordering::Greater));
1687                }
1688            },
1689        );
1690
1691        let mut indent_changes = indent_change_rows.into_iter().peekable();
1692        let mut prev_row = if config.auto_indent_using_last_non_empty_line {
1693            prev_non_blank_row.unwrap_or(0)
1694        } else {
1695            row_range.start.saturating_sub(1)
1696        };
1697        let mut prev_row_start = Point::new(prev_row, self.indent_size_for_line(prev_row).len);
1698        Some(row_range.map(move |row| {
1699            let row_start = Point::new(row, self.indent_size_for_line(row).len);
1700
1701            let mut indent_from_prev_row = false;
1702            let mut outdent_from_prev_row = false;
1703            let mut outdent_to_row = u32::MAX;
1704
1705            while let Some((indent_row, delta)) = indent_changes.peek() {
1706                match indent_row.cmp(&row) {
1707                    Ordering::Equal => match delta {
1708                        Ordering::Less => outdent_from_prev_row = true,
1709                        Ordering::Greater => indent_from_prev_row = true,
1710                        _ => {}
1711                    },
1712
1713                    Ordering::Greater => break,
1714                    Ordering::Less => {}
1715                }
1716
1717                indent_changes.next();
1718            }
1719
1720            for range in &indent_ranges {
1721                if range.start.row >= row {
1722                    break;
1723                }
1724                if range.start.row == prev_row && range.end > row_start {
1725                    indent_from_prev_row = true;
1726                }
1727                if range.end > prev_row_start && range.end <= row_start {
1728                    outdent_to_row = outdent_to_row.min(range.start.row);
1729                }
1730            }
1731
1732            let suggestion = if outdent_to_row == prev_row
1733                || (outdent_from_prev_row && indent_from_prev_row)
1734            {
1735                Some(IndentSuggestion {
1736                    basis_row: prev_row,
1737                    delta: Ordering::Equal,
1738                })
1739            } else if indent_from_prev_row {
1740                Some(IndentSuggestion {
1741                    basis_row: prev_row,
1742                    delta: Ordering::Greater,
1743                })
1744            } else if outdent_to_row < prev_row {
1745                Some(IndentSuggestion {
1746                    basis_row: outdent_to_row,
1747                    delta: Ordering::Equal,
1748                })
1749            } else if outdent_from_prev_row {
1750                Some(IndentSuggestion {
1751                    basis_row: prev_row,
1752                    delta: Ordering::Less,
1753                })
1754            } else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
1755            {
1756                Some(IndentSuggestion {
1757                    basis_row: prev_row,
1758                    delta: Ordering::Equal,
1759                })
1760            } else {
1761                None
1762            };
1763
1764            prev_row = row;
1765            prev_row_start = row_start;
1766            suggestion
1767        }))
1768    }
1769
1770    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1771        while row > 0 {
1772            row -= 1;
1773            if !self.is_line_blank(row) {
1774                return Some(row);
1775            }
1776        }
1777        None
1778    }
1779
1780    pub fn chunks<T: ToOffset>(&self, range: Range<T>, language_aware: bool) -> BufferChunks {
1781        let range = range.start.to_offset(self)..range.end.to_offset(self);
1782
1783        let mut syntax = None;
1784        let mut diagnostic_endpoints = Vec::new();
1785        if language_aware {
1786            let captures = self.syntax.captures(range.clone(), &self.text, |grammar| {
1787                grammar.highlights_query.as_ref()
1788            });
1789            let highlight_maps = captures
1790                .grammars()
1791                .into_iter()
1792                .map(|grammar| grammar.highlight_map())
1793                .collect();
1794            syntax = Some((captures, highlight_maps));
1795            for entry in self.diagnostics_in_range::<_, usize>(range.clone(), false) {
1796                diagnostic_endpoints.push(DiagnosticEndpoint {
1797                    offset: entry.range.start,
1798                    is_start: true,
1799                    severity: entry.diagnostic.severity,
1800                    is_unnecessary: entry.diagnostic.is_unnecessary,
1801                });
1802                diagnostic_endpoints.push(DiagnosticEndpoint {
1803                    offset: entry.range.end,
1804                    is_start: false,
1805                    severity: entry.diagnostic.severity,
1806                    is_unnecessary: entry.diagnostic.is_unnecessary,
1807                });
1808            }
1809            diagnostic_endpoints
1810                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1811        }
1812
1813        BufferChunks::new(self.text.as_rope(), range, syntax, diagnostic_endpoints)
1814    }
1815
1816    pub fn for_each_line(&self, range: Range<Point>, mut callback: impl FnMut(u32, &str)) {
1817        let mut line = String::new();
1818        let mut row = range.start.row;
1819        for chunk in self
1820            .as_rope()
1821            .chunks_in_range(range.to_offset(self))
1822            .chain(["\n"])
1823        {
1824            for (newline_ix, text) in chunk.split('\n').enumerate() {
1825                if newline_ix > 0 {
1826                    callback(row, &line);
1827                    row += 1;
1828                    line.clear();
1829                }
1830                line.push_str(text);
1831            }
1832        }
1833    }
1834
1835    pub fn language(&self) -> Option<&Arc<Language>> {
1836        self.language.as_ref()
1837    }
1838
1839    pub fn language_at<D: ToOffset>(&self, position: D) -> Option<&Arc<Language>> {
1840        let offset = position.to_offset(self);
1841        self.syntax
1842            .layers_for_range(offset..offset, &self.text)
1843            .last()
1844            .map(|info| info.language)
1845            .or(self.language.as_ref())
1846    }
1847
1848    pub fn surrounding_word<T: ToOffset>(&self, start: T) -> (Range<usize>, Option<CharKind>) {
1849        let mut start = start.to_offset(self);
1850        let mut end = start;
1851        let mut next_chars = self.chars_at(start).peekable();
1852        let mut prev_chars = self.reversed_chars_at(start).peekable();
1853        let word_kind = cmp::max(
1854            prev_chars.peek().copied().map(char_kind),
1855            next_chars.peek().copied().map(char_kind),
1856        );
1857
1858        for ch in prev_chars {
1859            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1860                start -= ch.len_utf8();
1861            } else {
1862                break;
1863            }
1864        }
1865
1866        for ch in next_chars {
1867            if Some(char_kind(ch)) == word_kind && ch != '\n' {
1868                end += ch.len_utf8();
1869            } else {
1870                break;
1871            }
1872        }
1873
1874        (start..end, word_kind)
1875    }
1876
1877    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1878        let range = range.start.to_offset(self)..range.end.to_offset(self);
1879        let mut result: Option<Range<usize>> = None;
1880        'outer: for layer in self.syntax.layers_for_range(range.clone(), &self.text) {
1881            let mut cursor = layer.node.walk();
1882
1883            // Descend to the first leaf that touches the start of the range,
1884            // and if the range is non-empty, extends beyond the start.
1885            while cursor.goto_first_child_for_byte(range.start).is_some() {
1886                if !range.is_empty() && cursor.node().end_byte() == range.start {
1887                    cursor.goto_next_sibling();
1888                }
1889            }
1890
1891            // Ascend to the smallest ancestor that strictly contains the range.
1892            loop {
1893                let node_range = cursor.node().byte_range();
1894                if node_range.start <= range.start
1895                    && node_range.end >= range.end
1896                    && node_range.len() > range.len()
1897                {
1898                    break;
1899                }
1900                if !cursor.goto_parent() {
1901                    continue 'outer;
1902                }
1903            }
1904
1905            let left_node = cursor.node();
1906            let mut layer_result = left_node.byte_range();
1907
1908            // For an empty range, try to find another node immediately to the right of the range.
1909            if left_node.end_byte() == range.start {
1910                let mut right_node = None;
1911                while !cursor.goto_next_sibling() {
1912                    if !cursor.goto_parent() {
1913                        break;
1914                    }
1915                }
1916
1917                while cursor.node().start_byte() == range.start {
1918                    right_node = Some(cursor.node());
1919                    if !cursor.goto_first_child() {
1920                        break;
1921                    }
1922                }
1923
1924                // If there is a candidate node on both sides of the (empty) range, then
1925                // decide between the two by favoring a named node over an anonymous token.
1926                // If both nodes are the same in that regard, favor the right one.
1927                if let Some(right_node) = right_node {
1928                    if right_node.is_named() || !left_node.is_named() {
1929                        layer_result = right_node.byte_range();
1930                    }
1931                }
1932            }
1933
1934            if let Some(previous_result) = &result {
1935                if previous_result.len() < layer_result.len() {
1936                    continue;
1937                }
1938            }
1939            result = Some(layer_result);
1940        }
1941
1942        result
1943    }
1944
1945    pub fn outline(&self, theme: Option<&SyntaxTheme>) -> Option<Outline<Anchor>> {
1946        self.outline_items_containing(0..self.len(), theme)
1947            .map(Outline::new)
1948    }
1949
1950    pub fn symbols_containing<T: ToOffset>(
1951        &self,
1952        position: T,
1953        theme: Option<&SyntaxTheme>,
1954    ) -> Option<Vec<OutlineItem<Anchor>>> {
1955        let position = position.to_offset(self);
1956        let mut items = self.outline_items_containing(
1957            position.saturating_sub(1)..self.len().min(position + 1),
1958            theme,
1959        )?;
1960        let mut prev_depth = None;
1961        items.retain(|item| {
1962            let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
1963            prev_depth = Some(item.depth);
1964            result
1965        });
1966        Some(items)
1967    }
1968
1969    fn outline_items_containing(
1970        &self,
1971        range: Range<usize>,
1972        theme: Option<&SyntaxTheme>,
1973    ) -> Option<Vec<OutlineItem<Anchor>>> {
1974        let mut matches = self.syntax.matches(range.clone(), &self.text, |grammar| {
1975            grammar.outline_config.as_ref().map(|c| &c.query)
1976        });
1977        let configs = matches
1978            .grammars()
1979            .iter()
1980            .map(|g| g.outline_config.as_ref().unwrap())
1981            .collect::<Vec<_>>();
1982
1983        let mut chunks = self.chunks(0..self.len(), true);
1984        let mut stack = Vec::<Range<usize>>::new();
1985        let mut items = Vec::new();
1986        while let Some(mat) = matches.peek() {
1987            let config = &configs[mat.grammar_index];
1988            let item_node = mat.captures.iter().find_map(|cap| {
1989                if cap.index == config.item_capture_ix {
1990                    Some(cap.node)
1991                } else {
1992                    None
1993                }
1994            })?;
1995
1996            let item_range = item_node.byte_range();
1997            if item_range.end < range.start || item_range.start > range.end {
1998                matches.advance();
1999                continue;
2000            }
2001
2002            // TODO - move later, after processing captures
2003
2004            let mut text = String::new();
2005            let mut name_ranges = Vec::new();
2006            let mut highlight_ranges = Vec::new();
2007            for capture in mat.captures {
2008                let node_is_name;
2009                if capture.index == config.name_capture_ix {
2010                    node_is_name = true;
2011                } else if Some(capture.index) == config.context_capture_ix {
2012                    node_is_name = false;
2013                } else {
2014                    continue;
2015                }
2016
2017                let range = capture.node.start_byte()..capture.node.end_byte();
2018                if !text.is_empty() {
2019                    text.push(' ');
2020                }
2021                if node_is_name {
2022                    let mut start = text.len();
2023                    let end = start + range.len();
2024
2025                    // When multiple names are captured, then the matcheable text
2026                    // includes the whitespace in between the names.
2027                    if !name_ranges.is_empty() {
2028                        start -= 1;
2029                    }
2030
2031                    name_ranges.push(start..end);
2032                }
2033
2034                let mut offset = range.start;
2035                chunks.seek(offset);
2036                for mut chunk in chunks.by_ref() {
2037                    if chunk.text.len() > range.end - offset {
2038                        chunk.text = &chunk.text[0..(range.end - offset)];
2039                        offset = range.end;
2040                    } else {
2041                        offset += chunk.text.len();
2042                    }
2043                    let style = chunk
2044                        .syntax_highlight_id
2045                        .zip(theme)
2046                        .and_then(|(highlight, theme)| highlight.style(theme));
2047                    if let Some(style) = style {
2048                        let start = text.len();
2049                        let end = start + chunk.text.len();
2050                        highlight_ranges.push((start..end, style));
2051                    }
2052                    text.push_str(chunk.text);
2053                    if offset >= range.end {
2054                        break;
2055                    }
2056                }
2057            }
2058
2059            matches.advance();
2060            while stack.last().map_or(false, |prev_range| {
2061                prev_range.start > item_range.start || prev_range.end < item_range.end
2062            }) {
2063                stack.pop();
2064            }
2065            stack.push(item_range.clone());
2066
2067            items.push(OutlineItem {
2068                depth: stack.len() - 1,
2069                range: self.anchor_after(item_range.start)..self.anchor_before(item_range.end),
2070                text,
2071                highlight_ranges,
2072                name_ranges,
2073            })
2074        }
2075        Some(items)
2076    }
2077
2078    pub fn enclosing_bracket_ranges<T: ToOffset>(
2079        &self,
2080        range: Range<T>,
2081    ) -> Option<(Range<usize>, Range<usize>)> {
2082        // Find bracket pairs that *inclusively* contain the given range.
2083        let range = range.start.to_offset(self).saturating_sub(1)
2084            ..self.len().min(range.end.to_offset(self) + 1);
2085        let mut matches = self.syntax.matches(range, &self.text, |grammar| {
2086            grammar.brackets_config.as_ref().map(|c| &c.query)
2087        });
2088        let configs = matches
2089            .grammars()
2090            .iter()
2091            .map(|grammar| grammar.brackets_config.as_ref().unwrap())
2092            .collect::<Vec<_>>();
2093
2094        // Get the ranges of the innermost pair of brackets.
2095        let mut result: Option<(Range<usize>, Range<usize>)> = None;
2096        while let Some(mat) = matches.peek() {
2097            let mut open = None;
2098            let mut close = None;
2099            let config = &configs[mat.grammar_index];
2100            for capture in mat.captures {
2101                if capture.index == config.open_capture_ix {
2102                    open = Some(capture.node.byte_range());
2103                } else if capture.index == config.close_capture_ix {
2104                    close = Some(capture.node.byte_range());
2105                }
2106            }
2107
2108            matches.advance();
2109
2110            if let Some((open, close)) = open.zip(close) {
2111                let len = close.end - open.start;
2112
2113                if let Some((existing_open, existing_close)) = &result {
2114                    let existing_len = existing_close.end - existing_open.start;
2115                    if len > existing_len {
2116                        continue;
2117                    }
2118                }
2119
2120                result = Some((open, close));
2121            }
2122        }
2123
2124        result
2125    }
2126
2127    #[allow(clippy::type_complexity)]
2128    pub fn remote_selections_in_range(
2129        &self,
2130        range: Range<Anchor>,
2131    ) -> impl Iterator<
2132        Item = (
2133            ReplicaId,
2134            bool,
2135            impl Iterator<Item = &Selection<Anchor>> + '_,
2136        ),
2137    > + '_ {
2138        self.remote_selections
2139            .iter()
2140            .filter(|(replica_id, set)| {
2141                **replica_id != self.text.replica_id() && !set.selections.is_empty()
2142            })
2143            .map(move |(replica_id, set)| {
2144                let start_ix = match set.selections.binary_search_by(|probe| {
2145                    probe.end.cmp(&range.start, self).then(Ordering::Greater)
2146                }) {
2147                    Ok(ix) | Err(ix) => ix,
2148                };
2149                let end_ix = match set.selections.binary_search_by(|probe| {
2150                    probe.start.cmp(&range.end, self).then(Ordering::Less)
2151                }) {
2152                    Ok(ix) | Err(ix) => ix,
2153                };
2154
2155                (
2156                    *replica_id,
2157                    set.line_mode,
2158                    set.selections[start_ix..end_ix].iter(),
2159                )
2160            })
2161    }
2162
2163    pub fn diagnostics_in_range<'a, T, O>(
2164        &'a self,
2165        search_range: Range<T>,
2166        reversed: bool,
2167    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2168    where
2169        T: 'a + Clone + ToOffset,
2170        O: 'a + FromAnchor,
2171    {
2172        self.diagnostics.range(search_range, self, true, reversed)
2173    }
2174
2175    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
2176        let mut groups = Vec::new();
2177        self.diagnostics.groups(&mut groups, self);
2178        groups
2179    }
2180
2181    pub fn diagnostic_group<'a, O>(
2182        &'a self,
2183        group_id: usize,
2184    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
2185    where
2186        O: 'a + FromAnchor,
2187    {
2188        self.diagnostics.group(group_id, self)
2189    }
2190
2191    pub fn diagnostics_update_count(&self) -> usize {
2192        self.diagnostics_update_count
2193    }
2194
2195    pub fn parse_count(&self) -> usize {
2196        self.parse_count
2197    }
2198
2199    pub fn selections_update_count(&self) -> usize {
2200        self.selections_update_count
2201    }
2202
2203    pub fn file(&self) -> Option<&dyn File> {
2204        self.file.as_deref()
2205    }
2206
2207    pub fn file_update_count(&self) -> usize {
2208        self.file_update_count
2209    }
2210}
2211
2212pub fn indent_size_for_line(text: &text::BufferSnapshot, row: u32) -> IndentSize {
2213    indent_size_for_text(text.chars_at(Point::new(row, 0)))
2214}
2215
2216pub fn indent_size_for_text(text: impl Iterator<Item = char>) -> IndentSize {
2217    let mut result = IndentSize::spaces(0);
2218    for c in text {
2219        let kind = match c {
2220            ' ' => IndentKind::Space,
2221            '\t' => IndentKind::Tab,
2222            _ => break,
2223        };
2224        if result.len == 0 {
2225            result.kind = kind;
2226        }
2227        result.len += 1;
2228    }
2229    result
2230}
2231
2232impl Clone for BufferSnapshot {
2233    fn clone(&self) -> Self {
2234        Self {
2235            text: self.text.clone(),
2236            syntax: self.syntax.clone(),
2237            file: self.file.clone(),
2238            remote_selections: self.remote_selections.clone(),
2239            diagnostics: self.diagnostics.clone(),
2240            selections_update_count: self.selections_update_count,
2241            diagnostics_update_count: self.diagnostics_update_count,
2242            file_update_count: self.file_update_count,
2243            language: self.language.clone(),
2244            parse_count: self.parse_count,
2245        }
2246    }
2247}
2248
2249impl Deref for BufferSnapshot {
2250    type Target = text::BufferSnapshot;
2251
2252    fn deref(&self) -> &Self::Target {
2253        &self.text
2254    }
2255}
2256
2257unsafe impl<'a> Send for BufferChunks<'a> {}
2258
2259impl<'a> BufferChunks<'a> {
2260    pub(crate) fn new(
2261        text: &'a Rope,
2262        range: Range<usize>,
2263        syntax: Option<(SyntaxMapCaptures<'a>, Vec<HighlightMap>)>,
2264        diagnostic_endpoints: Vec<DiagnosticEndpoint>,
2265    ) -> Self {
2266        let mut highlights = None;
2267        if let Some((captures, highlight_maps)) = syntax {
2268            highlights = Some(BufferChunkHighlights {
2269                captures,
2270                next_capture: None,
2271                stack: Default::default(),
2272                highlight_maps,
2273            })
2274        }
2275
2276        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
2277        let chunks = text.chunks_in_range(range.clone());
2278
2279        BufferChunks {
2280            range,
2281            chunks,
2282            diagnostic_endpoints,
2283            error_depth: 0,
2284            warning_depth: 0,
2285            information_depth: 0,
2286            hint_depth: 0,
2287            unnecessary_depth: 0,
2288            highlights,
2289        }
2290    }
2291
2292    pub fn seek(&mut self, offset: usize) {
2293        self.range.start = offset;
2294        self.chunks.seek(self.range.start);
2295        if let Some(highlights) = self.highlights.as_mut() {
2296            highlights
2297                .stack
2298                .retain(|(end_offset, _)| *end_offset > offset);
2299            if let Some(capture) = &highlights.next_capture {
2300                if offset >= capture.node.start_byte() {
2301                    let next_capture_end = capture.node.end_byte();
2302                    if offset < next_capture_end {
2303                        highlights.stack.push((
2304                            next_capture_end,
2305                            highlights.highlight_maps[capture.grammar_index].get(capture.index),
2306                        ));
2307                    }
2308                    highlights.next_capture.take();
2309                }
2310            }
2311            highlights.captures.set_byte_range(self.range.clone());
2312        }
2313    }
2314
2315    pub fn offset(&self) -> usize {
2316        self.range.start
2317    }
2318
2319    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
2320        let depth = match endpoint.severity {
2321            DiagnosticSeverity::ERROR => &mut self.error_depth,
2322            DiagnosticSeverity::WARNING => &mut self.warning_depth,
2323            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
2324            DiagnosticSeverity::HINT => &mut self.hint_depth,
2325            _ => return,
2326        };
2327        if endpoint.is_start {
2328            *depth += 1;
2329        } else {
2330            *depth -= 1;
2331        }
2332
2333        if endpoint.is_unnecessary {
2334            if endpoint.is_start {
2335                self.unnecessary_depth += 1;
2336            } else {
2337                self.unnecessary_depth -= 1;
2338            }
2339        }
2340    }
2341
2342    fn current_diagnostic_severity(&self) -> Option<DiagnosticSeverity> {
2343        if self.error_depth > 0 {
2344            Some(DiagnosticSeverity::ERROR)
2345        } else if self.warning_depth > 0 {
2346            Some(DiagnosticSeverity::WARNING)
2347        } else if self.information_depth > 0 {
2348            Some(DiagnosticSeverity::INFORMATION)
2349        } else if self.hint_depth > 0 {
2350            Some(DiagnosticSeverity::HINT)
2351        } else {
2352            None
2353        }
2354    }
2355
2356    fn current_code_is_unnecessary(&self) -> bool {
2357        self.unnecessary_depth > 0
2358    }
2359}
2360
2361impl<'a> Iterator for BufferChunks<'a> {
2362    type Item = Chunk<'a>;
2363
2364    fn next(&mut self) -> Option<Self::Item> {
2365        let mut next_capture_start = usize::MAX;
2366        let mut next_diagnostic_endpoint = usize::MAX;
2367
2368        if let Some(highlights) = self.highlights.as_mut() {
2369            while let Some((parent_capture_end, _)) = highlights.stack.last() {
2370                if *parent_capture_end <= self.range.start {
2371                    highlights.stack.pop();
2372                } else {
2373                    break;
2374                }
2375            }
2376
2377            if highlights.next_capture.is_none() {
2378                highlights.next_capture = highlights.captures.next();
2379            }
2380
2381            while let Some(capture) = highlights.next_capture.as_ref() {
2382                if self.range.start < capture.node.start_byte() {
2383                    next_capture_start = capture.node.start_byte();
2384                    break;
2385                } else {
2386                    let highlight_id =
2387                        highlights.highlight_maps[capture.grammar_index].get(capture.index);
2388                    highlights
2389                        .stack
2390                        .push((capture.node.end_byte(), highlight_id));
2391                    highlights.next_capture = highlights.captures.next();
2392                }
2393            }
2394        }
2395
2396        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2397            if endpoint.offset <= self.range.start {
2398                self.update_diagnostic_depths(endpoint);
2399                self.diagnostic_endpoints.next();
2400            } else {
2401                next_diagnostic_endpoint = endpoint.offset;
2402                break;
2403            }
2404        }
2405
2406        if let Some(chunk) = self.chunks.peek() {
2407            let chunk_start = self.range.start;
2408            let mut chunk_end = (self.chunks.offset() + chunk.len())
2409                .min(next_capture_start)
2410                .min(next_diagnostic_endpoint);
2411            let mut highlight_id = None;
2412            if let Some(highlights) = self.highlights.as_ref() {
2413                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2414                    chunk_end = chunk_end.min(*parent_capture_end);
2415                    highlight_id = Some(*parent_highlight_id);
2416                }
2417            }
2418
2419            let slice =
2420                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2421            self.range.start = chunk_end;
2422            if self.range.start == self.chunks.offset() + chunk.len() {
2423                self.chunks.next().unwrap();
2424            }
2425
2426            Some(Chunk {
2427                text: slice,
2428                syntax_highlight_id: highlight_id,
2429                highlight_style: None,
2430                diagnostic_severity: self.current_diagnostic_severity(),
2431                is_unnecessary: self.current_code_is_unnecessary(),
2432            })
2433        } else {
2434            None
2435        }
2436    }
2437}
2438
2439impl operation_queue::Operation for Operation {
2440    fn lamport_timestamp(&self) -> clock::Lamport {
2441        match self {
2442            Operation::Buffer(_) => {
2443                unreachable!("buffer operations should never be deferred at this layer")
2444            }
2445            Operation::UpdateDiagnostics {
2446                lamport_timestamp, ..
2447            }
2448            | Operation::UpdateSelections {
2449                lamport_timestamp, ..
2450            }
2451            | Operation::UpdateCompletionTriggers {
2452                lamport_timestamp, ..
2453            } => *lamport_timestamp,
2454        }
2455    }
2456}
2457
2458impl Default for Diagnostic {
2459    fn default() -> Self {
2460        Self {
2461            code: None,
2462            severity: DiagnosticSeverity::ERROR,
2463            message: Default::default(),
2464            group_id: 0,
2465            is_primary: false,
2466            is_valid: true,
2467            is_disk_based: false,
2468            is_unnecessary: false,
2469        }
2470    }
2471}
2472
2473impl IndentSize {
2474    pub fn spaces(len: u32) -> Self {
2475        Self {
2476            len,
2477            kind: IndentKind::Space,
2478        }
2479    }
2480
2481    pub fn tab() -> Self {
2482        Self {
2483            len: 1,
2484            kind: IndentKind::Tab,
2485        }
2486    }
2487
2488    pub fn chars(&self) -> impl Iterator<Item = char> {
2489        iter::repeat(self.char()).take(self.len as usize)
2490    }
2491
2492    pub fn char(&self) -> char {
2493        match self.kind {
2494            IndentKind::Space => ' ',
2495            IndentKind::Tab => '\t',
2496        }
2497    }
2498
2499    pub fn with_delta(mut self, direction: Ordering, size: IndentSize) -> Self {
2500        match direction {
2501            Ordering::Less => {
2502                if self.kind == size.kind && self.len >= size.len {
2503                    self.len -= size.len;
2504                }
2505            }
2506            Ordering::Equal => {}
2507            Ordering::Greater => {
2508                if self.len == 0 {
2509                    self = size;
2510                } else if self.kind == size.kind {
2511                    self.len += size.len;
2512                }
2513            }
2514        }
2515        self
2516    }
2517}
2518
2519impl Completion {
2520    pub fn sort_key(&self) -> (usize, &str) {
2521        let kind_key = match self.lsp_completion.kind {
2522            Some(lsp::CompletionItemKind::VARIABLE) => 0,
2523            _ => 1,
2524        };
2525        (kind_key, &self.label.text[self.label.filter_range.clone()])
2526    }
2527
2528    pub fn is_snippet(&self) -> bool {
2529        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
2530    }
2531}
2532
2533pub fn contiguous_ranges(
2534    values: impl Iterator<Item = u32>,
2535    max_len: usize,
2536) -> impl Iterator<Item = Range<u32>> {
2537    let mut values = values;
2538    let mut current_range: Option<Range<u32>> = None;
2539    std::iter::from_fn(move || loop {
2540        if let Some(value) = values.next() {
2541            if let Some(range) = &mut current_range {
2542                if value == range.end && range.len() < max_len {
2543                    range.end += 1;
2544                    continue;
2545                }
2546            }
2547
2548            let prev_range = current_range.clone();
2549            current_range = Some(value..(value + 1));
2550            if prev_range.is_some() {
2551                return prev_range;
2552            }
2553        } else {
2554            return current_range.take();
2555        }
2556    })
2557}
2558
2559pub fn char_kind(c: char) -> CharKind {
2560    if c.is_whitespace() {
2561        CharKind::Whitespace
2562    } else if c.is_alphanumeric() || c == '_' {
2563        CharKind::Word
2564    } else {
2565        CharKind::Punctuation
2566    }
2567}