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