buffer.rs

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