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