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