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