buffer.rs

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