buffer.rs

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