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