buffer.rs

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